Visualize Your Ideas With Code
feat(ui): custom inspectors (#913)
Jacob6c544248a2bd
diff --git a/packages/2d/src/editor/NodeInspectorConfig.tsx b/packages/2d/src/editor/NodeInspectorConfig.tsxnew file mode 100644index 00000000..b2d64b3b--- /dev/null+++ b/packages/2d/src/editor/NodeInspectorConfig.tsx@@ -0,0 +1,78 @@+import {+ AutoField,+ Button,+ Group,+ Label,+ Pane,+ PluginInspectorConfig,+ Separator,+ UnknownField,+ findAndOpenFirstUserFile,+ useApplication,+} from '@motion-canvas/ui';+import {useComputed} from '@preact/signals';+import {usePluginState} from './Provider';++function Component() {+ const {inspection} = useApplication();+ const {scene, afterRender} = usePluginState();+ const node = useComputed(() => {+ afterRender.value;+ const {payload} = inspection.value;+ return scene.value?.getNode(payload as string);+ });++ const attributes = useComputed(() => {+ afterRender.value;+ const currentNode = node.value;+ const attributes: [string, unknown][] = [];++ if (currentNode) {+ for (const {key, meta, signal} of currentNode) {+ if (!meta.inspectable) continue;+ attributes.push([key, signal()]);+ }+ }++ return attributes;+ });++ const stack = node.value?.creationStack;++ return (+ <Pane title="Node Inspector" id="node-inspector-pane">+ <Separator size={1} />+ {stack && (+ <Group>+ <Label />+ <Button onClick={() => findAndOpenFirstUserFile(stack)} main>+ GO TO SOURCE+ </Button>+ </Group>+ )}+ <Group>+ <Label>key</Label>+ <UnknownField value={inspection.value.payload} />+ </Group>+ {!node.value && (+ <Group>+ <Label />+ Couldn't find the node. It may have been deleted or doesn't exist yet.+ </Group>+ )}+ {attributes.value.map(([key, value]) => (+ <Group key={key}>+ <Label>{key}</Label>+ <AutoField value={value} />+ </Group>+ ))}+ </Pane>+ );+}++export const NodeInspectorKey = '@motion-canvas/2d/node-inspector';++export const NodeInspectorConfig: PluginInspectorConfig = {+ key: NodeInspectorKey,+ component: Component,+};diff --git a/packages/2d/src/editor/PreviewOverlayConfig.tsx b/packages/2d/src/editor/PreviewOverlayConfig.tsxindex e956a49c..9a74f71b 100644--- a/packages/2d/src/editor/PreviewOverlayConfig.tsx+++ b/packages/2d/src/editor/PreviewOverlayConfig.tsx@@ -1,26 +1,24 @@-import {isInspectable, Vector2} from '@motion-canvas/core';+import {Vector2} from '@motion-canvas/core';import {MouseButton,OverlayWrapper,PluginOverlayConfig,- useCurrentScene,useViewportContext,useViewportMatrix,} from '@motion-canvas/ui';import {ComponentChildren} from 'preact';-import {useInspection} from './Provider';+import {usePluginState} from './Provider';function Component({children}: {children?: ComponentChildren}) {const state = useViewportContext();- const scene = useCurrentScene();- const {selectedKey} = useInspection();+ const {scene, selectedKey} = usePluginState();const matrix = useViewportMatrix();return (<OverlayWrapperonPointerDown={event => {if (event.button !== MouseButton.Left || event.shiftKey) return;- if (!isInspectable(scene)) return;+ if (!scene.value) return;event.stopPropagation();const position = new Vector2(@@ -28,7 +26,7 @@ function Component({children}: {children?: ComponentChildren}) {event.y - state.rect.y,).transformAsPoint(matrix.inverse());- selectedKey.value = scene.inspectPosition(+ selectedKey.value = scene.value.inspectPosition(position.x,position.y,) as string;@@ -40,7 +38,7 @@ function Component({children}: {children?: ComponentChildren}) {}function drawHook() {- const {selectedKey, hoveredKey, afterRender, scene} = useInspection();+ const {selectedKey, hoveredKey, afterRender, scene} = usePluginState();selectedKey.value;hoveredKey.value;afterRender.value;@@ -50,19 +48,12 @@ function drawHook() {if (!currentScene) return;let node = currentScene.getNode(selectedKey.value);- if (!node || node.key !== selectedKey.value) {- selectedKey.value = node?.key ?? null;- } else {- currentScene.drawOverlay(selectedKey.value, matrix, ctx);+ if (node) {+ currentScene.drawOverlay(node.key, matrix, ctx);}node = currentScene.getNode(hoveredKey.value);- if (!node || node.key !== hoveredKey.value) {- hoveredKey.value = node?.key ?? null;- return;- }-- if (hoveredKey.value !== selectedKey.value) {+ if (node && hoveredKey.value !== selectedKey.value) {ctx.globalAlpha = 0.5;currentScene.drawOverlay(hoveredKey.value, matrix, ctx);}diff --git a/packages/2d/src/editor/Provider.tsx b/packages/2d/src/editor/Provider.tsxindex e86fc440..5bfff66a 100644--- a/packages/2d/src/editor/Provider.tsx+++ b/packages/2d/src/editor/Provider.tsx@@ -1,18 +1,18 @@import {Scene2D} from '@motion-canvas/2d';import {SceneRenderEvent} from '@motion-canvas/core';-import {useCurrentScene} from '@motion-canvas/ui';+import {useApplication, useCurrentScene} from '@motion-canvas/ui';import {ReadonlySignal,Signal,computed,signal,- useSignal,useSignalEffect,} from '@preact/signals';import {ComponentChildren, createContext} from 'preact';import {useContext, useMemo} from 'preact/hooks';+import {NodeInspectorKey} from './NodeInspectorConfig';-export interface InspectionState {+export interface PluginState {selectedKey: Signal<string | null>;hoveredKey: Signal<string | null>;openNodes: Map<string, boolean>;@@ -21,17 +21,18 @@ export interface InspectionState {afterRender: ReadonlySignal<number>;}-const InspectionContext = createContext<InspectionState | null>(null);+const PluginContext = createContext<PluginState | null>(null);-export function useInspection() {- return useContext(InspectionContext)!;+export function usePluginState() {+ return useContext(PluginContext)!;}export function Provider({children}: {children?: ComponentChildren}) {+ const {inspection} = useApplication();const currentScene = useCurrentScene();const state = useMemo(() => {- const scene = useSignal(currentScene as Scene2D);+ const scene = signal(currentScene as Scene2D);const selectedKey = signal<string | null>(null);const afterRender = signal(0);const hoveredKey = signal<string | null>(null);@@ -58,22 +59,39 @@ export function Provider({children}: {children?: ComponentChildren}) {openNodes,selectedChain,scene,- } satisfies InspectionState;+ } satisfies PluginState;}, []);state.scene.value = currentScene as Scene2D;- useSignalEffect(() =>- state.scene.value.onRenderLifecycle.subscribe(([event]) => {- if (event === SceneRenderEvent.AfterRender) {- state.afterRender.value++;- }- }),+ useSignalEffect(+ () =>+ state.scene.value?.onRenderLifecycle.subscribe(([event]) => {+ if (event === SceneRenderEvent.AfterRender) {+ state.afterRender.value++;+ }+ }),);+ useSignalEffect(() => {+ const {key, payload} = inspection.value;+ if (key === NodeInspectorKey) {+ state.selectedKey.value = payload as string;+ }+ });++ useSignalEffect(() => {+ const nodeKey = state.selectedKey.value;+ const {key, payload} = inspection.peek();++ if (key === NodeInspectorKey && !nodeKey) {+ inspection.value = {key: '', payload: null};+ } else if (payload !== nodeKey) {+ inspection.value = {key: NodeInspectorKey, payload: nodeKey};+ }+ });+return (- <InspectionContext.Provider value={state}>- {children}- </InspectionContext.Provider>+ <PluginContext.Provider value={state}>{children}</PluginContext.Provider>);}diff --git a/packages/2d/src/editor/SceneGraphTabConfig.tsx b/packages/2d/src/editor/SceneGraphTabConfig.tsxindex f8394ded..ec5e5b77 100644--- a/packages/2d/src/editor/SceneGraphTabConfig.tsx+++ b/packages/2d/src/editor/SceneGraphTabConfig.tsx@@ -12,21 +12,21 @@ import {import {useSignalEffect} from '@preact/signals';import {useEffect, useRef} from 'preact/hooks';-import {useInspection} from './Provider';+import {usePluginState} from './Provider';import {DetachedRoot, ViewRoot} from './tree';function TabComponent({tab}: PluginTabProps) {const {sidebar} = usePanels();const inspectorTab = useRef<HTMLButtonElement>(null);const reducedMotion = useReducedMotion();- const {selectedKey} = useInspection();+ const {selectedKey} = usePluginState();const {logger} = useApplication();useEffect(() =>logger.onInspected.subscribe(key => {- selectedKey.value = key;sidebar.set(tab);+ selectedKey.value = key;}),[tab],);@@ -59,7 +59,7 @@ function TabComponent({tab}: PluginTabProps) {}function PaneComponent() {- const {selectedKey} = useInspection();+ const {selectedKey} = usePluginState();return (<Panediff --git a/packages/2d/src/editor/index.ts b/packages/2d/src/editor/index.tsindex 59b94cc0..37b6f5b2 100644--- a/packages/2d/src/editor/index.ts+++ b/packages/2d/src/editor/index.ts@@ -1,6 +1,7 @@import './index.css';import {makeEditorPlugin} from '@motion-canvas/ui';+import {NodeInspectorConfig} from './NodeInspectorConfig';import {PreviewOverlayConfig} from './PreviewOverlayConfig';import {Provider} from './Provider';import {SceneGraphTabConfig} from './SceneGraphTabConfig';@@ -11,5 +12,6 @@ export default makeEditorPlugin(() => {provider: Provider,previewOverlay: PreviewOverlayConfig,tabs: [SceneGraphTabConfig],+ inspectors: [NodeInspectorConfig],};});diff --git a/packages/2d/src/editor/tree/DetachedRoot.tsx b/packages/2d/src/editor/tree/DetachedRoot.tsxindex 3b4f0795..5d9085ee 100644--- a/packages/2d/src/editor/tree/DetachedRoot.tsx+++ b/packages/2d/src/editor/tree/DetachedRoot.tsx@@ -1,11 +1,11 @@import {useSignal} from '@preact/signals';-import {useInspection} from '../Provider';+import {usePluginState} from '../Provider';import {NodeElement} from './NodeElement';import {TreeElement} from './TreeElement';import {TreeRoot} from './TreeRoot';export function DetachedRoot() {- const {afterRender, scene} = useInspection();+ const {afterRender, scene} = usePluginState();const open = useSignal(false);const currentScene = scene.value;const children = currentScene ? [...currentScene.getDetachedNodes()] : [];diff --git a/packages/2d/src/editor/tree/NodeElement.tsx b/packages/2d/src/editor/tree/NodeElement.tsxindex 05779524..4eb49364 100644--- a/packages/2d/src/editor/tree/NodeElement.tsx+++ b/packages/2d/src/editor/tree/NodeElement.tsx@@ -1,7 +1,7 @@import {Node} from '@motion-canvas/2d';import {useComputed, useSignal, useSignalEffect} from '@preact/signals';import {useRef} from 'preact/hooks';-import {useInspection} from '../Provider';+import {usePluginState} from '../Provider';import {TreeElement} from './TreeElement';interface NodeElementProps {@@ -11,7 +11,7 @@ interface NodeElementProps {export function NodeElement({node, depth = 0}: NodeElementProps) {const {selectedKey, hoveredKey, openNodes, selectedChain, afterRender} =- useInspection();+ usePluginState();const ref = useRef<HTMLDivElement>(null);const open = useSignal(selectedChain.peek().has(node.key) || (openNodes.get(node.key) ?? false),diff --git a/packages/2d/src/editor/tree/ViewRoot.tsx b/packages/2d/src/editor/tree/ViewRoot.tsxindex 3b4afbc2..90095ee5 100644--- a/packages/2d/src/editor/tree/ViewRoot.tsx+++ b/packages/2d/src/editor/tree/ViewRoot.tsx@@ -1,10 +1,10 @@import {useSignal, useSignalEffect} from '@preact/signals';-import {useInspection} from '../Provider';+import {usePluginState} from '../Provider';import {NodeElement} from './NodeElement';import {TreeRoot} from './TreeRoot';export function ViewRoot() {- const {scene} = useInspection();+ const {scene} = usePluginState();const view = useSignal(scene.value?.getView());useSignalEffect(() => {diff --git a/packages/ui/src/components/viewport/EditorPreview.tsx b/packages/ui/src/components/viewport/EditorPreview.tsxindex c6bddf01..8d36526f 100644--- a/packages/ui/src/components/viewport/EditorPreview.tsx+++ b/packages/ui/src/components/viewport/EditorPreview.tsx@@ -19,6 +19,7 @@ import {ButtonCheckbox} from '../controls/ButtonCheckbox';import {Grid as GridIcon, Recenter} from '../icons';import {ColorPicker} from './ColorPicker';import {Coordinates} from './Coordinates';+import {Inspector} from './Inspector';import {OverlayCanvas} from './OverlayCanvas';import {PreviewStage} from './PreviewStage';import styles from './Viewport.module.scss';@@ -46,6 +47,7 @@ export function EditorPreview() {y: 0,});+ const inspector = useMemo(() => <Inspector />, []);const drawHooks = useMemo(() =>plugins.map(plugin => plugin.previewOverlay?.drawHook).filter(Boolean),@@ -241,6 +243,7 @@ export function EditorPreview() {<ColorPicker />{coordinateSetting && <Coordinates />}</div>+ {inspector}</div></ViewportProvider>);diff --git a/packages/ui/src/components/viewport/Inspector.tsx b/packages/ui/src/components/viewport/Inspector.tsxnew file mode 100644index 00000000..070690e4--- /dev/null+++ b/packages/ui/src/components/viewport/Inspector.tsx@@ -0,0 +1,27 @@+import {FunctionComponent} from 'preact';+import {useMemo} from 'preact/hooks';+import {useApplication, usePanels} from '../../contexts';+import styles from './Viewport.module.scss';++export function Inspector() {+ const {inspection} = useApplication();+ const {inspectors} = usePanels();+ const lookup = useMemo(() => {+ const lookup = new Map<string, FunctionComponent>();+ for (const config of inspectors) {+ lookup.set(config.key, config.component);+ }++ return lookup;+ }, [inspectors]);++ const Component = lookup.get(inspection.value.key);++ return Component ? (+ <div className={styles.inspectorOverlay}>+ <div className={styles.inspector}>+ <Component />+ </div>+ </div>+ ) : null;+}diff --git a/packages/ui/src/components/viewport/Viewport.module.scss b/packages/ui/src/components/viewport/Viewport.module.scssindex f96f5193..5a742837 100644--- a/packages/ui/src/components/viewport/Viewport.module.scss+++ b/packages/ui/src/components/viewport/Viewport.module.scss@@ -86,3 +86,19 @@display: block;}}++.inspectorOverlay {+ position: absolute;+ top: 0;+ right: 0;+ bottom: 0;+ padding: 12px;+ max-width: 424px;+ width: 40%;+}++.inspector {+ height: 100%;+ border-radius: var(--radius);+ overflow: hidden;+}diff --git a/packages/ui/src/contexts/application.tsx b/packages/ui/src/contexts/application.tsxindex 091df795..bd59b6c8 100644--- a/packages/ui/src/contexts/application.tsx+++ b/packages/ui/src/contexts/application.tsx@@ -6,12 +6,18 @@ import type {Renderer,SettingsMetadata,} from '@motion-canvas/core';+import {Signal, useSignal} from '@preact/signals';import {ComponentChildren, createContext} from 'preact';import {useContext, useRef} from 'preact/hooks';import {useSubscribable} from '../hooks';import {EditorPlugin} from '../plugin';import {LoggerManager} from '../utils';+export interface Inspection {+ key: string;+ payload: unknown;+}+interface Application {project: Project;player: Player;@@ -21,6 +27,7 @@ interface Application {settings: SettingsMetadata;plugins: EditorPlugin[];logger: LoggerManager;+ inspection: Signal<Inspection>;}const ApplicationContext = createContext<Application | null>(null);@@ -33,9 +40,10 @@ export function ApplicationProvider({application,children,}: {- application: Omit<Application, 'logger'>;+ application: Omit<Application, 'logger' | 'inspection'>;children: ComponentChildren;}) {+ const inspection = useSignal<Inspection>({key: '', payload: null});const manager = useRef<LoggerManager | null>(null);manager.current ??= new LoggerManager(application.project.logger);useSubscribable(@@ -49,6 +57,7 @@ export function ApplicationProvider({value={{...application,logger: manager.current,+ inspection,}}>{application.plugins.reduce((children, plugin) => {diff --git a/packages/ui/src/contexts/panels.tsx b/packages/ui/src/contexts/panels.tsxindex 51e32daa..f3b497e1 100644--- a/packages/ui/src/contexts/panels.tsx+++ b/packages/ui/src/contexts/panels.tsx@@ -1,7 +1,7 @@import {computed, ReadonlySignal} from '@preact/signals';import {ComponentChildren, createContext} from 'preact';import {useContext, useMemo} from 'preact/hooks';-import {PluginTabConfig} from '../plugin';+import {PluginInspectorConfig, PluginTabConfig} from '../plugin';import {EditorPanel, storedSignal} from '../signals';import {useApplication} from './application';@@ -15,6 +15,7 @@ interface Panels {sidebar: Panel;bottom: Panel;tabs: PluginTabConfig[];+ inspectors: PluginInspectorConfig[];}const PanelsContext = createContext<Panels | null>(null);@@ -39,6 +40,17 @@ export function PanelsProvider({children}: {children: ComponentChildren}) {return tabs;}, [plugins]);+ const inspectors = useMemo(() => {+ const inspectors: PluginInspectorConfig[] = [];+ for (const plugin of plugins) {+ for (const inspector of plugin.inspectors ?? []) {+ inspectors.push(inspector);+ }+ }++ return inspectors;+ }, [plugins]);+const options = useMemo(() => {const options = tabs.map(tab => tab.name);options.push(...Object.values(EditorPanel));@@ -54,6 +66,7 @@ export function PanelsProvider({children}: {children: ComponentChildren}) {sidebar,bottom,tabs,+ inspectors,}}>{children}diff --git a/packages/ui/src/plugin/EditorPlugin.ts b/packages/ui/src/plugin/EditorPlugin.tsindex 3691a2cb..9b021b1f 100644--- a/packages/ui/src/plugin/EditorPlugin.ts+++ b/packages/ui/src/plugin/EditorPlugin.ts@@ -39,6 +39,25 @@ export interface PluginTabConfig {paneComponent: FunctionComponent<PluginTabProps>;}+/**+ * Configuration for a custom inspector in the editor.+ */+export interface PluginInspectorConfig {+ /**+ * A unique key representing the payload this inspector can handle.+ *+ * @remarks+ * This key will be matched against {@link Inspection.key} to determine if the+ * inspector should be displayed.+ */+ key: string;++ /**+ * The component displayed in the inspector.+ */+ component: FunctionComponent;+}+export interface PluginDrawFunction {(ctx: CanvasRenderingContext2D, matrix: DOMMatrix): void;}@@ -95,4 +114,8 @@ export interface EditorPlugin extends Plugin {* Configuration for custom overlays displayed on top of the presentation.*/presenterOverlay?: PluginOverlayConfig;+ /**+ * Configuration for custom inspectors displayed on the right.+ */+ inspectors?: PluginInspectorConfig[];}