Skip to content

Visualize Your Ideas With Code

feat(2d): support tweening in applyState (#859)

Jacobb7ed2e247732
diff --git a/packages/2d/src/components/Node.ts b/packages/2d/src/components/Node.ts
index a710dc81..4c854945 100644
--- a/packages/2d/src/components/Node.ts
+++ b/packages/2d/src/components/Node.ts
@@ -24,14 +24,12 @@ import {
} from '@motion-canvas/core/lib/types';
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 {Promisable, ThreadGenerator} from '@motion-canvas/core/lib/threading';
import {useScene2D} from '../scenes/useScene2D';
import {
clamp,
- deepLerp,
easeInOutCubic,
TimingFunction,
- tween,
} from '@motion-canvas/core/lib/tweening';
import {threadable} from '@motion-canvas/core/lib/decorators';
import {drawLine} from '../utils';
@@ -48,6 +46,7 @@ import {
modify,
unwrap,
} from '@motion-canvas/core/lib/signals';
+import {all} from '@motion-canvas/core';
export type NodeState = NodeProps & Record<string, any>;
@@ -1093,8 +1092,8 @@ export class Node implements Promisable<Node> {
*
* @param customProps - Properties to override.
*/
- public clone(customProps: NodeProps = {}): this {
- const props: NodeProps & Record<string, any> = {...customProps};
+ public clone(customProps: NodeState = {}): this {
+ const props = {...customProps};
if (isReactive(this.children.context.raw())) {
props.children ??= this.children.context.raw();
} else if (this.children().length > 0) {
@@ -1106,11 +1105,14 @@ export class Node implements Promisable<Node> {
if (meta.compound) {
for (const [key, property] of meta.compoundEntries) {
if (property in props) continue;
- props[property] = (<Record<string, SimpleSignal<any>>>(
+ const component = (<Record<string, SimpleSignal<any>>>(
(<unknown>signal)
- ))[key].context.raw();
+ ))[key];
+ if (!component.context.isInitial()) {
+ props[property] = component.context.raw();
+ }
}
- } else {
+ } else if (!signal.context.isInitial()) {
props[key] = signal.context.raw();
}
}
@@ -1127,8 +1129,8 @@ export class Node implements Promisable<Node> {
*
* @param customProps - Properties to override.
*/
- public snapshotClone(customProps: NodeProps = {}): this {
- const props: NodeProps & Record<string, any> = {
+ public snapshotClone(customProps: NodeState = {}): this {
+ const props = {
...this.getState(),
...customProps,
};
@@ -1149,8 +1151,8 @@ export class Node implements Promisable<Node> {
*
* @param customProps - Properties to override.
*/
- public reactiveClone(customProps: NodeProps = {}): this {
- const props: NodeProps & Record<string, any> = {...customProps};
+ public reactiveClone(customProps: NodeState = {}): this {
+ const props = {...customProps};
if (this.children().length > 0) {
props.children ??= this.children().map(child => child.reactiveClone());
}
@@ -1581,13 +1583,43 @@ export class Node implements Promisable<Node> {
*
* @param state - The state to apply to the node.
*/
- public applyState(state: NodeState) {
+ public applyState(state: NodeState): void;
+ /**
+ * Smoothly transition between the current state of the node and the given
+ * state.
+ *
+ * @param state - The state to transition to.
+ * @param duration - The duration of the transition.
+ * @param timing - The timing function to use for the transition.
+ */
+ public applyState(
+ state: NodeState,
+ duration: number,
+ timing?: TimingFunction,
+ ): ThreadGenerator;
+ public applyState(
+ state: NodeState,
+ duration?: number,
+ timing: TimingFunction = easeInOutCubic,
+ ): ThreadGenerator | void {
+ if (duration === undefined) {
+ for (const key in state) {
+ const signal = this.signalByKey(key);
+ if (signal) {
+ signal(state[key]);
+ }
+ }
+ }
+
+ const tasks: ThreadGenerator[] = [];
for (const key in state) {
const signal = this.signalByKey(key);
- if (signal) {
- signal(state[key]);
+ if (state[key] !== signal.context.raw()) {
+ tasks.push(signal(state[key], duration!, timing));
}
}
+
+ return all(...tasks);
}
/**
@@ -1610,8 +1642,31 @@ export class Node implements Promisable<Node> {
* node to a previously saved state. Restoring a node to a previous state
* removes that state from the state stack.
*
- * Providing a duration will tween the node to the restored state. Otherwise,
- * it will be restored immediately.
+ * @example
+ * ```tsx
+ * const node = <Circle width={100} height={100} fill={"lightseagreen"} />
+ *
+ * view.add(node);
+ *
+ * // Save the node's current state
+ * node.save();
+ *
+ * // Modify some of the node's properties
+ * yield* node.scale(2, 1);
+ * yield* node.fill('hotpink', 1);
+ *
+ * // Restore the node to its saved state
+ * node.restore();
+ * ```
+ */
+ public restore(): void;
+ /**
+ * Tween the node to its last saved state.
+ *
+ * @remarks
+ * This method can be used together with the {@link save} method to restore a
+ * node to a previously saved state. Restoring a node to a previous state
+ * removes that state from the state stack.
*
* @example
* ```tsx
@@ -1626,44 +1681,23 @@ export class Node implements Promisable<Node> {
* yield* node.scale(2, 1);
* yield* node.fill('hotpink', 1);
*
- * // Restore the node to its saved state over 1 second
+ * // Tween the node to its saved state over 1 second
* yield* node.restore(1);
* ```
*
* @param duration - The duration of the transition.
* @param timing - The timing function to use for the transition.
*/
- public restore(duration?: number, timing: TimingFunction = easeInOutCubic) {
+ public restore(duration: number, timing?: TimingFunction): ThreadGenerator;
+ public restore(
+ duration?: number,
+ timing: TimingFunction = easeInOutCubic,
+ ): ThreadGenerator | void {
const state = this.stateStack.pop();
- if (state === undefined) {
- return;
- }
-
- if (duration === undefined) {
- this.applyState(state);
- return;
+ if (state !== undefined) {
+ return this.applyState(state, duration!, timing);
}
-
- const currentState = this.getState();
- for (const key in state) {
- // Filter out any properties that haven't changed between the current and
- // previous states, so we don't perform unnecessary tweens.
- if (currentState[key] === state[key]) {
- delete state[key];
- }
- }
-
- return tween(duration, value => {
- const t = timing(value);
-
- const nextState = Object.keys(state).reduce((newState, key) => {
- newState[key] = deepLerp(currentState[key], state[key], t);
- return newState;
- }, {} as NodeState);
-
- this.applyState(nextState);
- });
}
public *[Symbol.iterator]() {
diff --git a/packages/2d/src/components/__tests__/clone.test.tsx b/packages/2d/src/components/__tests__/clone.test.tsx
new file mode 100644
index 00000000..c8fee256
--- /dev/null
+++ b/packages/2d/src/components/__tests__/clone.test.tsx
@@ -0,0 +1,126 @@
+import {describe, it, expect} from 'vitest';
+import {createSignal, range, Vector2} from '@motion-canvas/core';
+import {mockScene2D} from './mockScene2D';
+import {Circle} from '../Circle';
+import {Node} from '../Node';
+
+describe('clone', () => {
+ mockScene2D();
+
+ it('Normal clone', () => {
+ const signal = createSignal(45);
+ const template = (
+ <Circle lineWidth={8} startAngle={signal} end={0.5} />
+ ) as Circle;
+ const clone = template.clone({end: 0});
+
+ expect(clone.lineWidth()).toBe(8);
+ expect(clone.startAngle()).toBe(45);
+ expect(clone.end()).toBe(0);
+ expect(clone.startArrow.context.isInitial()).toBe(true);
+
+ signal(90);
+
+ expect(clone.startAngle()).toBe(90);
+ });
+
+ it('Reactive clone', () => {
+ const signal = createSignal(45);
+ const template = (
+ <Circle lineWidth={8} startAngle={signal} end={0.5} />
+ ) as Circle;
+ const clone = template.reactiveClone({end: 0});
+
+ expect(clone.lineWidth()).toBe(8);
+ expect(clone.startAngle()).toBe(45);
+ expect(clone.end()).toBe(0);
+ expect(clone.startArrow.context.isInitial()).toBe(false);
+
+ template.lineWidth(16);
+ template.startArrow(true);
+ template.end(0.25);
+ signal(90);
+
+ expect(clone.lineWidth()).toBe(16);
+ expect(clone.startAngle()).toBe(90);
+ expect(clone.startArrow()).toBe(true);
+ expect(clone.end()).toBe(0);
+ });
+
+ it('Snapshot clone', () => {
+ const signal = createSignal(45);
+ const template = (
+ <Circle lineWidth={8} startAngle={signal} end={0.5} />
+ ) as Circle;
+ const clone = template.snapshotClone({end: 0});
+
+ expect(clone.lineWidth()).toBe(8);
+ expect(clone.startAngle()).toBe(45);
+ expect(clone.end()).toBe(0);
+ expect(clone.startArrow.context.isInitial()).toBe(true);
+
+ template.lineWidth(16);
+ template.startArrow(true);
+ signal(90);
+
+ expect(clone.lineWidth()).toBe(8);
+ expect(clone.startAngle()).toBe(45);
+ expect(clone.startArrow()).toBe(false);
+ });
+
+ it('Clone compound signal', () => {
+ const signal = Vector2.createSignal(200);
+ const template = (<Circle offset={1} position={signal} />) as Circle;
+ const clone = template.clone({x: 100, offsetY: -1});
+
+ expect(clone.x()).toBe(100);
+ expect(clone.y()).toBe(200);
+ expect(clone.offset.x()).toBe(1);
+ expect(clone.offset.y()).toBe(-1);
+
+ signal([300, 400]);
+
+ expect(clone.x()).toBe(100);
+ expect(clone.y()).toBe(400);
+ });
+
+ it('Clone children', () => {
+ const signal = createSignal(45);
+ const template = (
+ <Node>
+ <Circle lineWidth={8} startAngle={signal} />
+ </Node>
+ );
+ const clone = template.clone();
+
+ expect(clone.children().length).toBe(1);
+ expect(clone.childAs(0)).not.toBe(template.childAs(0));
+ expect(clone.childAs<Circle>(0)!.lineWidth()).toBe(8);
+ expect(clone.childAs<Circle>(0)!.startAngle()).toBe(45);
+
+ signal(90);
+
+ expect(clone.childAs<Circle>(0)!.startAngle()).toBe(90);
+ });
+
+ it('Clone spawner', () => {
+ const count = createSignal(3);
+ const template = (
+ <Node>
+ {() =>
+ range(count()).map(() => (
+ <Circle lineWidth={8} startAngle={count} end={0.5} />
+ ))
+ }
+ </Node>
+ );
+ const clone = template.clone();
+
+ expect(clone.children().length).toBe(3);
+ expect(clone.childAs(0)).not.toBe(template.childAs(0));
+
+ count(5);
+
+ expect(clone.children().length).toBe(5);
+ });
+});
diff --git a/packages/2d/src/components/__tests__/generatorTest.ts b/packages/2d/src/components/__tests__/generatorTest.ts
new file mode 100644
index 00000000..213014b6
--- /dev/null
+++ b/packages/2d/src/components/__tests__/generatorTest.ts
@@ -0,0 +1,27 @@
+import {ThreadGeneratorFactory, threads} from '@motion-canvas/core';
+import {useScene2D} from '../../scenes';
+import {View2D} from '../View2D';
+
+/**
+ * Turn a generator factory into a test function.
+ *
+ * @example
+ * ```ts
+ * it(
+ * 'Example test',
+ * generatorTest(function* () {
+ * yield* waitFor(1);
+ * expect(useTime()).toBe(1);
+ * }),
+ * );
+ * ```
+ *
+ * @param factory - The generator factory to test.
+ */
+export function generatorTest(factory: ThreadGeneratorFactory<View2D>) {
+ return () => {
+ const view = useScene2D().getView();
+ const tasks = threads(() => factory(view));
+ [...tasks];
+ };
+}
diff --git a/packages/2d/src/components/__tests__/state.test.tsx b/packages/2d/src/components/__tests__/state.test.tsx
new file mode 100644
index 00000000..0e346654
--- /dev/null
+++ b/packages/2d/src/components/__tests__/state.test.tsx
@@ -0,0 +1,60 @@
+import {describe, it, expect} from 'vitest';
+import {createSignal, join, waitFor} from '@motion-canvas/core';
+import {mockScene2D} from './mockScene2D';
+import {Circle} from '../Circle';
+import {generatorTest} from './generatorTest';
+
+describe('state', () => {
+ mockScene2D();
+
+ it('Restoring state', () => {
+ const signal = createSignal(45);
+ const circle = (
+ <Circle lineWidth={8} startAngle={signal} end={0.5} />
+ ) as Circle;
+ circle.save();
+
+ circle.lineWidth(16);
+ circle.startAngle(90);
+ circle.end(0.25);
+
+ circle.restore();
+
+ expect(circle.lineWidth()).toBe(8);
+ expect(circle.startAngle()).toBe(45);
+ expect(circle.end()).toBe(0.5);
+
+ signal(180);
+
+ expect(circle.startAngle()).toBe(45);
+ expect(circle.startArrow.context.isInitial()).toBe(true);
+ });
+
+ it(
+ 'Tweening state',
+ generatorTest(function* () {
+ const signal = createSignal(20);
+ const circle = (
+ <Circle lineWidth={8} startAngle={signal} end={0.5} />
+ ) as Circle;
+ circle.save();
+
+ circle.lineWidth(16);
+ circle.startAngle(40);
+ circle.end(0.3);
+
+ const task = yield circle.restore(2);
+ yield* waitFor(1);
+
+ expect(circle.lineWidth()).closeTo(12, 0.0001);
+ expect(circle.startAngle()).closeTo(30, 0.0001);
+ expect(circle.end()).closeTo(0.4, 0.0001);
+
+ yield* join(task);
+
+ expect(circle.lineWidth()).toBe(8);
+ expect(circle.startAngle()).toBe(20);
+ expect(circle.end()).toBe(0.5);
+ }),
+ );
+});
diff --git a/packages/core/src/signals/CompoundSignalContext.ts b/packages/core/src/signals/CompoundSignalContext.ts
index e7dea904..a9cfe1ee 100644
--- a/packages/core/src/signals/CompoundSignalContext.ts
+++ b/packages/core/src/signals/CompoundSignalContext.ts
@@ -111,4 +111,19 @@ export class CompoundSignalContext<
}
return this.owner;
}
+
+ public override isInitial(): boolean {
+ for (const [, signal] of this.signals) {
+ if (!signal.isInitial()) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public override raw() {
+ return Object.fromEntries(
+ this.signals.map(([key, property]) => [key, property.context.raw()]),
+ ) as TSetterValue;
+ }
}