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

Simplify interaction between canvas and editor #858

Merged
merged 9 commits into from
Aug 30, 2022
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
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { FiberNode, Hook } from 'react-devtools-inline';
import { NodeId, RUNTIME_PROP_NODE_ID, RUNTIME_PROP_SLOTS, SlotType } from '@mui/toolpad-core';
import { NodeFiberHostProps } from '@mui/toolpad-core/runtime';
import { PageViewState, NodesInfo, NodeInfo, FlowDirection } from './types';
import { getRelativeBoundingRect, getRelativeOuterRect } from './utils/geometry';
import { PageViewState, NodesInfo, NodeInfo, FlowDirection } from '../types';
import { getRelativeBoundingRect, getRelativeOuterRect } from '../utils/geometry';

declare global {
interface Window {
Expand Down Expand Up @@ -130,6 +130,6 @@ export function getNodesViewInfo(rootElm: HTMLElement): {
return { nodes };
}

export function getPageViewState(rootElm: HTMLElement): PageViewState {
export default function getPageViewState(rootElm: HTMLElement): PageViewState {
return getNodesViewInfo(rootElm);
}
86 changes: 70 additions & 16 deletions packages/toolpad-app/src/canvas/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import * as React from 'react';
import { fireEvent } from '@mui/toolpad-core/runtime';
import invariant from 'invariant';
import { throttle } from 'lodash-es';
import ToolpadApp, { CanvasHooks, CanvasHooksContext } from '../runtime';
import * as appDom from '../appDom';
import { PageViewState } from '../types';
import getPageViewState from './getPageViewState';
import { rectContainsPoint } from '../utils/geometry';

export interface AppCanvasState {
appId: string;
Expand All @@ -10,12 +15,13 @@ export interface AppCanvasState {

export interface ToolpadBridge {
update(updates: AppCanvasState): void;
getViewCoordinates(clientX: number, clientY: number): { x: number; y: number } | null;
getPageViewState(): PageViewState;
}

declare global {
interface Window {
__TOOLPAD_READY__?: boolean | (() => void);
__TOOLPAD_BRIDGE__?: ToolpadBridge;
__TOOLPAD_BRIDGE__?: ToolpadBridge | ((bridge: ToolpadBridge) => void);
}
}

Expand All @@ -26,33 +32,80 @@ export interface AppCanvasProps {
export default function AppCanvas({ basename }: AppCanvasProps) {
const [state, setState] = React.useState<AppCanvasState | null>(null);

const rootRef = React.useRef<HTMLDivElement>();

const [appRoot, setAppRoot] = React.useState<HTMLDivElement | null>(null);

React.useEffect(() => {
// eslint-disable-next-line no-underscore-dangle
window.__TOOLPAD_BRIDGE__ = {
if (!appRoot) {
return () => {};
}

rootRef.current = appRoot;

const onScreenUpdate = () => fireEvent({ type: 'screenUpdate' });

const handleScreenUpdateThrottled = throttle(onScreenUpdate, 50, {
trailing: true,
});

const mutationObserver = new MutationObserver(handleScreenUpdateThrottled);

mutationObserver.observe(appRoot, {
attributes: true,
childList: true,
subtree: true,
characterData: true,
});

const resizeObserver = new ResizeObserver(handleScreenUpdateThrottled);

resizeObserver.observe(appRoot);
appRoot.querySelectorAll('*').forEach((elm) => resizeObserver.observe(elm));

onScreenUpdate();

return () => {
handleScreenUpdateThrottled.cancel();
mutationObserver.disconnect();
resizeObserver.disconnect();
};
}, [appRoot]);

React.useEffect(() => {
const bridge: ToolpadBridge = {
update: (newState) => {
React.startTransition(() => {
setState(newState);
});
},
getPageViewState: () => {
invariant(rootRef.current, 'App ref not attached');
return getPageViewState(rootRef.current);
},
getViewCoordinates(clientX, clientY) {
if (!rootRef.current) {
return null;
}
const rect = rootRef.current.getBoundingClientRect();
if (rectContainsPoint(rect, clientX, clientY)) {
return { x: clientX - rect.x, y: clientY - rect.y };
}
return null;
},
};

// eslint-disable-next-line no-underscore-dangle
if (typeof window.__TOOLPAD_READY__ === 'function') {
if (typeof window.__TOOLPAD_BRIDGE__ === 'function') {
// eslint-disable-next-line no-underscore-dangle
window.__TOOLPAD_READY__();
window.__TOOLPAD_BRIDGE__(bridge);
} else {
// eslint-disable-next-line no-underscore-dangle
window.__TOOLPAD_READY__ = true;
window.__TOOLPAD_BRIDGE__ = bridge;
}
return () => {
// eslint-disable-next-line no-underscore-dangle
delete window.__TOOLPAD_BRIDGE__;
};
}, []);

React.useEffect(() => {
// Run after every render
fireEvent({ type: 'afterRender' });
});
return () => {};
}, []);

const editorHooks: CanvasHooks = React.useMemo(() => {
return {
Expand All @@ -65,6 +118,7 @@ export default function AppCanvas({ basename }: AppCanvasProps) {
return state ? (
<CanvasHooksContext.Provider value={editorHooks}>
<ToolpadApp
rootRef={setAppRoot}
hidePreviewBanner
dom={state.dom}
version="preview"
Expand Down
1 change: 0 additions & 1 deletion packages/toolpad-app/src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
export const MUI_X_PRO_LICENSE =
'82281641f885336d8c6b61faa73edecdT1JERVI6c3R1ZGlvXzEyMyxFWFBJUlk9MTY3NzY2NTQ3MjM4MSxLRVlWRVJTSU9OPTE=';
export const HTML_ID_APP_ROOT = 'root';
export const HTML_ID_EDITOR_OVERLAY = 'editor-overlay';
export const WINDOW_PROP_TOOLPAD_APP_RENDER_PARAMS = '__TOOLPAD_APP_RENDER_PARAMS__';
export const RUNTIME_CONFIG_WINDOW_PROPERTY = '__TOOLPAD_RUNTIME_CONFIG__';
6 changes: 4 additions & 2 deletions packages/toolpad-app/src/runtime/ToolpadApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ import evalJsBindings, {
evaluateExpression,
ParsedBinding,
} from './evalJsBindings';
import { HTML_ID_APP_ROOT, HTML_ID_EDITOR_OVERLAY } from '../constants';
import { HTML_ID_EDITOR_OVERLAY } from '../constants';
import { mapProperties, mapValues } from '../utils/collections';
import usePageTitle from '../utils/usePageTitle';
import ComponentsContext, { useComponents, useComponent } from './ComponentsContext';
Expand Down Expand Up @@ -779,6 +779,7 @@ const queryClient = new QueryClient({
});

export interface ToolpadAppProps {
rootRef?: React.Ref<HTMLDivElement>;
hidePreviewBanner?: boolean;
basename: string;
appId: string;
Expand All @@ -787,6 +788,7 @@ export interface ToolpadAppProps {
}

export default function ToolpadApp({
rootRef,
basename,
appId,
version,
Expand All @@ -800,7 +802,7 @@ export default function ToolpadApp({
React.useEffect(() => setResetNodeErrorsKey((key) => key + 1), [dom]);

return (
<AppRoot id={HTML_ID_APP_ROOT}>
<AppRoot ref={rootRef}>
<NoSsr>
<DomContextProvider value={dom}>
<AppThemeProvider dom={dom}>
Expand Down
Loading