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

Unify preview and canvas entrypoints #2760

Merged
merged 22 commits into from
Oct 10, 2023
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
55 changes: 30 additions & 25 deletions packages/toolpad-app/src/canvas/ToolpadBridge.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,7 @@ export function setCommandHandler<T extends Record<string, Function>, K extends
name: K,
handler: T[K],
) {
if (typeof commands[COMMAND_HANDLERS][name] !== 'undefined') {
throw new Error(`"${name}" is already handled`);
}
commands[COMMAND_HANDLERS][name] = handler;
return () => {
delete commands[COMMAND_HANDLERS][name];
};
}

// Interface to communicate between editor and canvas
Expand All @@ -69,34 +63,45 @@ export interface ToolpadBridge {
invalidateQueries(): void;
}>;
}

if (
const isRenderedInCanvas =
typeof window !== 'undefined' &&
process.env.NODE_ENV !== 'test' &&
!(window.frameElement as HTMLIFrameElement | null)?.dataset.toolpadCanvas
) {
throw new Error(
'An attempt was made at setting up the canvas bridge outside of the canvas. Was this file imported unintentionally?',
);
}
(window.frameElement as HTMLIFrameElement | null)?.dataset.toolpadCanvas;

let canvasIsReady = false;
export const bridge: ToolpadBridge = {
editorEvents: new Emitter(),
editorCommands: createCommands(),
canvasEvents: new Emitter(),
canvasCommands: createCommands({
isReady: () => canvasIsReady,
}),
} as ToolpadBridge;

bridge.canvasEvents.on('ready', () => {
const bridge: ToolpadBridge | null = isRenderedInCanvas
? ({
editorEvents: new Emitter(),
editorCommands: createCommands(),
canvasEvents: new Emitter(),
canvasCommands: createCommands({
isReady: () => canvasIsReady,
getPageViewState: () => {
throw new Error('Not implemented');
},
getViewCoordinates: () => {
throw new Error('Not implemented');
},
invalidateQueries: () => {
throw new Error('Not implemented');
},
update: () => {
throw new Error('Not implemented');
},
}),
} satisfies ToolpadBridge)
: null;

bridge?.canvasEvents.on('ready', () => {
canvasIsReady = true;
});

if (typeof window !== 'undefined') {
if (bridge) {
if (typeof window[TOOLPAD_BRIDGE_GLOBAL] === 'function') {
window[TOOLPAD_BRIDGE_GLOBAL](bridge);
}

window[TOOLPAD_BRIDGE_GLOBAL] = bridge;
}

export { bridge };
94 changes: 38 additions & 56 deletions packages/toolpad-app/src/canvas/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,28 +10,27 @@ import getPageViewState from './getPageViewState';
import { rectContainsPoint } from '../utils/geometry';
import { CanvasHooks, CanvasHooksContext } from '../runtime/CanvasHooksContext';
import { bridge, setCommandHandler } from './ToolpadBridge';
import { BridgeContext } from './BridgeContext';

const handleScreenUpdate = throttle(
() => {
bridge.canvasEvents.emit('screenUpdate', {});
bridge?.canvasEvents.emit('screenUpdate', {});
},
50,
{ trailing: true },
);

export interface AppCanvasProps {
initialState?: AppCanvasState | null;
state: AppCanvasState;
basename: string;
extraComponents: ToolpadComponents;
}

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

const appRootRef = React.useRef<HTMLDivElement>();
const appRootCleanupRef = React.useRef<() => void>();
Expand Down Expand Up @@ -83,31 +82,27 @@ export default function AppCanvas({
});

React.useEffect(() => {
const unsetGetPageViewState = setCommandHandler(
bridge.canvasCommands,
'getPageViewState',
() => {
invariant(appRootRef.current, 'App ref not attached');
return getPageViewState(appRootRef.current);
},
);

const unsetGetViewCoordinates = setCommandHandler(
bridge.canvasCommands,
'getViewCoordinates',
(clientX, clientY) => {
if (!appRootRef.current) {
return null;
}
const rect = appRootRef.current.getBoundingClientRect();
if (rectContainsPoint(rect, clientX, clientY)) {
return { x: clientX - rect.x, y: clientY - rect.y };
}
if (!bridge) {
return;
}

setCommandHandler(bridge.canvasCommands, 'getPageViewState', () => {
invariant(appRootRef.current, 'App ref not attached');
return getPageViewState(appRootRef.current);
});

setCommandHandler(bridge.canvasCommands, 'getViewCoordinates', (clientX, clientY) => {
if (!appRootRef.current) {
return null;
},
);
}
const rect = appRootRef.current.getBoundingClientRect();
if (rectContainsPoint(rect, clientX, clientY)) {
return { x: clientX - rect.x, y: clientY - rect.y };
}
return null;
});

const unsetUpdate = setCommandHandler(bridge.canvasCommands, 'update', (newState) => {
setCommandHandler(bridge.canvasCommands, 'update', (newState) => {
// `update` will be called from the parent window. Since the canvas runs in an iframe, it's
// running in another javascript realm than the one this object was constructed in. This makes
// the MUI core `deepMerge` function fail. The `deepMerge` function uses `isPlainObject` which checks
Expand All @@ -120,22 +115,11 @@ export default function AppCanvas({
React.startTransition(() => setState(structuredClone(newState)));
});

const unsetInvalidateQueries = setCommandHandler(
bridge.canvasCommands,
'invalidateQueries',
() => {
queryClient.invalidateQueries();
},
);
setCommandHandler(bridge.canvasCommands, 'invalidateQueries', () => {
queryClient.invalidateQueries();
});

bridge.canvasEvents.emit('ready', {});

return () => {
unsetGetPageViewState();
unsetGetViewCoordinates();
unsetUpdate();
unsetInvalidateQueries();
};
}, []);

const savedNodes = state?.savedNodes;
Expand All @@ -145,18 +129,16 @@ export default function AppCanvas({
};
}, [savedNodes]);

return state ? (
<BridgeContext.Provider value={bridge}>
<CanvasHooksContext.Provider value={editorHooks}>
<CanvasEventsContext.Provider value={bridge.canvasEvents}>
<ToolpadApp
rootRef={onAppRoot}
extraComponents={extraComponents}
basename={basename}
state={state}
/>
</CanvasEventsContext.Provider>
</CanvasHooksContext.Provider>
</BridgeContext.Provider>
) : null;
return (
<CanvasHooksContext.Provider value={editorHooks}>
<CanvasEventsContext.Provider value={bridge?.canvasEvents || null}>
<ToolpadApp
rootRef={onAppRoot}
extraComponents={extraComponents}
basename={basename}
state={state}
/>
</CanvasEventsContext.Provider>
</CanvasHooksContext.Provider>
);
}
5 changes: 1 addition & 4 deletions packages/toolpad-app/src/server/appServerWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,10 @@ function devServerPlugin({ config }: ToolpadAppDevServerParams): Plugin {
return () => {
viteServer.middlewares.use('/', async (req, res, next) => {
invariant(req.url, 'request must have a url');
const url = new URL(req.url, 'http://x');
const canvas = url.searchParams.get('toolpad-display') === 'canvas';

try {
const dom = await loadDom();

const template = getHtmlContent({ canvas });
const template = getHtmlContent({ canvas: true });

let html = await viteServer.transformIndexHtml(req.url, template);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ export default function EditorCanvasHost({
}
});

const src = `${base}/pages/${pageNodeId}?toolpad-display=canvas`;
const src = `${base}/pages/${pageNodeId}`;

const [loading, setLoading] = React.useState(true);
useOnChange(src, () => setLoading(true));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1158,7 +1158,6 @@ export default function RenderOverlay({ bridge }: RenderOverlayProps) {
}, [handleNodeDragEnd]);

const resizePreviewElementRef = React.useRef<HTMLDivElement | null>(null);
const resizePreviewElement = resizePreviewElementRef.current;

const overlayGridRef = React.useRef<OverlayGridHandle>({
gridElement: null,
Expand All @@ -1173,6 +1172,7 @@ export default function RenderOverlay({ bridge }: RenderOverlayProps) {
return;
}

const resizePreviewElement = resizePreviewElementRef.current;
const draggedNodeInfo = nodesInfo[draggedNode.id];
const draggedNodeRect = draggedNodeInfo?.rect;

Expand Down Expand Up @@ -1253,7 +1253,7 @@ export default function RenderOverlay({ bridge }: RenderOverlayProps) {
}
}
},
[bridge, dom, draggedEdge, draggedNode, nodesInfo, resizePreviewElement],
[bridge, dom, draggedEdge, draggedNode, nodesInfo],
);

const handleEdgeDragEnd = React.useCallback(
Expand All @@ -1267,6 +1267,7 @@ export default function RenderOverlay({ bridge }: RenderOverlayProps) {
const draggedNodeInfo = nodesInfo[draggedNode.id];
const draggedNodeRect = draggedNodeInfo?.rect;

const resizePreviewElement = resizePreviewElementRef.current;
const resizePreviewRect = resizePreviewElement?.getBoundingClientRect();

if (draggedNodeRect && resizePreviewRect) {
Expand Down Expand Up @@ -1364,7 +1365,7 @@ export default function RenderOverlay({ bridge }: RenderOverlayProps) {

api.dragEnd();
},
[api, domApi, draggedEdge, draggedNode, nodesInfo, resizePreviewElement],
[api, domApi, draggedEdge, draggedNode, nodesInfo],
);

return (
Expand Down
Loading