Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add isCanvas into app host context #3170

Merged
merged 4 commits into from
Feb 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions packages/toolpad-app/src/canvas/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { throttle } from 'lodash-es';
import { CanvasEventsContext } from '@mui/toolpad-core/runtime';
import { FlowDirection, SlotType } from '@mui/toolpad-core';
import { update } from '@mui/toolpad-utils/immutability';
import ToolpadApp, { IS_RENDERED_IN_CANVAS } from '../runtime/ToolpadApp';
import { useNonNullableContext } from '@mui/toolpad-utils/react';
import ToolpadApp from '../runtime/ToolpadApp';
import { queryClient } from '../runtime/api';
import { AppCanvasState, NodeInfo, PageViewState, SlotsState } from '../types';
import {
Expand All @@ -14,6 +15,7 @@ import {
} from '../utils/geometry';
import { CanvasHooks, CanvasHooksContext } from '../runtime/CanvasHooksContext';
import { ToolpadBridge, bridge, setCommandHandler } from './ToolpadBridge';
import { AppHostContext } from '../runtime/AppHostContext';

const handleScreenUpdate = throttle(
() => {
Expand Down Expand Up @@ -80,7 +82,7 @@ export interface AppCanvasProps {

export default function AppCanvas({ basename, state: initialState }: AppCanvasProps) {
const [state, setState] = React.useState<AppCanvasState>(initialState);
const [readyBridge, setReadyBridge] = React.useState<ToolpadBridge>();
const [readyBridge, setReadyBridge] = React.useState<ToolpadBridge | undefined>();

const appRootRef = React.useRef<HTMLDivElement>();
const appRootCleanupRef = React.useRef<() => void>();
Expand Down Expand Up @@ -202,7 +204,9 @@ export default function AppCanvas({ basename, state: initialState }: AppCanvasPr
};
}, [savedNodes]);

if (IS_RENDERED_IN_CANVAS) {
const appHost = useNonNullableContext(AppHostContext);

if (appHost.isCanvas) {
return readyBridge ? (
<CanvasHooksContext.Provider value={editorHooks}>
<CanvasEventsContext.Provider value={readyBridge.canvasEvents}>
Expand Down
1 change: 1 addition & 0 deletions packages/toolpad-app/src/runtime/AppHostContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as React from 'react';
export interface AppHost {
isPreview: boolean;
isCustomServer: boolean;
isCanvas: boolean;
}

export const AppHostContext = React.createContext<AppHost | null>(null);
2 changes: 1 addition & 1 deletion packages/toolpad-app/src/runtime/ToolpadApp.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ afterEach(cleanup);
const waitFor: typeof waitForOrig = (waiter, options) =>
waitForOrig(waiter, { timeout: 10000, ...options });

const appHost: AppHost = { isPreview: false, isCustomServer: false };
const appHost: AppHost = { isPreview: false, isCustomServer: false, isCanvas: false };

function renderPage(
initPage: (dom: appDom.AppDom, page: appDom.PageNode) => appDom.AppDom,
Expand Down
23 changes: 11 additions & 12 deletions packages/toolpad-app/src/runtime/ToolpadApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,14 @@ import { mapProperties, mapValues } from '@mui/toolpad-utils/collections';
import { set as setObjectPath } from 'lodash-es';
import { QueryClientProvider, useMutation } from '@tanstack/react-query';
import {
BrowserRouter,
Routes,
Route,
useLocation,
Navigate,
Location as RouterLocation,
useNavigate,
useMatch,
BrowserRouter,
} from 'react-router-dom';
import { ErrorBoundary, FallbackProps } from 'react-error-boundary';
import {
Expand Down Expand Up @@ -99,11 +99,6 @@ import { AppHostContext } from './AppHostContext';

const browserJsRuntime = getBrowserRuntime();

export const IS_RENDERED_IN_CANVAS =
typeof window === 'undefined'
? false
: !!(window.frameElement as HTMLIFrameElement)?.dataset?.toolpadCanvas;

export type PageComponents = Partial<Record<string, React.ComponentType>>;

export const componentsStore = createGlobalState<ToolpadComponents>({});
Expand Down Expand Up @@ -1484,6 +1479,8 @@ function RenderedPages({ pages, defaultPage }: RenderedPagesProps) {

const defaultPageNavigation = <Navigate to={`/pages/${defaultPage.name}${search}`} replace />;

const appHost = useNonNullableContext(AppHostContext);

return (
<Routes>
{pages.map((page) => {
Expand All @@ -1496,7 +1493,7 @@ function RenderedPages({ pages, defaultPage }: RenderedPagesProps) {
/>
);

if (!IS_RENDERED_IN_CANVAS) {
if (!appHost.isCanvas) {
pageContent = (
<RequireAuthorization
allowAll={page.attributes.authorization?.allowAll ?? true}
Expand Down Expand Up @@ -1583,16 +1580,18 @@ function ToolpadAppLayout({ dom, basename, clipped }: ToolpadAppLayoutProps) {
[authFilteredPages],
);

if (!IS_RENDERED_IN_CANVAS && !session?.user && hasAuthentication) {
const appHost = useNonNullableContext(AppHostContext);

if (!appHost.isCanvas && !session?.user && hasAuthentication) {
return <AppLoading />;
}

return (
<AppLayout
activePageSlug={activePageSlug}
pages={navEntries}
hasNavigation={!IS_RENDERED_IN_CANVAS}
hasHeader={hasAuthentication && !IS_RENDERED_IN_CANVAS}
hasNavigation={!appHost.isCanvas}
hasHeader={hasAuthentication && !appHost.isCanvas}
clipped={clipped}
basename={basename}
>
Expand Down Expand Up @@ -1627,10 +1626,10 @@ export default function ToolpadApp({ rootRef, basename, state }: ToolpadAppProps
(window as any).toggleDevtools = () => toggleDevtools();
}, [toggleDevtools]);

const authContext = useAuth({ dom, basename, isRenderedInCanvas: IS_RENDERED_IN_CANVAS });
const authContext = useAuth({ dom, basename });

const appHost = useNonNullableContext(AppHostContext);
const showPreviewHeader: boolean = !!appHost?.isPreview && !IS_RENDERED_IN_CANVAS;
const showPreviewHeader: boolean = !!appHost.isPreview && !appHost.isCanvas;

return (
<BrowserRouter basename={basename}>
Expand Down
9 changes: 7 additions & 2 deletions packages/toolpad-app/src/runtime/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,14 @@ import RuntimeToolpadApp, {
pageComponentsStore,
} from './ToolpadApp';
import { RuntimeState } from './types';
import { AppHostContext } from './AppHostContext';
import { AppHost, AppHostContext } from './AppHostContext';

const IS_PREVIEW = process.env.NODE_ENV !== 'production';
const IS_CUSTOM_SERVER = process.env.TOOLPAD_CUSTOM_SERVER === 'true';
const IS_RENDERED_IN_CANVAS =
typeof window === 'undefined'
? false
: !!(window.frameElement as HTMLIFrameElement)?.dataset?.toolpadCanvas;

const cache = createCache({
key: 'css',
Expand All @@ -43,9 +47,10 @@ export interface RootProps {
ToolpadApp: React.ComponentType<ToolpadAppProps>;
}

const appHost = {
const appHost: AppHost = {
isPreview: IS_PREVIEW,
isCustomServer: IS_CUSTOM_SERVER,
isCanvas: IS_RENDERED_IN_CANVAS,
};

function Root({ ToolpadApp, initialState, base }: RootProps) {
Expand Down
11 changes: 7 additions & 4 deletions packages/toolpad-app/src/runtime/useAuth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import * as React from 'react';
import * as appDom from '@mui/toolpad-core/appDom';
import { useNonNullableContext } from '@mui/toolpad-utils/react';
import { AppHostContext } from './AppHostContext';

const AUTH_API_PATH = '/api/auth';

Expand Down Expand Up @@ -46,10 +48,9 @@ export const AuthContext = React.createContext<AuthPayload>({
interface UseAuthInput {
dom: appDom.RenderTree;
basename: string;
isRenderedInCanvas?: boolean;
}

export function useAuth({ dom, basename, isRenderedInCanvas = true }: UseAuthInput): AuthPayload {
export function useAuth({ dom, basename }: UseAuthInput): AuthPayload {
const authProviders = React.useMemo(() => {
const app = appDom.getApp(dom);
const authProviderConfigs = app.attributes.authentication?.providers ?? [];
Expand Down Expand Up @@ -157,11 +158,13 @@ export function useAuth({ dom, basename, isRenderedInCanvas = true }: UseAuthInp
[basename, getCsrfToken, signOut],
);

const appHost = useNonNullableContext(AppHostContext);

React.useEffect(() => {
if (!isRenderedInCanvas && hasAuthentication) {
if (hasAuthentication && !appHost.isCanvas) {
getSession();
}
}, [getCsrfToken, getSession, hasAuthentication, isRenderedInCanvas]);
}, [getCsrfToken, getSession, hasAuthentication, appHost.isCanvas]);

return {
session,
Expand Down
Loading