Visualize Your Ideas With Code
feat: better children and spawners (#858)
Jacob9b5c23d20761
diff --git a/.eslintrc.json b/.eslintrc.jsonindex 804b000c..b2ebc2d0 100644--- a/.eslintrc.json+++ b/.eslintrc.json@@ -28,7 +28,12 @@"@typescript-eslint/no-non-null-assertion": "off","@typescript-eslint/no-namespace": "off","tsdoc/syntax": "error",- "@typescript-eslint/no-unused-vars": "error",+ "@typescript-eslint/no-unused-vars": [+ "error",+ {+ "ignoreRestSiblings": true+ }+ ],"@typescript-eslint/naming-convention": ["error",{diff --git a/packages/2d/src/components/Node.ts b/packages/2d/src/components/Node.tsindex d8e0605a..a710dc81 100644--- a/packages/2d/src/components/Node.ts+++ b/packages/2d/src/components/Node.ts@@ -22,11 +22,7 @@ import {ColorSignal,SimpleVector2Signal,} from '@motion-canvas/core/lib/types';-import {- DetailedError,- ReferenceReceiver,- useLogger,-} from '@motion-canvas/core/lib/utils';+import {ReferenceReceiver, useLogger} from '@motion-canvas/core/lib/utils';import type {ComponentChild, ComponentChildren, NodeConstructor} from './types';import {Promisable} from '@motion-canvas/core/lib/threading';import {useScene2D} from '../scenes/useScene2D';@@ -47,6 +43,7 @@ import {DependencyContext,SignalValue,SimpleSignal,+ Signal,isReactive,modify,unwrap,@@ -56,8 +53,11 @@ export type NodeState = NodeProps & Record<string, any>;export interface NodeProps {ref?: ReferenceReceiver<any>;- children?: ComponentChildren;- spawner?: SignalValue<Node[]>;+ children?: SignalValue<ComponentChildren>;+ /**+ * @deprecated Use {@link children} instead.+ */+ spawner?: SignalValue<ComponentChildren>;key?: string;x?: SignalValue<number>;@@ -399,49 +399,45 @@ export class Node implements Promisable<Node> {return filters;}+ /**+ * @deprecated Use {@link children} instead.+ */@inspectable(false)@cloneable(false)- @initial([])@signal()- protected declare readonly spawner: SimpleSignal<Node[], this>;+ protected declare readonly spawner: SimpleSignal<ComponentChildren, this>;+ protected getSpawner(): ComponentChildren {+ return this.children();+ }+ protected setSpawner(value: SignalValue<ComponentChildren>) {+ this.children(value);+ }@inspectable(false)@cloneable(false)@signal()- public declare readonly children: SimpleSignal<Node[], this>;- protected setChildren(value: SignalValue<Node[]>) {- this.spawner(value);+ public declare readonly children: Signal<ComponentChildren, Node[], this>;+ protected setChildren(value: SignalValue<ComponentChildren>) {+ this.children.context.setter(value);+ if (!isReactive(value)) {+ this.spawnChildren(false, value);+ } else if (!this.hasSpawnedChildren) {+ for (const oldChild of this.realChildren) {+ oldChild.parent(null);+ }+ }}protected getChildren(): Node[] {- this.spawnChildren();- return this.realChildren;+ return this.spawnedChildren();}@computed()- protected spawnChildren() {- const children = this.spawner();- if (isReactive(this.spawner.context.raw())) {- const keep = new Set<string>();- for (const realChild of children) {- const current = realChild.parent.context.raw();- if (current && current !== this) {- throw new DetailedError(- 'The spawner returned a node that already has a parent',- 'A spawner should either create entirely new nodes or reuse nodes from a pool.',- );- }- realChild.parent(this);- keep.add(realChild.key);- }- for (const realChild of this.realChildren) {- if (!keep.has(realChild.key)) {- realChild.parent(null);- }- }- this.realChildren = children;- } else {- this.realChildren = children;+ protected spawnedChildren(): Node[] {+ const children = this.children.context.getter();+ if (isReactive(this.children.context.raw())) {+ this.spawnChildren(true, children);}+ return this.realChildren;}@computed()@@ -453,7 +449,9 @@ export class Node implements Promisable<Node> {protected view2D: View2D;private stateStack: NodeState[] = [];- private realChildren: Node[] = [];+ protected realChildren: Node[] = [];+ protected hasSpawnedChildren = false;+ private unregister: () => void;public readonly parent = createSignal<Node | null>(null);public readonly properties = getPropertiesOf(this);public readonly key: string;@@ -461,14 +459,19 @@ export class Node implements Promisable<Node> {public constructor({children, spawner, key, ...rest}: NodeProps) {const scene = useScene2D();- this.key = scene.registerNode(this, key);+ [this.key, this.unregister] = scene.registerNode(this, key);this.view2D = scene.getView();this.creationStack = new Error().stack;initializeSignals(this, rest);- this.add(children);if (spawner) {- this.children(spawner);+ useLogger().warn({+ message: 'Node.spawner() has been deprecated.',+ remarks: 'Use <code>Node.children()</code> instead.',+ inspect: this.key,+ stack: new Error().stack,+ });}+ this.children(spawner ?? children);}/**@@ -658,7 +661,7 @@ export class Node implements Promisable<Node> {}newChildren.push(...children.slice(index));- this.children(newChildren);+ this.setParsedChildren(newChildren);return this;}@@ -672,7 +675,7 @@ export class Node implements Promisable<Node> {return this;}- current.children(current.children().filter(child => child !== this));+ current.removeChild(this);this.parent(null);return this;}@@ -722,7 +725,7 @@ export class Node implements Promisable<Node> {}}- parent.children(newChildren);+ parent.setParsedChildren(newChildren);return this;}@@ -903,9 +906,10 @@ export class Node implements Promisable<Node> {* Remove all children of this node.*/public removeChildren() {- for (const node of this.children()) {- node.remove();+ for (const oldChild of this.realChildren) {+ oldChild.parent(null);}+ this.setParsedChildren([]);}/**@@ -1077,6 +1081,8 @@ export class Node implements Promisable<Node> {*/public dispose() {this.stateStack = [];+ this.unregister();+ this.unregister = null!;for (const {signal} of this) {signal?.context.dispose();}@@ -1089,8 +1095,8 @@ export class Node implements Promisable<Node> {*/public clone(customProps: NodeProps = {}): this {const props: NodeProps & Record<string, any> = {...customProps};- if (isReactive(this.spawner.context.raw())) {- props.spawner = this.spawner.context.raw();+ if (isReactive(this.children.context.raw())) {+ props.children ??= this.children.context.raw();} else if (this.children().length > 0) {props.children ??= this.children().map(child => child.clone());}@@ -1166,6 +1172,67 @@ export class Node implements Promisable<Node> {return new (<NodeConstructor<NodeProps, this>>this.constructor)(props);}+ /**+ * Set the children without parsing them.+ *+ * @remarks+ * This method assumes that the caller took care of parsing the children and+ * updating the hierarchy.+ *+ * @param value - The children to set.+ */+ protected setParsedChildren(value: Node[]) {+ this.children.context.setter(value);+ this.realChildren = value;+ }++ protected spawnChildren(reactive: boolean, children: ComponentChildren) {+ const parsedChildren = this.parseChildren(children);++ const keep = new Set<string>();+ for (const newChild of parsedChildren) {+ const current = newChild.parent.context.raw() as Node | null;+ if (current && current !== this) {+ current.removeChild(newChild);+ }+ keep.add(newChild.key);+ newChild.parent(this);+ }++ for (const oldChild of this.realChildren) {+ if (!keep.has(oldChild.key)) {+ oldChild.parent(null);+ }+ }++ this.hasSpawnedChildren = reactive;+ this.realChildren = parsedChildren;+ }++ /**+ * Parse any `ComponentChildren` into an array of nodes.+ *+ * @param children - The children to parse.+ */+ protected parseChildren(children: ComponentChildren): Node[] {+ const result: Node[] = [];+ const array = Array.isArray(children) ? children : [children];+ for (const child of array) {+ if (child instanceof Node) {+ result.push(child);+ }+ }++ return result;+ }++ /**+ * Remove the given child.+ */+ protected removeChild(child: Node) {+ this.setParsedChildren(this.children().filter(node => node !== child));+ }+/*** Whether this node should be cached or not.*/diff --git a/packages/2d/src/components/__tests__/children.test.tsx b/packages/2d/src/components/__tests__/children.test.tsxnew file mode 100644index 00000000..548d767f--- /dev/null+++ b/packages/2d/src/components/__tests__/children.test.tsx@@ -0,0 +1,142 @@+import {describe, it, expect} from 'vitest';+import {createRef, createSignal, range} from '@motion-canvas/core';+import {mockScene2D} from './mockScene2D';+import {useScene2D} from '../../scenes';+import {Node} from '../Node';++describe('children', () => {+ mockScene2D();++ it('Append children', () => {+ const view = useScene2D().getView();+ const parent = createRef<Node>();+ const childA = createRef<Node>();+ const childB = createRef<Node>();++ view.add(+ <Node ref={parent}>+ <Node ref={childA} />+ <Node ref={childB} />+ </Node>,+ );++ expect(childA().parent()).toBe(parent());+ expect(childB().parent()).toBe(parent());+ expect(parent().children()).toEqual([childA(), childB()]);+ });++ it('Clear children', () => {+ const view = useScene2D().getView();+ const parent = createRef<Node>();+ const childA = createRef<Node>();+ const childB = createRef<Node>();++ view.add(+ <Node ref={parent}>+ <Node ref={childA} />+ <Node ref={childB} />+ </Node>,+ );++ parent().removeChildren();++ expect(childA().parent()).toBe(null);+ expect(childB().parent()).toBe(null);+ expect(parent().children()).toEqual([]);+ });++ it('Replace children', () => {+ const view = useScene2D().getView();+ const parent = createRef<Node>();+ const childA = <Node />;+ const childB = <Node />;++ view.add(<Node ref={parent}>{childA}</Node>);++ parent().children(childB);++ expect(childA.parent()).toBe(null);+ expect(childB.parent()).toBe(parent());+ expect(parent().children()).toEqual([childB]);+ });++ it('Take a child from another node', () => {+ const view = useScene2D().getView();+ const parentA = createRef<Node>();+ const parentB = createRef<Node>();+ const child = createRef<Node>();++ view.add(+ <>+ <Node ref={parentA}>+ <Node ref={child} />+ </Node>+ <Node ref={parentB} />+ </>,+ );++ expect(parentA().children()).toEqual([child()]);+ expect(parentB().children()).toEqual([]);+ expect(child().parent()).toBe(parentA());++ parentB().children(child());++ expect(parentA().children()).toEqual([]);+ expect(parentB().children()).toEqual([child()]);+ expect(child().parent()).toBe(parentB());+ });++ it('Append children conditionally', () => {+ const view = useScene2D().getView();+ const parent = createRef<Node>();+ const childA = <Node />;+ const childB = <Node />;+ const predicate = createSignal(false);++ view.add(<Node ref={parent}>{() => (predicate() ? childA : childB)}</Node>);++ expect(parent().children()).toEqual([childB]);+ expect(childA.parent()).toBe(null);+ expect(childB.parent()).toBe(parent());++ predicate(true);++ expect(parent().children()).toEqual([childA]);+ expect(childA.parent()).toBe(parent());+ expect(childB.parent()).toBe(null);+ });++ it('Spawn reactive children', () => {+ const view = useScene2D().getView();+ const parent = createRef<Node>();+ const count = createSignal(3);++ view.add(+ <Node ref={parent}>{() => range(count()).map(() => <Node />)}</Node>,+ );++ expect(parent().children().length).toBe(3);++ count(5);++ expect(parent().children().length).toBe(5);+ });++ it('Replace a spawner', () => {+ const view = useScene2D().getView();+ const parent = createRef<Node>();+ const childA = <Node />;+ const childB = <Node />;++ view.add(<Node ref={parent}>{() => childA}</Node>);++ expect(parent().children()).toEqual([childA]);+ expect(childA.parent()).toBe(parent());++ parent().children(childB);++ expect(childA.parent()).toBe(null);+ expect(childB.parent()).toBe(parent());+ expect(parent().children()).toEqual([childB]);+ });+});diff --git a/packages/2d/src/scenes/Scene2D.ts b/packages/2d/src/scenes/Scene2D.tsindex 414e137c..dc4454e3 100644--- a/packages/2d/src/scenes/Scene2D.ts+++ b/packages/2d/src/scenes/Scene2D.ts@@ -13,7 +13,7 @@ import {Node, View2D} from '../components';export class Scene2D extends GeneratorScene<View2D> implements Inspectable {private view: View2D | null = null;- private readonly registeredNodes = new Map<string, Node>();+ private registeredNodes = new Map<string, Node>();private readonly nodeCounters = new Map<string, number>();private assetHash = Date.now().toString();@@ -61,6 +61,7 @@ export class Scene2D extends GeneratorScene<View2D> implements Inspectable {}}this.registeredNodes.clear();+ this.registeredNodes = new Map<string, Node>();this.nodeCounters.clear();this.recreateView();@@ -123,7 +124,7 @@ export class Scene2D extends GeneratorScene<View2D> implements Inspectable {.transformAsPoint(this.getView().localToParent().inverse());}- public registerNode(node: Node, key?: string): string {+ public registerNode(node: Node, key?: string): [string, () => void] {const className = node.constructor?.name ?? 'unknown';const counter = (this.nodeCounters.get(className) ?? 0) + 1;this.nodeCounters.set(className, counter);@@ -139,7 +140,8 @@ export class Scene2D extends GeneratorScene<View2D> implements Inspectable {key ??= `${this.name}/${className}[${counter}]`;this.registeredNodes.set(key, node);- return key;+ const currentNodeMap = this.registeredNodes;+ return [key, () => currentNodeMap.delete(key!)];}public getNode(key: any): Node | null {diff --git a/packages/docs/docs/advanced/spawners.mdx b/packages/docs/docs/advanced/spawners.mdxindex d122fff6..d321d9fa 100644--- a/packages/docs/docs/advanced/spawners.mdx+++ b/packages/docs/docs/advanced/spawners.mdx@@ -15,7 +15,7 @@ const count = createSignal(10);view.add(<Layout layout>{range(count()).map(() => (- <Circle width={32} height={32} fill={'white'} />+ <Circle size={32} fill={'white'} />))}</Layout>,);@@ -25,36 +25,46 @@ We first create the `count` signal and then use its value to generate N numberof circles.This example is not reactive - changing the `count` signal won't change the-number of circles inside the `Layout` node. We can fix that with the use of the-[`spawner`](/api/2d/components/NodeProps#spawner) property:+number of circles inside the `Layout` node. We can fix that by using a function+that returns the children instead of writing them directly:```tsxconst count = createSignal(10);view.add(- <Layout- layout- spawner={() =>- range(count()).map(() => <Circle width={32} height={32} fill={'white'} />)- }- />,+ <Layout layout>+ {() => range(count()).map(() => <Circle size={32} fill={'white'} />)}+ </Layout>,);```-`spawner` accepts a function that returns an array of nodes. These nodes will-become the new children of the `Layout` node. We can now animate our `count`-signal to check if it works:+Throughout this guide, we will refer to functions that return children as+**spawners**. Like any other signal, this function will keep track of its+dependencies and recompute its value whenever they change. We can animate our+`count` signal to see if it works:++```tsx editor+import {makeScene2D, Layout, Circle} from '@motion-canvas/2d';+import {createSignal, linear, range} from '@motion-canvas/core';++export default makeScene2D(function* (view) {+ const count = createSignal(10);++ view.add(+ <Layout layout>+ {() => range(count()).map(() => <Circle size={32} fill={'white'} />)}+ </Layout>,+ );-```ts-yield * count(5, 2);+ yield* count(3, 2, linear).wait(1).back(2);+});```-It's important to remember that (like most Node properties) `spawner` is a-signal. The function we pass to it will be invoked each time any of its-dependencies change. If the spawner happens to generate a large number of nodes-and its dependencies change every frame, it may drastically reduce the-playback's performance. To counteract this, we can use an object pool that will-let us reuse the same nodes instead of recreating them each time:+It's important to remember that creating new nodes comes with some overhead. If+our spawner happens to generate a large number of nodes and its dependencies+change every frame, it may drastically reduce the playback's performance. To+counteract this, we can use an object pool that will let us reuse the same nodes+instead of recreating them each time:```tsxconst count = createSignal(10);@@ -64,22 +74,21 @@ const pool = range(64).map(i => ());const layout = createRef<Layout>();-view.add(<Layout layout ref={layout} spawner={() => pool.slice(0, count())} />);+view.add(+ <Layout layout ref={layout}>+ {() => pool.slice(0, count())}+ </Layout>,+);```Apart from the spawner function, the pool should never be accessed directly. Use-the `children()` signal of the parent object to get references to the spawned-objects:+the helper methods on the parent object to get references to the spawned+children:```tsx// ... continuing from above ...-let spawnedCircles = layout().children() as Circle[];-yield *- all(- ...spawnedCircles.map(function* (circle) {- yield* circle.scale(1.5, 1).to(1, 1);- }),- );+let spawnedCircles = layout().childrenAs<Circle>();+yield * all(...spawnedCircles.map(circle => circle.scale(1.5, 1).to(1, 1)));```Be aware that the references returned by a call to `children()` may be