Visualize Your Ideas With Code
feat: replaced `scene.transition` with `useTransition` (#68)
Ross Esmondf521115889a7
diff --git a/README.md b/README.mdindex fb5e7c68..39be9996 100644--- a/README.md+++ b/README.md@@ -78,8 +78,6 @@ Otherwise, below are the steps to set it up manually:import {waitFor} from '@motion-canvas/core/lib/flow';export default makeKonvaScene(function* example(view) {- yield* scene.transition();-// animation code goes hereyield* waitFor(5);diff --git a/src/Project.ts b/src/Project.tsindex 8e400ca9..006be88c 100644--- a/src/Project.ts+++ b/src/Project.ts@@ -161,12 +161,8 @@ export class Project {);}- this.context.save();this.previousScene?.render(this.context, this.canvas);- this.context.restore();- this.context.save();this.currentScene.current?.render(this.context, this.canvas);- this.context.restore();}public reload(runners: SceneDescription[]) {@@ -184,10 +180,7 @@ export class Project {public async next(): Promise<boolean> {if (this.previousScene) {await this.previousScene.next();- if (- !this.currentScene.current ||- this.currentScene.current.isAfterTransitionIn()- ) {+ if (!this.currentScene.current) {this.previousScene = null;}}@@ -196,6 +189,12 @@ export class Project {if (this.currentScene.current) {await this.currentScene.current.next();+ if (+ this.previousScene &&+ this.currentScene.current.isAfterTransitionIn()+ ) {+ this.previousScene = null;+ }if (this.currentScene.current.canTransitionOut()) {this.previousScene = this.currentScene.current;this.currentScene.current = this.getNextScene(this.previousScene);diff --git a/src/events/EventDispatcherBase.ts b/src/events/EventDispatcherBase.tsindex a027c02b..d0637709 100644--- a/src/events/EventDispatcherBase.ts+++ b/src/events/EventDispatcherBase.ts@@ -32,6 +32,13 @@ export abstract class EventDispatcherBase<this.subscribers.delete(handler);}+ /**+ * Unsubscribe all subscribers from the event.+ */+ public clear() {+ this.subscribers.clear();+ }+protected notifySubscribers(value: TValue): ReturnType<THandler>[] {return [...this.subscribers].map(handler => handler(value));}diff --git a/src/player/Player.ts b/src/player/Player.tsindex 180b6ef6..e082709d 100644--- a/src/player/Player.ts+++ b/src/player/Player.ts@@ -24,7 +24,6 @@ export interface PlayerState extends Record<string, unknown> {}interface PlayerCommands {- reset: boolean;seek: number;recalculate: boolean;}@@ -73,7 +72,6 @@ export class Player {private requestId: number = null;private commands: PlayerCommands = {- reset: true,seek: -1,recalculate: true,};@@ -116,7 +114,6 @@ export class Player {private consumeCommands(): PlayerCommands {const commands = {...this.commands};- this.commands.reset = false;this.commands.seek = -1;this.commands.recalculate = false;diff --git a/src/scenes/GeneratorScene.ts b/src/scenes/GeneratorScene.tsindex 3c881978..0d596c5a 100644--- a/src/scenes/GeneratorScene.ts+++ b/src/scenes/GeneratorScene.ts@@ -5,13 +5,8 @@ import {EventDispatcher, ValueDispatcher} from '../events';import {Project} from '../Project';import {decorate, threadable} from '../decorators';import {setProject, setScene} from '../utils';-import {CachedSceneData, Scene, SceneMetadata} from './Scene';-import {- isTransitionable,- SceneTransition,- Transitionable,- TransitionContext,-} from './Transitionable';+import {CachedSceneData, Scene, SceneMetadata, SceneRenderEvent} from './Scene';+import {LifecycleEvents} from './LifecycleEvents';import {Threadable} from './Threadable';import {Size} from '../types';import {SceneState} from './SceneState';@@ -26,7 +21,7 @@ export interface ThreadGeneratorFactory<T> {* Uses generators to control the animation.*/export abstract class GeneratorScene<T>- implements Scene<ThreadGeneratorFactory<T>>, Transitionable, Threadable+ implements Scene<ThreadGeneratorFactory<T>>, Threadable{public readonly timeEvents: TimeEvents;public readonly meta: Meta<SceneMetadata>;@@ -64,23 +59,24 @@ export abstract class GeneratorScene<T>}private readonly thread = new ValueDispatcher<Thread>(null);- public get onBeforeRendered() {- return this.beforeRendered.subscribable;+ public get onRenderLifecycle() {+ return this.renderLifecycle.subscribable;}- protected readonly beforeRendered =- new EventDispatcher<CanvasRenderingContext2D>();-- public get onAfterRendered() {- return this.afterRendered.subscribable;- }- protected readonly afterRendered =- new EventDispatcher<CanvasRenderingContext2D>();+ protected readonly renderLifecycle = new EventDispatcher<+ [SceneRenderEvent, CanvasRenderingContext2D]+ >();public get onReset() {return this.afterReset.subscribable;}private readonly afterReset = new EventDispatcher<void>();+ public readonly LifecycleEvents: LifecycleEvents = new LifecycleEvents(this);++ public get previous() {+ return this.previousScene;+ }+private previousScene: Scene = null;private runner: ThreadGenerator;private state: SceneState = SceneState.Initial;@@ -139,13 +135,20 @@ export abstract class GeneratorScene<T>cached.transitionDuration = -1;await this.reset();while (!this.canTransitionOut()) {- if (cached.transitionDuration < 0 && this.isAfterTransitionIn()) {+ if (+ cached.transitionDuration < 0 &&+ this.state === SceneState.AfterTransitionIn+ ) {cached.transitionDuration = this.project.frame - cached.firstFrame;}this.project.frame++;await this.next();}+ if (cached.transitionDuration === -1) {+ cached.transitionDuration = 0;+ }+cached.lastFrame = this.project.frame;cached.duration = cached.lastFrame - cached.firstFrame;// Prevent the page from becoming unresponsive.@@ -185,7 +188,11 @@ export abstract class GeneratorScene<T>this.thread.current = thread;},);- this.state = SceneState.Initial;+ if (this.cache.current.transitionDuration === 0) {+ this.state = SceneState.AfterTransitionIn;+ } else {+ this.state = SceneState.Initial;+ }this.afterReset.dispatch();await this.next();}@@ -209,23 +216,26 @@ export abstract class GeneratorScene<T>return this.state === SceneState.Finished;}- public enterCanTransitionOut() {- if (this.state === SceneState.AfterTransitionIn) {- this.state = SceneState.CanTransitionOut;+ public enterAfterTransitionIn() {+ if (this.state === SceneState.Initial) {+ this.state = SceneState.AfterTransitionIn;} else {console.warn(- `Scene ${this.name} was marked as finished in an unexpected state: `,+ `Scene ${this.name} transitioned in an unexpected state: `,this.state,);}}- public enterAfterTransitionIn() {- if (this.state === SceneState.Initial) {- this.state = SceneState.AfterTransitionIn;+ public enterCanTransitionOut() {+ if (+ this.state === SceneState.AfterTransitionIn ||+ this.state === SceneState.Initial // only on recalculate+ ) {+ this.state = SceneState.CanTransitionOut;} else {console.warn(- `Scene ${this.name} transitioned in an unexpected state: `,+ `Scene ${this.name} was marked as finished in an unexpected state: `,this.state,);}@@ -245,26 +255,4 @@ export abstract class GeneratorScene<T>return `${this.name}.${type}.${id}`;}-- //#region Transitionable Interface-- @threadable()- public *transition(transitionRunner?: SceneTransition): ThreadGenerator {- const previous = isTransitionable(this.previousScene)- ? this.previousScene.getTransitionContext()- : null;-- if (!transitionRunner) {- previous?.visible(false);- this.enterAfterTransitionIn();- return;- }-- yield* transitionRunner(this.getTransitionContext(), previous);- this.enterAfterTransitionIn();- }-- public abstract getTransitionContext(): TransitionContext;-- //#endregion}diff --git a/src/scenes/KonvaScene.ts b/src/scenes/KonvaScene.tsindex cf8bc312..54287032 100644--- a/src/scenes/KonvaScene.ts+++ b/src/scenes/KonvaScene.ts@@ -1,11 +1,10 @@import {Container} from 'konva/lib/Container';-import {Scene, SceneDescription} from './Scene';+import {Scene, SceneDescription, SceneRenderEvent} from './Scene';import {HitCanvas, SceneCanvas} from 'konva/lib/Canvas';import {Shape, shapes} from 'konva/lib/Shape';import {Group} from 'konva/lib/Group';import {GeneratorScene, ThreadGeneratorFactory} from './GeneratorScene';import {useScene} from '../utils';-import {SceneTransition, TransitionContext} from './Transitionable';import {Inspectable,InspectedElement,@@ -16,7 +15,6 @@ import {Util} from 'konva/lib/Util';import {Node} from 'konva/lib/Node';import {Konva} from 'konva/lib/Global';import {NODE_ID} from '../symbols';-import {ThreadGenerator} from '../threading';Konva.autoDrawEnabled = false;@@ -55,7 +53,7 @@ export function makeKonvaScene(};}-class KonvaView extends Container implements TransitionContext {+class KonvaView extends Container {public constructor(private readonly scene: KonvaScene) {super();}@@ -67,13 +65,6 @@ class KonvaView extends Container implements TransitionContext {this.scene.enterCanTransitionOut();}- /**- * @inheritDoc Transitionable.transition- */- public transition(transitionRunner?: SceneTransition): ThreadGenerator {- return this.scene.transition(transitionRunner);- }-public updateLayout() {super.updateLayout();let limit = 10;@@ -125,9 +116,15 @@ export class KonvaScenesceneCanvas.getContext()._context = context;}- this.beforeRendered.dispatch(context);+ context.save();+ this.renderLifecycle.dispatch([SceneRenderEvent.BeforeRender, context]);+ context.save();+ this.renderLifecycle.dispatch([SceneRenderEvent.BeginRender, context]);this.view.drawScene(sceneCanvas);- this.afterRendered.dispatch(context);+ this.renderLifecycle.dispatch([SceneRenderEvent.FinishRender, context]);+ context.restore();+ this.renderLifecycle.dispatch([SceneRenderEvent.AfterRender, context]);+ context.restore();}public reset(previousScene: Scene = null) {@@ -136,10 +133,6 @@ export class KonvaScenereturn super.reset(previousScene);}- public getTransitionContext(): TransitionContext {- return this.view;- }-//#region Inspectable Interfacepublic inspectPosition(x: number, y: number): InspectedElement | null {diff --git a/src/scenes/LifecycleEvents.ts b/src/scenes/LifecycleEvents.tsnew file mode 100644index 00000000..be5cd652--- /dev/null+++ b/src/scenes/LifecycleEvents.ts@@ -0,0 +1,52 @@+import {Scene, SceneRenderEvent} from './Scene';+import {EventDispatcher} from '../events';++/**+ * Lifecycle events for {@link Scene} that are cleared on every reset.+ */+export class LifecycleEvents {+ public get onBeforeRender() {+ return this.beforeRender.subscribable;+ }+ protected readonly beforeRender =+ new EventDispatcher<CanvasRenderingContext2D>();++ public get onBeginRender() {+ return this.beginRender.subscribable;+ }+ protected readonly beginRender =+ new EventDispatcher<CanvasRenderingContext2D>();++ public get onFinishRender() {+ return this.finishRender.subscribable;+ }+ protected readonly finishRender =+ new EventDispatcher<CanvasRenderingContext2D>();++ public get onAfterRender() {+ return this.afterRender.subscribable;+ }+ protected readonly afterRender =+ new EventDispatcher<CanvasRenderingContext2D>();++ public constructor(private readonly scene: Scene) {+ this.scene.onRenderLifecycle.subscribe(([event, ctx]) => {+ switch (event) {+ case SceneRenderEvent.BeforeRender:+ return this.beforeRender.dispatch(ctx);+ case SceneRenderEvent.BeginRender:+ return this.beginRender.dispatch(ctx);+ case SceneRenderEvent.FinishRender:+ return this.finishRender.dispatch(ctx);+ case SceneRenderEvent.AfterRender:+ return this.afterRender.dispatch(ctx);+ }+ });+ this.scene.onReset.subscribe(() => {+ this.beforeRender.clear();+ this.beginRender.clear();+ this.finishRender.clear();+ this.afterRender.clear();+ });+ }+}diff --git a/src/scenes/Scene.ts b/src/scenes/Scene.tsindex 901c61e4..d458aa02 100644--- a/src/scenes/Scene.ts+++ b/src/scenes/Scene.ts@@ -3,6 +3,7 @@ import {Meta, Metadata} from '../Meta';import {SavedTimeEvent, TimeEvents} from './TimeEvents';import {SubscribableEvent, SubscribableValueEvent} from '../events';import {Size} from '../types';+import {LifecycleEvents} from './LifecycleEvents';export interface SceneMetadata extends Metadata {timeEvents: SavedTimeEvent[];@@ -53,6 +54,28 @@ export interface CachedSceneData {duration: number;}+/**+ * Signifies the various stages of a {@link Scene}'s render lifecycle.+ */+export enum SceneRenderEvent {+ /**+ * Occurs before the render starts when the Scene transitions are applied.+ */+ BeforeRender,+ /**+ * Occurs at the beginning of a render when the Scene's `useContext` handlers are applied.+ */+ BeginRender,+ /**+ * Occurs at the end of a render when the Scene's `useContextAfter` handlers are applied.+ */+ FinishRender,+ /**+ * Occurs after a render ends.+ */+ AfterRender,+}+/*** The main interface for scenes.*@@ -109,18 +132,18 @@ export interface Scene<T = unknown> {get onRecalculated(): SubscribableEvent<void>;/**- * Triggered before the scene is rendered with the Context2D.- *- * @event CanvasRenderingContext2D+ * The scene's {@link LifecycleEvents}.*/- get onBeforeRendered(): SubscribableEvent<CanvasRenderingContext2D>;+ get LifecycleEvents(): LifecycleEvents;/**- * Triggered after the scene is rendered with the Context2D.+ * Triggered at various stages of the render lifecycle with an event title and a Context2D.*- * @event CanvasRenderingContext2D+ * @event [SceneRenderEvent, CanvasRenderingContext2D]*/- get onAfterRendered(): SubscribableEvent<CanvasRenderingContext2D>;+ get onRenderLifecycle(): SubscribableEvent<+ [SceneRenderEvent, CanvasRenderingContext2D]+ >;/*** Triggered when the scene is reset.@@ -129,6 +152,11 @@ export interface Scene<T = unknown> {*/get onReset(): SubscribableEvent<void>;+ /**+ * The scene directly before this scene, or null if omitted for performance.+ */+ get previous(): Scene;+/*** Render the scene onto a canvas.*@@ -198,7 +226,12 @@ export interface Scene<T = unknown> {isFinished(): boolean;/**- * Enter the {@link SceneState.CanTransitionOut} state?+ * Enter the {@link SceneState.AfterTransitionIn} state.+ */+ enterAfterTransitionIn(): void;++ /**+ * Enter the {@link SceneState.CanTransitionOut} state.*/enterCanTransitionOut(): void;diff --git a/src/scenes/Transitionable.ts b/src/scenes/Transitionable.tsdeleted file mode 100644index aea73fd4..00000000--- a/src/scenes/Transitionable.ts+++ /dev/null@@ -1,78 +0,0 @@-import {ThreadGenerator} from '../threading';-import {Vector2} from '../types';--/**- * Describes the transition context of a scene.- *- * This context is used by scene transitions to modify the way scenes are- * displayed in a renderer-agnostic way.- *- * It allows transitions to work across different scenes.- */-export interface TransitionContext {- /**- * Set the position of the scene.- * @param value- */- position(value: Vector2): void;-- /**- * Set the scale of the scene.- * @param value- */- scale(value: Vector2): void;-- /**- * Set the rotation of the scene.- *- * @param value- */- rotation(value: number): void;-- /**- * Set the opacity of the scene.- * @param value- */- opacity(value: number): void;-- /**- * Set whether the scene should be visible.- *- * @param value- */- visible(value: boolean): void;-}--/**- * Describes a function that performs a transition.- */-export interface SceneTransition {- /**- * A function that performs a transition.- *- * @param next the context of the scene that should appear next.- * @param previous If present, the context of the scene that should disappear.- */- (next: TransitionContext, previous?: TransitionContext): ThreadGenerator;-}--/**- * Scenes can implement this interface to support transitions.- */-export interface Transitionable {- /**- * Get the transition context for this scene.- */- getTransitionContext(): TransitionContext;-- /**- * Perform the transition.- *- * @param transitionRunner A generator function that runs the transition.- */- transition(transitionRunner?: SceneTransition): ThreadGenerator;-}--export function isTransitionable(value: any): value is Transitionable {- return value && typeof value === 'object' && 'getTransitionContext' in value;-}diff --git a/src/scenes/index.ts b/src/scenes/index.tsindex 69fc0a02..4439c577 100644--- a/src/scenes/index.ts+++ b/src/scenes/index.ts@@ -5,4 +5,4 @@ export * from './Scene';export * from './SceneState';export * from './Threadable';export * from './TimeEvents';-export * from './Transitionable';+export * from './LifecycleEvents';diff --git a/src/transitions/index.ts b/src/transitions/index.tsindex a0e4331e..5164b00c 100644--- a/src/transitions/index.ts+++ b/src/transitions/index.ts@@ -1 +1,2 @@export * from './slideTransition';+export * from './useTransition';diff --git a/src/transitions/slideTransition.ts b/src/transitions/slideTransition.tsindex 13077f0c..08bbfd90 100644--- a/src/transitions/slideTransition.ts+++ b/src/transitions/slideTransition.ts@@ -1,26 +1,28 @@-import type {SceneTransition} from '../scenes';import {Direction, originPosition} from '../types';import {easeInOutCubic, tween, vector2dTween} from '../tweening';import {useScene} from '../utils';+import {useTransition} from './';-export function slideTransition(- direction: Direction = Direction.Top,-): SceneTransition {- return (next, previous) => {- const size = useScene().getSize();- const position = originPosition(direction, size.width, size.height);- return tween(0.6, value => {- previous?.position(- vector2dTween(- {x: 0, y: 0},- {x: -position.x, y: -position.y},- easeInOutCubic(value),- ),+export function slideTransition(direction: Direction = Direction.Top) {+ const size = useScene().getSize();+ const position = originPosition(direction, size.width, size.height);+ let ppos = {x: 0, y: 0};+ let cpos = {x: 0, y: 0};+ const endTransition = useTransition(+ ctx => ctx.translate(cpos.x, cpos.y),+ ctx => ctx.translate(ppos.x, ppos.y),+ );+ return tween(+ 0.6,+ value => {+ ppos = vector2dTween(+ {x: 0, y: 0},+ {x: -position.x, y: -position.y},+ easeInOutCubic(value),);- next.position(- vector2dTween(position, {x: 0, y: 0}, easeInOutCubic(value)),- );- });- };+ cpos = vector2dTween(position, {x: 0, y: 0}, easeInOutCubic(value));+ },+ endTransition,+ );}diff --git a/src/transitions/useTransition.ts b/src/transitions/useTransition.tsnew file mode 100644index 00000000..0d541e76--- /dev/null+++ b/src/transitions/useTransition.ts@@ -0,0 +1,30 @@+import {useScene} from '../utils';++/**+ * Transition to the current scene by altering the Context2D before scenes are rendered.+ *+ * @param current - The callback to use before the current scene is rendered.+ * @param previous - The callback to use before the previous scene is rendered.+ */+export function useTransition(+ current: (ctx: CanvasRenderingContext2D) => void,+ previous?: (ctx: CanvasRenderingContext2D) => void,+) {+ if (previous == null) {+ previous = () => {+ // do nothing+ };+ }++ const scene = useScene();+ const prior = scene.previous;++ const unsubPrev = prior?.LifecycleEvents.onBeforeRender.subscribe(previous);+ const unsubNext = scene.LifecycleEvents.onBeforeRender.subscribe(current);++ return () => {+ scene.enterAfterTransitionIn();+ unsubPrev?.();+ unsubNext();+ };+}diff --git a/src/utils/useContext.ts b/src/utils/useContext.tsindex 66646483..d496bfd0 100644--- a/src/utils/useContext.ts+++ b/src/utils/useContext.ts@@ -1,28 +1,23 @@import {useScene} from './useScene';-import type {Scene} from '../scenes';--function subscribe(fn: (scene: Scene) => () => void) {- const scene = useScene();- if (scene == null) {- throw new Error('no scene found from which to use the context');- }- const unsubScene = fn(scene);- const unsubReset = scene.onReset.subscribe(unsubAll);- function unsubAll() {- unsubScene();- unsubReset();- }- return unsubAll;-}+/**+ * Provide a function to access the Context2D before the scene is rendered.+ *+ * @param callback - The function that will be provided the context before render.+ */export function useContext(callback: (ctx: CanvasRenderingContext2D) => void,): () => void {- return subscribe(scene => scene.onBeforeRendered.subscribe(callback));+ return useScene().LifecycleEvents.onBeginRender.subscribe(callback);}+/**+ * Provide a function to access the Context2D after the scene is rendered.+ *+ * @param callback - The function that will be provided the context after render.+ */export function useContextAfter(callback: (ctx: CanvasRenderingContext2D) => void,): () => void {- return subscribe(scene => scene.onAfterRendered.subscribe(callback));+ return useScene().LifecycleEvents.onFinishRender.subscribe(callback);}