Visualize Your Ideas With Code
feat(2d): add querying helpers (#852)
Jacob614de6bd8542
diff --git a/packages/2d/package.json b/packages/2d/package.jsonindex 7df9ef45..edccca86 100644--- a/packages/2d/package.json+++ b/packages/2d/package.json@@ -10,7 +10,7 @@"types": "./lib/index.d.ts","scripts": {"dev": "tspc -w",- "build": "tspc",+ "build": "tspc -p tsconfig.build.json","bundle": "rollup -c rollup.config.mjs","test": "vitest"},diff --git a/packages/2d/src/components/Layout.ts b/packages/2d/src/components/Layout.tsindex 82ab542e..702a05c0 100644--- a/packages/2d/src/components/Layout.ts+++ b/packages/2d/src/components/Layout.ts@@ -41,7 +41,7 @@ import {import {threadable} from '@motion-canvas/core/lib/decorators';import {ThreadGenerator} from '@motion-canvas/core/lib/threading';import {Node, NodeProps} from './Node';-import {drawLine, drawPivot} from '../utils';+import {drawLine, drawPivot, is} from '../utils';import {spacingSignal} from '../decorators/spacingSignal';import {modify,@@ -640,15 +640,7 @@ export class Layout extends Node {@computed()protected parentTransform(): Layout | null {- let parent: Node | null = this.parent();- while (parent) {- if (parent instanceof Layout) {- return parent;- }- parent = parent.parent();- }-- return null;+ return this.findAncestor(is(Layout));}@computed()diff --git a/packages/2d/src/components/Node.ts b/packages/2d/src/components/Node.tsindex 30c84467..d8e0605a 100644--- a/packages/2d/src/components/Node.ts+++ b/packages/2d/src/components/Node.ts@@ -908,6 +908,163 @@ export class Node implements Promisable<Node> {}}+ /**+ * Find all descendants of this node that match the given predicate.+ *+ * @param predicate - A function that returns true if the node matches.+ */+ public findAll<T extends Node>(predicate: (node: any) => node is T): T[];+ /**+ * Find all descendants of this node that match the given predicate.+ *+ * @param predicate - A function that returns true if the node matches.+ */+ public findAll<T extends Node = Node>(predicate: (node: any) => boolean): T[];+ public findAll<T extends Node>(predicate: (node: any) => node is T): T[] {+ const result: T[] = [];+ const queue = this.reversedChildren();+ while (queue.length > 0) {+ const node = queue.pop()!;+ if (predicate(node)) {+ result.push(node);+ }+ const children = node.children();+ for (let i = children.length - 1; i >= 0; i--) {+ queue.push(children[i]);+ }+ }++ return result;+ }++ /**+ * Find the first descendant of this node that matches the given predicate.+ *+ * @param predicate - A function that returns true if the node matches.+ */+ public findFirst<T extends Node>(+ predicate: (node: Node) => node is T,+ ): T | null;+ /**+ * Find the first descendant of this node that matches the given predicate.+ *+ * @param predicate - A function that returns true if the node matches.+ */+ public findFirst<T extends Node = Node>(+ predicate: (node: Node) => boolean,+ ): T | null;+ public findFirst<T extends Node>(+ predicate: (node: Node) => node is T,+ ): T | null {+ const queue = this.reversedChildren();+ while (queue.length > 0) {+ const node = queue.pop()!;+ if (predicate(node)) {+ return node;+ }+ const children = node.children();+ for (let i = children.length - 1; i >= 0; i--) {+ queue.push(children[i]);+ }+ }++ return null;+ }++ /**+ * Find the last descendant of this node that matches the given predicate.+ *+ * @param predicate - A function that returns true if the node matches.+ */+ public findLast<T extends Node>(+ predicate: (node: Node) => node is T,+ ): T | null;+ /**+ * Find the last descendant of this node that matches the given predicate.+ *+ * @param predicate - A function that returns true if the node matches.+ */+ public findLast<T extends Node = Node>(+ predicate: (node: Node) => boolean,+ ): T | null;+ public findLast<T extends Node>(+ predicate: (node: Node) => node is T,+ ): T | null {+ const search: Node[] = [];+ const queue = this.reversedChildren();++ while (queue.length > 0) {+ const node = queue.pop()!;+ search.push(node);+ const children = node.children();+ for (let i = children.length - 1; i >= 0; i--) {+ queue.push(children[i]);+ }+ }++ while (search.length > 0) {+ const node = search.pop()!;+ if (predicate(node)) {+ return node;+ }+ }++ return null;+ }++ /**+ * Find the closest ancestor of this node that matches the given predicate.+ *+ * @param predicate - A function that returns true if the node matches.+ */+ public findAncestor<T extends Node>(+ predicate: (node: Node) => node is T,+ ): T | null;+ /**+ * Find the closest ancestor of this node that matches the given predicate.+ *+ * @param predicate - A function that returns true if the node matches.+ */+ public findAncestor<T extends Node = Node>(+ predicate: (node: Node) => boolean,+ ): T | null;+ public findAncestor<T extends Node>(+ predicate: (node: Node) => node is T,+ ): T | null {+ let parent: Node | null = this.parent();+ while (parent) {+ if (predicate(parent)) {+ return parent;+ }+ parent = parent.parent();+ }++ return null;+ }++ /**+ * Get the nth children cast to the specified type.+ *+ * @param index - The index of the child to retrieve.+ */+ public childAs<T extends Node = Node>(index: number): T | null {+ return (this.children()[index] as T) ?? null;+ }++ /**+ * Get the children array cast to the specified type.+ */+ public childrenAs<T extends Node = Node>(): T[] {+ return this.children() as T[];+ }++ /**+ * Get the parent cast to the specified type.+ */+ public parentAs<T extends Node = Node>(): T | null {+ return (this.parent() as T) ?? null;+ }+/*** Prepare this node to be disposed of.*@@ -1453,6 +1610,15 @@ export class Node implements Promisable<Node> {private signalByKey(key: string): SimpleSignal<any> {return (<Record<string, SimpleSignal<any>>>(<unknown>this))[key];}++ private reversedChildren() {+ const children = this.children();+ const result: Node[] = [];+ for (let i = children.length - 1; i >= 0; i--) {+ result.push(children[i]);+ }+ return result;+ }}/*@__PURE__*/diff --git a/packages/2d/src/components/View2D.ts b/packages/2d/src/components/View2D.tsindex bf24a3a5..a1571c09 100644--- a/packages/2d/src/components/View2D.ts+++ b/packages/2d/src/components/View2D.ts@@ -1,8 +1,10 @@+import type {Node} from './Node';import {Rect, RectProps} from './Rect';import {initial, signal} from '../decorators';import {PlaybackState} from '@motion-canvas/core';import {SimpleSignal} from '@motion-canvas/core/lib/signals';import {lazy} from '@motion-canvas/core/lib/decorators';+import {useScene2D} from '../scenes/useScene2D';export interface View2DProps extends RectProps {assetHash: string;@@ -65,6 +67,15 @@ export class View2D extends Rect {super.render(context);}+ /**+ * Find a node by its key.+ *+ * @param key - The key of the node.+ */+ public findKey<T extends Node = Node>(key: string): T | null {+ return (useScene2D().getNode(key) as T) ?? null;+ }+protected override requestLayoutUpdate() {this.updateLayout();}diff --git a/packages/2d/src/components/__tests__/mockScene2D.ts b/packages/2d/src/components/__tests__/mockScene2D.tsnew file mode 100644index 00000000..a9bb19d0--- /dev/null+++ b/packages/2d/src/components/__tests__/mockScene2D.ts@@ -0,0 +1,50 @@+import {afterAll, beforeAll, beforeEach} from 'vitest';+import {+ endPlayback,+ endScene,+ FullSceneDescription,+ PlaybackManager,+ PlaybackStatus,+ startPlayback,+ startScene,+ ThreadGeneratorFactory,+ ValueDispatcher,+ Vector2,+} from '@motion-canvas/core';+import {makeScene2D, Scene2D} from '../../scenes';+import {ReadOnlyTimeEvents} from '@motion-canvas/core/lib/scenes/timeEvents';+import {View2D} from '../View2D';++/**+ * Set up the test environment to support creating nodes.+ *+ * @remarks+ * Should be called inside a `describe()` block.+ * Due to js-dom limitations, layouts are not correctly computed.+ */+export function mockScene2D() {+ const playback = new PlaybackManager();+ const status = new PlaybackStatus(playback);+ const description = {+ ...makeScene2D(function* () {+ // do nothing+ }),+ name: 'test',+ size: new Vector2(1920, 1080),+ resolutionScale: 1,+ timeEventsClass: ReadOnlyTimeEvents,+ playback: status,+ } as unknown as FullSceneDescription<ThreadGeneratorFactory<View2D>>;+ description.onReplaced = new ValueDispatcher(description);+ const scene = new Scene2D(description);++ beforeAll(() => {+ startScene(scene);+ startPlayback(status);+ });+ afterAll(() => {+ endPlayback(status);+ endScene(scene);+ });+ beforeEach(() => scene.reset());+}diff --git a/packages/2d/src/components/__tests__/query.test.tsx b/packages/2d/src/components/__tests__/query.test.tsxnew file mode 100644index 00000000..65b630b8--- /dev/null+++ b/packages/2d/src/components/__tests__/query.test.tsx@@ -0,0 +1,122 @@+import {describe, it, expect} from 'vitest';+import {createRef, createRefArray} from '@motion-canvas/core';+import {mockScene2D} from './mockScene2D';+import {useScene2D} from '../../scenes';+import {Rect} from '../Rect';+import {Circle} from '../Circle';+import {is} from '../../utils';++describe('query', () => {+ mockScene2D();++ it('Query items based on their type', () => {+ const view = useScene2D().getView();+ const circles = createRefArray<Circle>();+ view.add(+ <>+ <Rect />+ <Circle ref={circles} />+ <Rect />+ <Circle ref={circles} />+ <Rect />+ </>,+ );++ const query = view.findAll(is(Circle));+ expect(query.length).toBe(2);+ expect(query).toEqual([...circles]);+ });++ it('Query items based on a custom predicate', () => {+ const view = useScene2D().getView();+ const nodes = createRefArray<Node>();+ view.add(+ <>+ <Rect ref={nodes} scale={2} />+ <Rect />+ <Circle />+ <Circle ref={nodes} scale={2} />+ </>,+ );++ const query = view.findAll(node => node.scale.x() === 2);+ expect(query.length).toBe(2);+ expect(query).toEqual([...nodes]);+ });++ it('Query the first matching child', () => {+ const view = useScene2D().getView();+ const match = createRef<Circle>();+ view.add(+ <>+ <Rect />+ <Rect>+ <Rect />+ <Circle ref={match} />+ </Rect>+ <Circle />+ <Rect />+ </>,+ );++ const query = view.findFirst(is(Circle));+ expect(query).toBe(match());+ });++ it('Query the last matching child', () => {+ const view = useScene2D().getView();+ const match = createRef<Circle>();+ view.add(+ <>+ <Rect />+ <Circle />+ <Circle>+ <Circle />+ <Rect />+ <Circle ref={match} />+ </Circle>+ <Rect />+ </>,+ );++ const query = view.findLast(is(Circle));+ expect(query?.key).toBe(match().key);+ });++ it('Query the first matching ancestor', () => {+ const view = useScene2D().getView();+ const child = createRef<Circle>();+ const match = createRef<Circle>();+ view.add(+ <Circle>+ <Circle ref={match}>+ <Rect>+ <Circle />+ <Circle ref={child} />+ <Circle />+ </Rect>+ </Circle>+ </Circle>,+ );++ const query = child().findAncestor(is(Circle));+ expect(query).toBe(match());+ });++ it('Retrieve a node by its key', () => {+ const view = useScene2D().getView();+ const match = createRef<Circle>();+ view.add(+ <>+ <Circle>+ <Rect />+ <Circle ref={match} key="test-key" />+ </Circle>+ <Rect />+ </>,+ );++ const query = view.findKey('test-key');+ expect(query).toBe(match());+ });+});diff --git a/packages/2d/src/jsx-runtime.ts b/packages/2d/src/jsx-runtime.tsindex 9f54b969..a6ddb51f 100644--- a/packages/2d/src/jsx-runtime.ts+++ b/packages/2d/src/jsx-runtime.ts@@ -25,6 +25,7 @@ export const Fragment = Symbol.for('@motion-canvas/2d/fragment');export function jsx(type: NodeConstructor | FunctionComponent | typeof Fragment,config: JSXProps,+ key?: any,): ComponentChildren {const {ref, children, ...rest} = config;const flatChildren = Array.isArray(children) ? children.flat() : children;@@ -34,11 +35,11 @@ export function jsx(}if (isClassComponent(type)) {- const node = new type({...rest, children: flatChildren});+ const node = new type({...rest, children: flatChildren, key});ref?.(node);return node;} else {- return type({...rest, ref, children: flatChildren});+ return type({...rest, ref, children: flatChildren, key});}}export {jsx as jsxs};diff --git a/packages/2d/src/scenes/Scene2D.ts b/packages/2d/src/scenes/Scene2D.tsindex 7980c64c..414e137c 100644--- a/packages/2d/src/scenes/Scene2D.ts+++ b/packages/2d/src/scenes/Scene2D.ts@@ -8,13 +8,13 @@ import {SceneRenderEvent,ThreadGeneratorFactory,} from '@motion-canvas/core/lib/scenes';-import {Vector2} from '@motion-canvas/core';+import {useLogger, Vector2} from '@motion-canvas/core';import {Node, View2D} from '../components';export class Scene2D extends GeneratorScene<View2D> implements Inspectable {private view: View2D | null = null;- private registeredNodes: Record<string, Node> = {};- private nodeCounters: Record<string, number> = {};+ private readonly registeredNodes = new Map<string, Node>();+ private readonly nodeCounters = new Map<string, number>();private assetHash = Date.now().toString();public constructor(@@ -53,15 +53,15 @@ export class Scene2D extends GeneratorScene<View2D> implements Inspectable {}public override reset(previousScene?: Scene): Promise<void> {- for (const key in this.registeredNodes) {+ for (const key of this.registeredNodes.keys()) {try {- this.registeredNodes[key].dispose();+ this.registeredNodes.get(key)!.dispose();} catch (e: any) {this.logger.error(e);}}- this.registeredNodes = {};- this.nodeCounters = {};+ this.registeredNodes.clear();+ this.nodeCounters.clear();this.recreateView();return super.reset(previousScene);@@ -125,17 +125,26 @@ export class Scene2D extends GeneratorScene<View2D> implements Inspectable {public registerNode(node: Node, key?: string): string {const className = node.constructor?.name ?? 'unknown';- this.nodeCounters[className] ??= 0;- const counter = this.nodeCounters[className]++;+ const counter = (this.nodeCounters.get(className) ?? 0) + 1;+ this.nodeCounters.set(className, counter);++ if (key && this.registeredNodes.has(key)) {+ useLogger().error({+ message: `Duplicated node key: "${key}".`,+ inspect: key,+ stack: new Error().stack,+ });+ key = undefined;+ }key ??= `${this.name}/${className}[${counter}]`;- this.registeredNodes[key] = node;+ this.registeredNodes.set(key, node);return key;}public getNode(key: any): Node | null {if (typeof key !== 'string') return null;- return this.registeredNodes[key] ?? null;+ return this.registeredNodes.get(key) ?? null;}protected recreateView() {diff --git a/packages/2d/src/utils/index.ts b/packages/2d/src/utils/index.tsindex e3d57674..5847f637 100644--- a/packages/2d/src/utils/index.ts+++ b/packages/2d/src/utils/index.ts@@ -1 +1,2 @@export * from './CanvasUtils';+export * from './is';diff --git a/packages/2d/src/utils/is.ts b/packages/2d/src/utils/is.tsnew file mode 100644index 00000000..3202a29b--- /dev/null+++ b/packages/2d/src/utils/is.ts@@ -0,0 +1,15 @@+/**+ * Create a predicate that checks if the given object is an instance of the+ * given class.+ *+ * @param klass - The class to check against.+ */+export function is<+ T extends+ // NOTE This is the one specific case where the Function type is actually+ // desired. Hence, the eslint-disable-next-line.+ // eslint-disable-next-line @typescript-eslint/ban-types+ Function,+>(klass: T): (object: any) => object is T {+ return (object): object is T => object instanceof klass;+}diff --git a/packages/2d/tsconfig.build.json b/packages/2d/tsconfig.build.jsonnew file mode 100644index 00000000..3f58745d--- /dev/null+++ b/packages/2d/tsconfig.build.json@@ -0,0 +1,4 @@+{+ "extends": "./tsconfig.json",+ "exclude": ["**/*.test.*", "**/__tests__/**/*"]+}diff --git a/packages/2d/tsconfig.json b/packages/2d/tsconfig.jsonindex 4a553e27..3ba1a670 100644--- a/packages/2d/tsconfig.json+++ b/packages/2d/tsconfig.json@@ -13,6 +13,8 @@"experimentalDecorators": true,"skipLibCheck": true,"types": ["node"],+ "jsx": "react-jsx",+ "jsxImportSource": "@motion-canvas/2d/src","plugins": [{"transform": "@motion-canvas/internal/transformers/markdown-literals.js"diff --git a/packages/2d/vitest.config.ts b/packages/2d/vitest.config.tsindex 908dc395..5b71a510 100644--- a/packages/2d/vitest.config.ts+++ b/packages/2d/vitest.config.ts@@ -4,6 +4,7 @@ import markdownLiterals from '@motion-canvas/internal/vite/markdown-literals';export default defineConfig({plugins: [markdownLiterals()],test: {+ include: ['./src/**/*.test.*'],environment: 'jsdom',},});diff --git a/packages/docs/docs/getting-started/hierarchy.mdx b/packages/docs/docs/getting-started/hierarchy.mdxindex c077b7cf..e77bdb44 100644--- a/packages/docs/docs/getting-started/hierarchy.mdx+++ b/packages/docs/docs/getting-started/hierarchy.mdx@@ -94,71 +94,163 @@ view.add([</div></div>-Just like with DOM, it's possible to add, remove, and rearrange nodes at any-time. The [`Node`][node] class contains the+## Modifying the hierarchy++After the hierarchy has been created, it's still possible to add, remove, and+rearrange nodes at any time. The [`Node`][node] class contains the[`children`](/api/2d/components/Node#children) and[`parent`](/api/2d/components/Node#parent) properties that can be used totraverse the tree. But in order to modify it, it's recommended to use thefollowing helper methods:-## `Node.add`+### `Node.add`<ApiSnippet url={'/api/2d/components/Node#add'} /><hr />-## `Node.insert`+### `Node.insert`<ApiSnippet url={'/api/2d/components/Node#insert'} /><hr />-## `Node.remove`+### `Node.remove`<ApiSnippet url={'/api/2d/components/Node#remove'} /><hr />-## `Node.reparent`+### `Node.reparent`<ApiSnippet url={'/api/2d/components/Node#reparent'} /><hr />-## `Node.moveUp`+### `Node.moveUp`<ApiSnippet url={'/api/2d/components/Node#moveUp'} /><hr />-## `Node.moveDown`+### `Node.moveDown`<ApiSnippet url={'/api/2d/components/Node#moveDown'} /><hr />-## `Node.moveToTop`+### `Node.moveToTop`<ApiSnippet url={'/api/2d/components/Node#moveToTop'} /><hr />-## `Node.moveToBottom`+### `Node.moveToBottom`<ApiSnippet url={'/api/2d/components/Node#moveToBottom'} /><hr />-## `Node.moveTo`+### `Node.moveTo`<ApiSnippet url={'/api/2d/components/Node#moveTo'} /><hr />-## `Node.moveAbove`+### `Node.moveAbove`<ApiSnippet url={'/api/2d/components/Node#moveAbove'} /><hr />-## `Node.moveBelow`+### `Node.moveBelow`<ApiSnippet url={'/api/2d/components/Node#moveBelow'} /><hr />-## `Node.removeChildren`+### `Node.removeChildren`<ApiSnippet url={'/api/2d/components/Node#removeChildren'} /><hr />+## Querying the hierarchy++Sometimes it can be useful to traverse the hierarchy and find some specific+nodes. In this documentation, we'll be referring to this process as _querying_.+Consider the following animation:++```tsx editor+import {makeScene2D, Layout, Txt, Circle, Rect, is} from '@motion-canvas/2d';+import {all} from '@motion-canvas/core';++export default makeScene2D(function* (view) {+ view.add(+ <Layout layout gap={20} alignItems={'center'}>+ <Txt fill={'white'}>Example</Txt>+ <Rect fill={'#f3303f'} padding={20} gap={20}>+ <Txt fill={'white'}>42</Txt>+ <Circle size={60} fill={'#FFC66D'} />+ <Txt fill={'white'}>!!!</Txt>+ </Rect>+ </Layout>,+ );++ const texts = view.findAll(is(Txt));++ yield* all(...texts.map(text => text.fill('#FFC66D', 1).back(1)));+});+```++It contains multiple text nodes whose color oscillates between white and yellow.+To achieve that, we used `view.findAll(is(Txt))` to search through all+descendants of the view node and select only those of type `Txt`. The first+argument passed to the [`findAll`](/api/2d/components/Node#findAll) method is a+so-called `predicate`. It's a function that takes a node and returns `true` if+it's a node we're looking for.++For instance, if we wanted to find all nodes whose scale x is greater than `1`,+we could write:++```ts+const wideNodes = view.findAll(node => node.scale.x() > 1);+```++Knowing this, we could try to find all nodes of type `Txt` as follows:++```ts+const texts = view.findAll(node => node instanceof Txt);+```++But Motion Canvas comes with a helpful utility function called+[`is`](/api/2d/utils#is) that can create this predicate for us:++```ts+import {is} from '@motion-canvas/2d';+// ...+const texts = view.findAll(is(Txt));+```++These can be used with any JavaScript function that accepts a predicate. The+`findAll` method has been implemented to traverse all descendants of a node, but+if we wanted to query only the direct children, we could retrieve the+[`children`](/api/2d/components/Node#children) array and call the built-in+`filter` method with our predicate:++```ts+const textChildren = someParent.children().filter(is(Txt));+```++There are a few other methods that can be used to query the hierarchy depending+on your needs:++### `Node.findAll`++<ApiSnippet url={'/api/2d/components/Node#findAll'} />+<hr />++### `Node.findFirst`++<ApiSnippet url={'/api/2d/components/Node#findFirst'} />+<hr />++### `Node.findLast`++<ApiSnippet url={'/api/2d/components/Node#findLast'} />+<hr />++### `Node.findAncestor`++<ApiSnippet url={'/api/2d/components/Node#findAncestor'} />+<hr />+[node]: /api/2d/components/Nodediff --git a/packages/docs/typedoc.js b/packages/docs/typedoc.jsindex 19bcd0b5..fb8e1336 100644--- a/packages/docs/typedoc.js+++ b/packages/docs/typedoc.js@@ -64,7 +64,7 @@ module.exports = () => ({'../2d/src/scenes','../2d/src/utils',],- tsconfig: '../2d/tsconfig.json',+ tsconfig: '../2d/tsconfig.build.json',},'2d',core,