Visualize Your Ideas With Code
feat: add video node (#86)
Jacobf4aa65437a18
diff --git a/packages/2d/src/components/CodeBlock.ts b/packages/2d/src/components/CodeBlock.tsindex e4b767d0..5b48c4d0 100644--- a/packages/2d/src/components/CodeBlock.ts+++ b/packages/2d/src/components/CodeBlock.ts@@ -1,5 +1,9 @@import {computed, initial, property} from '../decorators';-import {Signal, SignalValue} from '@motion-canvas/core/lib/utils';+import {+ createComputedAsync,+ Signal,+ SignalValue,+} from '@motion-canvas/core/lib/utils';import {Shape, ShapeProps} from './Shape';import {CodeTree, parse, diff, ready, MorphToken} from 'code-fns';import {@@ -16,6 +20,11 @@ export interface CodeProps extends ShapeProps {}export class CodeBlock extends Shape {+ private static initialized = createComputedAsync(+ () => ready().then(() => true),+ false,+ );+@initial('')@property()public declare readonly code: Signal<CodeTree, this>;@@ -35,9 +44,9 @@ export class CodeBlock extends Shape {}}- protected override collectAsyncResources(resources: Promise<any>[]): void {- super.collectAsyncResources(resources);- resources.push(ready());+ protected override collectAsyncResources(): void {+ super.collectAsyncResources();+ CodeBlock.initialized();}@threadable()@@ -61,6 +70,8 @@ export class CodeBlock extends Shape {}protected override draw(context: CanvasRenderingContext2D) {+ if (!CodeBlock.initialized()) return;+this.requestFontUpdate();this.applyStyle(context);context.font = this.styles.font;diff --git a/packages/2d/src/components/Image.ts b/packages/2d/src/components/Image.tsindex 7de913ba..83e36bf1 100644--- a/packages/2d/src/components/Image.ts+++ b/packages/2d/src/components/Image.ts@@ -1,8 +1,13 @@-import {Signal, SignalValue} from '@motion-canvas/core/lib/utils';+import {+ collectPromise,+ Signal,+ SignalValue,+} from '@motion-canvas/core/lib/utils';import {computed, initial, property} from '../decorators';import {Color, Rect as RectType, Vector2} from '@motion-canvas/core/lib/types';import {drawImage} from '../utils';import {Rect, RectProps} from './Rect';+import {View2D} from '../scenes';export interface ImageProps extends RectProps {src?: SignalValue<string>;@@ -11,6 +16,8 @@ export interface ImageProps extends RectProps {}export class Image extends Rect {+ private static pool: Record<string, HTMLImageElement> = {};+@property()public declare readonly src: Signal<string, this>;@@ -22,43 +29,30 @@ export class Image extends Rect {@property()public declare readonly smoothing: Signal<boolean, this>;- protected readonly image: HTMLImageElement;-public constructor(props: ImageProps) {- super({- ...props,- tagName: 'img',- });- this.image = <HTMLImageElement>this.element;+ super(props);}- protected override draw(context: CanvasRenderingContext2D) {- this.drawShape(context);- if (this.clip()) {- context.clip(this.getPath());- }- const alpha = this.alpha();- if (alpha > 0) {- const rect = RectType.fromSizeCentered(this.computedSize());- context.save();- if (alpha < 1) {- context.globalAlpha *= alpha;- }- context.imageSmoothingEnabled = this.smoothing();- drawImage(context, this.image, rect);- context.restore();+ @computed()+ protected image(): HTMLImageElement {+ const src = this.src();+ if (Image.pool[src]) {+ return Image.pool[src];}- this.drawChildren(context);- }- protected override updateLayout() {- this.applySrc();- super.updateLayout();- }+ const image = View2D.document.createElement('img');+ image.src = src;+ if (!image.complete) {+ collectPromise(+ new Promise((resolve, reject) => {+ image.addEventListener('load', resolve);+ image.addEventListener('error', reject);+ }),+ );+ }+ Image.pool[src] = image;- @computed()- protected applySrc() {- this.image.src = this.src();+ return image;}@computed()@@ -74,19 +68,46 @@ export class Image extends Rect {}@computed()- protected imageDrawnCanvas() {- this.applySrc();+ protected filledImageCanvas() {const context = this.imageCanvas();- context.canvas.width = this.image.naturalWidth;- context.canvas.height = this.image.naturalHeight;+ const image = this.image();+ context.canvas.width = image.naturalWidth;+ context.canvas.height = image.naturalHeight;context.imageSmoothingEnabled = this.smoothing();- context.drawImage(this.image, 0, 0);+ context.drawImage(image, 0, 0);return context;}- public getColorAtPoint(position: Vector2): any {- const context = this.imageDrawnCanvas();+ protected override draw(context: CanvasRenderingContext2D) {+ this.drawShape(context);+ if (this.clip()) {+ context.clip(this.getPath());+ }+ const alpha = this.alpha();+ if (alpha > 0) {+ const rect = RectType.fromSizeCentered(this.computedSize());+ context.save();+ if (alpha < 1) {+ context.globalAlpha *= alpha;+ }+ context.imageSmoothingEnabled = this.smoothing();+ drawImage(context, this.image(), rect);+ context.restore();+ }+ this.drawChildren(context);+ }++ protected override applyFlex() {+ super.applyFlex();+ const image = this.image();+ this.element.style.aspectRatio = this.parseValue(+ this.ratio() ?? image.naturalWidth / image.naturalHeight,+ );+ }++ public getColorAtPoint(position: Vector2): Color {+ const context = this.filledImageCanvas();const relativePosition = position.add(this.computedSize().scale(0.5));const data = context.getImageData(relativePosition.x,@@ -103,16 +124,8 @@ export class Image extends Rect {});}- protected override collectAsyncResources(deps: Promise<any>[]) {- super.collectAsyncResources(deps);- this.applySrc();- if (!this.image.complete) {- deps.push(- new Promise((resolve, reject) => {- this.image.addEventListener('load', resolve);- this.image.addEventListener('error', reject);- }),- );- }+ protected override collectAsyncResources() {+ super.collectAsyncResources();+ this.image();}}diff --git a/packages/2d/src/components/Node.ts b/packages/2d/src/components/Node.tsindex 485af60e..7ed158ac 100644--- a/packages/2d/src/components/Node.ts+++ b/packages/2d/src/components/Node.ts@@ -21,6 +21,7 @@ import {PossibleVector2,} from '@motion-canvas/core/lib/types';import {+ consumePromises,createSignal,isReactive,Reference,@@ -865,20 +866,17 @@ export class Node implements Promisable<Node> {* before continuing the animation.*/public waitForAsyncResources() {- const deps: Promise<any>[] = [];- this.collectAsyncResources(deps);- return Promise.all(deps);+ this.collectAsyncResources();+ const promises = consumePromises();+ return Promise.all(promises.map(handle => handle.promise));}/**- * Collect all asynchronous resources used by this node and put them in the- * `resources` array.- *- * @param resources - An array to which resources should be collected.+ * Collect all asynchronous resources used by this node.*/- protected collectAsyncResources(resources: Promise<any>[]) {+ protected collectAsyncResources() {for (const child of this.children()) {- child.collectAsyncResources(resources);+ child.collectAsyncResources();}}diff --git a/packages/2d/src/components/Video.ts b/packages/2d/src/components/Video.tsnew file mode 100644index 00000000..db1dc352--- /dev/null+++ b/packages/2d/src/components/Video.ts@@ -0,0 +1,211 @@+import {Rect as RectType} from '@motion-canvas/core/lib/types';+import {drawImage} from '../utils';+import {computed, initial, property} from '../decorators';+import {+ collectPromise,+ Signal,+ SignalValue,+ useProject,+ useThread,+} from '@motion-canvas/core/lib/utils';+import {View2D} from '../scenes';+import {PlaybackState} from '@motion-canvas/core';+import {clamp} from '@motion-canvas/core/lib/tweening';+import {Rect, RectProps} from './Rect';++export interface VideoProps extends RectProps {+ src?: SignalValue<string>;+ alpha?: SignalValue<number>;+ smoothing?: SignalValue<boolean>;+ time?: SignalValue<number>;+ play?: boolean;+}++export class Video extends Rect {+ private static readonly pool: Record<string, HTMLVideoElement> = {};++ @property()+ public declare readonly src: Signal<string, this>;++ @initial(1)+ @property()+ public declare readonly alpha: Signal<number, this>;++ @initial(true)+ @property()+ public declare readonly smoothing: Signal<boolean, this>;++ @initial(0)+ @property()+ protected declare readonly time: Signal<number, this>;++ @initial(false)+ @property()+ protected declare readonly playing: Signal<boolean, this>;++ private lastTime = -1;++ public constructor(props: VideoProps) {+ super(props);+ }++ @computed()+ public completion(): number {+ return this.clampTime(this.time()) / this.video().duration;+ }++ @computed()+ protected video(): HTMLVideoElement {+ const src = this.src();+ const key = `${this.key}/${src}`;+ if (Video.pool[key]) {+ return Video.pool[key];+ }++ const video = View2D.document.createElement('video');+ video.src = src;+ if (video.readyState < 2) {+ collectPromise(+ new Promise<void>(resolve => {+ const listener = () => {+ resolve();+ video.removeEventListener('canplay', listener);+ };+ video.addEventListener('canplay', listener);+ }),+ );+ }+ Video.pool[key] = video;++ return video;+ }++ @computed()+ protected seekedVideo(): HTMLVideoElement {+ const video = this.video();+ const time = this.clampTime(this.time());++ if (!video.paused) {+ video.pause();+ }++ if (this.lastTime === time) {+ return video;+ }++ this.setCurrentTime(time);++ return video;+ }++ @computed()+ protected fastSeekedVideo(): HTMLVideoElement {+ const video = this.video();+ const time = this.clampTime(this.time());+ if (this.lastTime === time) {+ return video;+ }++ const playing = this.playing() && time < video.duration;+ if (playing) {+ if (video.paused) {+ collectPromise(video.play());+ }+ } else {+ if (!video.paused) {+ video.pause();+ }+ }++ if (Math.abs(video.currentTime - time) > 0.2) {+ this.setCurrentTime(time);+ } else if (!playing) {+ video.currentTime = time;+ }++ return video;+ }++ protected override draw(context: CanvasRenderingContext2D) {+ this.drawShape(context);+ if (this.clip()) {+ context.clip(this.getPath());+ }++ const alpha = this.alpha();+ if (alpha > 0) {+ const video =+ useProject().playbackState() === PlaybackState.Playing+ ? this.fastSeekedVideo()+ : this.seekedVideo();++ const rect = RectType.fromSizeCentered(this.computedSize());+ context.save();+ if (alpha < 1) {+ context.globalAlpha *= alpha;+ }+ context.imageSmoothingEnabled = this.smoothing();+ drawImage(context, video, rect);+ context.restore();+ }++ this.drawChildren(context);+ }++ protected override applyFlex() {+ super.applyFlex();+ const video = this.video();+ this.element.style.aspectRatio = this.parseValue(+ this.ratio() ?? video.videoWidth / video.videoHeight,+ );+ }++ protected setCurrentTime(value: number) {+ const video = this.video();+ video.currentTime = value;+ this.lastTime = value;+ if (video.seeking) {+ collectPromise(+ new Promise<void>(resolve => {+ const listener = () => {+ resolve();+ video.removeEventListener('seeked', listener);+ };+ video.addEventListener('seeked', listener);+ }),+ );+ }+ }++ public play() {+ const time = useThread().time;+ const start = time() - this.time();+ this.playing(true);+ this.time(() => this.clampTime(time() - start));+ }++ public pause() {+ this.playing(false);+ this.time.save();+ this.video().pause();+ }++ public seek(time: number) {+ const playing = this.playing();+ this.time(this.clampTime(time));+ if (playing) {+ this.play();+ } else {+ this.pause();+ }+ }++ public clampTime(time: number): number {+ return clamp(0, this.video().duration, time);+ }++ protected override collectAsyncResources() {+ super.collectAsyncResources();+ this.seekedVideo();+ }+}diff --git a/packages/2d/src/components/index.ts b/packages/2d/src/components/index.tsindex 3349daaa..ee8816b3 100644--- a/packages/2d/src/components/index.ts+++ b/packages/2d/src/components/index.ts@@ -1,4 +1,5 @@export * from './Circle';+export * from './CodeBlock';export * from './Image';export * from './Layout';export * from './Line';@@ -6,3 +7,4 @@ export * from './Node';export * from './Rect';export * from './Text';export * from './types';+export * from './Video';diff --git a/packages/2d/src/scenes/Scene2D.ts b/packages/2d/src/scenes/Scene2D.tsindex 3451f076..b03534df 100644--- a/packages/2d/src/scenes/Scene2D.ts+++ b/packages/2d/src/scenes/Scene2D.ts@@ -26,7 +26,7 @@ export class Scene2D extends GeneratorScene<View2D> implements Inspectable {return this.view;}- public render(context: CanvasRenderingContext2D): void {+ public draw(context: CanvasRenderingContext2D) {context.save();this.renderLifecycle.dispatch([SceneRenderEvent.BeforeRender, context]);context.save();diff --git a/packages/core/src/Project.ts b/packages/core/src/Project.tsindex 0cc33217..ad056aa1 100644--- a/packages/core/src/Project.ts+++ b/packages/core/src/Project.ts@@ -3,7 +3,7 @@ import {Meta, Metadata} from './Meta';import {EventDispatcher, ValueDispatcher} from './events';import {CanvasColorSpace, CanvasOutputMimeType, Vector2} from './types';import {AudioManager} from './media';-import {ifHot} from './utils';+import {createSignal, ifHot} from './utils';const EXPORT_FRAME_LIMIT = 256;const EXPORT_RETRY_DELAY = 1000;@@ -22,6 +22,13 @@ export interface ProjectConfig {background?: string | false;}+export enum PlaybackState {+ Playing,+ Rendering,+ Paused,+ Seeking,+}+export type ProjectMetadata = Metadata;export class Project {@@ -89,14 +96,30 @@ export class Project {}private updateCanvas() {- if (this.canvas) {- this.context = this.canvas.getContext('2d', {- colorSpace: this._colorSpace,- });- this.canvas.width = this.width * this._resolutionScale;- this.canvas.height = this.height * this._resolutionScale;- this.render();+ if (!this.canvas) {+ return;}++ this.buffer = this.buffer.canvas.getContext('2d', {+ colorSpace: this._colorSpace,+ });+ this.previousBuffer = this.previousBuffer.canvas.getContext('2d', {+ colorSpace: this._colorSpace,+ });+ this.context = this.canvas.getContext('2d', {+ colorSpace: this._colorSpace,+ });++ this.canvas.width =+ this.buffer.canvas.width =+ this.previousBuffer.canvas.width =+ this.width * this._resolutionScale;+ this.canvas.height =+ this.buffer.canvas.height =+ this.previousBuffer.canvas.height =+ this.height * this._resolutionScale;++ this.render();}public setCanvas(value: HTMLCanvasElement) {@@ -124,6 +147,7 @@ export class Project {public readonly name: string;public readonly audio = new AudioManager();+ public playbackState = createSignal(PlaybackState.Paused);private readonly renderLookup: Record<number, Callback> = {};private _resolutionScale = 1;private _colorSpace: CanvasColorSpace = 'srgb';@@ -135,6 +159,8 @@ export class Project {private background: string | false;private canvas: HTMLCanvasElement;private context: CanvasRenderingContext2D;+ private buffer = document.createElement('canvas').getContext('2d');+ private previousBuffer = document.createElement('canvas').getContext('2d');private exportCounter = 0;private width: number;@@ -183,31 +209,24 @@ export class Project {);}- public render() {+ public async render() {if (!this.canvas) return;- this.transformCanvas(this.context);+ this.transformCanvas(this.buffer);+ this.transformCanvas(this.previousBuffer);+ await this.previousScene?.render(this.previousBuffer);+ await this.currentScene.current?.render(this.buffer);+if (this.background) {this.context.save();this.context.fillStyle = this.background;- this.context.fillRect(- this.width / -2,- this.height / -2,- this.width,- this.height,- );+ this.context.fillRect(0, 0, this.width, this.height);this.context.restore();} else {- this.context.clearRect(- this.width / -2,- this.height / -2,- this.width,- this.height,- );+ this.context.clearRect(0, 0, this.width, this.height);}-- this.previousScene?.render(this.context, this.canvas);- this.currentScene.current?.render(this.context, this.canvas);+ this.context.drawImage(this.previousBuffer.canvas, 0, 0);+ this.context.drawImage(this.buffer.canvas, 0, 0);}private reloadAll() {diff --git a/packages/core/src/flow/scheduling.ts b/packages/core/src/flow/scheduling.tsindex 9dfbc018..0298af51 100644--- a/packages/core/src/flow/scheduling.ts+++ b/packages/core/src/flow/scheduling.ts@@ -58,13 +58,13 @@ export function* waitFor(const thread = useThread();const step = project.framesToSeconds(1);- const targetTime = thread.time + seconds;+ const targetTime = thread.time() + seconds;// subtracting the step is not necessary, but it keeps the thread time ahead// of the project time.while (targetTime - step > project.time) {yield;}- thread.time = targetTime;+ thread.time(targetTime);if (after) {yield* after;diff --git a/packages/core/src/player/Player.ts b/packages/core/src/player/Player.tsindex 7c43c8f9..08536f61 100644--- a/packages/core/src/player/Player.ts+++ b/packages/core/src/player/Player.ts@@ -1,4 +1,5 @@import type {Project} from '../Project';+import {PlaybackState} from '../Project';import {EventDispatcher, ValueDispatcher} from '../events';import type {CanvasColorSpace, CanvasOutputMimeType} from '../types';@@ -235,6 +236,11 @@ export class Player {commands.seek = state.startFrame;}+ const previousState = this.project.playbackState();+ this.project.playbackState(+ state.paused ? PlaybackState.Paused : PlaybackState.Playing,+ );+// Recalculateif (commands.recalculate) {const startTime = performance.now();@@ -242,7 +248,7 @@ export class Player {const duration = this.project.frame;const frame = commands.seek < 0 ? this.frame.current : commands.seek;const finished = await this.project.seek(frame);- this.project.render();+ await this.project.render();this.updateState({duration,finished,@@ -272,8 +278,9 @@ export class Player {// Renderingif (state.render) {+ this.project.playbackState(PlaybackState.Rendering);state.finished = await this.project.next();- this.project.render();+ await this.project.render();try {await this.project.export();} catch (e) {@@ -310,6 +317,9 @@ export class Player {this.project.audio.isInRange(this.project.time) &&this.project.audio.getTime() < this.project.time)) {+ if (state.paused && previousState !== PlaybackState.Paused) {+ await this.project.render();+ }this.request();return;}@@ -336,7 +346,7 @@ export class Player {}// Draw the project- this.project.render();+ await this.project.render();// handle finishingif (state.finished) {diff --git a/packages/core/src/scenes/GeneratorScene.ts b/packages/core/src/scenes/GeneratorScene.tsindex 400f8024..43ad0f42 100644--- a/packages/core/src/scenes/GeneratorScene.ts+++ b/packages/core/src/scenes/GeneratorScene.ts@@ -8,13 +8,13 @@ import {import {Meta} from '../Meta';import {TimeEvents} from './TimeEvents';import {EventDispatcher, ValueDispatcher} from '../events';-import {Project} from '../Project';+import {PlaybackState, Project} from '../Project';import {decorate, threadable} from '../decorators';-import {endScene, setProject, startScene} from '../utils';+import {consumePromises, endScene, setProject, startScene} from '../utils';import {CachedSceneData, Scene, SceneMetadata, SceneRenderEvent} from './Scene';import {LifecycleEvents} from './LifecycleEvents';import {Threadable} from './Threadable';-import {Vector2} from '../types';+import {Rect, Vector2} from '../types';import {SceneState} from './SceneState';export interface ThreadGeneratorFactory<T> {@@ -31,6 +31,7 @@ export abstract class GeneratorScene<T>{public readonly timeEvents: TimeEvents;public project: Project;+ public playbackInfo: PlaybackState;public get firstFrame() {return this.cache.current.firstFrame;@@ -112,10 +113,27 @@ export abstract class GeneratorScene<T>// do nothing}- public abstract render(- context: CanvasRenderingContext2D,- canvas: HTMLCanvasElement,- ): void;+ public async render(context: CanvasRenderingContext2D): Promise<void> {+ let promises = consumePromises();+ let iterations = 0;+ do {+ iterations++;+ await Promise.all(promises.map(handle => handle.promise));+ context.save();+ const rect = Rect.fromSizeCentered(this.getSize());+ context.clearRect(rect.x, rect.y, rect.width, rect.height);+ this.draw(context);+ context.restore();++ promises = consumePromises();+ } while (promises.length > 0 && iterations < 10);++ if (iterations > 1) {+ console.info('render iterations:', iterations);+ }+ }++ protected abstract draw(context: CanvasRenderingContext2D): void;public reload(runnerFactory?: ThreadGeneratorFactory<T>) {if (runnerFactory) {@@ -180,6 +198,13 @@ export abstract class GeneratorScene<T>}endScene(this);+ const promises = consumePromises();+ if (promises.length > 0) {+ await Promise.all(promises.map(handle => handle.promise));+ // TODO Display a more helpful message+ console.error(promises);+ }+if (result.done) {this.state = SceneState.Finished;}diff --git a/packages/core/src/scenes/Scene.ts b/packages/core/src/scenes/Scene.tsindex faddd035..84091ad0 100644--- a/packages/core/src/scenes/Scene.ts+++ b/packages/core/src/scenes/Scene.ts@@ -161,9 +161,8 @@ export interface Scene<T = unknown> {* Render the scene onto a canvas.** @param context - The context to used when rendering.- * @param canvas - The canvas onto which the scene should be rendered.*/- render(context: CanvasRenderingContext2D, canvas: HTMLCanvasElement): void;+ render(context: CanvasRenderingContext2D): Promise<void>;/*** Reload the scene.diff --git a/packages/core/src/threading/Thread.ts b/packages/core/src/threading/Thread.tsindex 7e7db92c..74e400be 100644--- a/packages/core/src/threading/Thread.ts+++ b/packages/core/src/threading/Thread.ts@@ -1,6 +1,6 @@import {GeneratorHelper} from '../helpers';import {ThreadGenerator} from './ThreadGenerator';-import {endThread, startThread, useProject} from '../utils';+import {createSignal, endThread, startThread, useProject} from '../utils';/*** A class representing an individual thread.@@ -25,7 +25,7 @@ export class Thread {* Used by {@link waitFor} and other time-based functions to properly* support durations shorter than one frame.*/- public time = 0;+ public readonly time = createSignal(0);/*** Check if this thread or any of its ancestors has been canceled.@@ -46,7 +46,7 @@ export class Thread {) {const project = useProject();this.frameDuration = project.framesToSeconds(1);- this.time = project.time;+ this.time(project.time);}/**@@ -64,7 +64,7 @@ export class Thread {* Prepare the thread for the next update cycle.*/public update() {- this.time += useProject().framesToSeconds(1);+ this.time(this.time() + useProject().framesToSeconds(1));this.children = this.children.filter(child => !child.canceled);}@@ -72,7 +72,7 @@ export class Thread {child.cancel();child.parent = this;child.isCanceled = false;- child.time = this.time;+ child.time(this.time());this.children.push(child);if (!Object.getPrototypeOf(child.runner).threadable) {diff --git a/packages/core/src/threading/ThreadGenerator.ts b/packages/core/src/threading/ThreadGenerator.tsindex ffd9ed44..4fda4fc2 100644--- a/packages/core/src/threading/ThreadGenerator.ts+++ b/packages/core/src/threading/ThreadGenerator.ts@@ -48,5 +48,7 @@ export type ThreadGenerator = Generator<* @param value - A possible thread {@link ThreadGenerator}.*/export function isThreadGenerator(value: unknown): value is ThreadGenerator {- return typeof value === 'object' && Symbol.iterator in value;+ return (+ typeof value === 'object' && Symbol.iterator in value && 'next' in value+ );}diff --git a/packages/core/src/threading/cancel.ts b/packages/core/src/threading/cancel.tsindex 81a3dc68..e36c2f71 100644--- a/packages/core/src/threading/cancel.ts+++ b/packages/core/src/threading/cancel.ts@@ -21,7 +21,7 @@ export function cancel(...tasks: ThreadGenerator[]) {const child = thread.children.find(thread => thread.runner === task);if (child && !child.canceled) {child.cancel();- child.time = thread.time;+ child.time(thread.time());}}}diff --git a/packages/core/src/threading/join.ts b/packages/core/src/threading/join.tsindex f6eb322e..5acf85fd 100644--- a/packages/core/src/threading/join.ts+++ b/packages/core/src/threading/join.ts@@ -55,20 +55,20 @@ export function* join(.map(task => parent.children.find(thread => thread.runner === task)).filter(thread => thread);- const startTime = parent.time;+ const startTime = parent.time();let childTime;if (all) {while (threads.find(thread => !thread.canceled)) {yield;}- childTime = Math.max(...threads.map(thread => thread.time));+ childTime = Math.max(...threads.map(thread => thread.time()));} else {while (!threads.find(thread => thread.canceled)) {yield;}const canceled = threads.filter(thread => thread.canceled);- childTime = Math.min(...canceled.map(thread => thread.time));+ childTime = Math.min(...canceled.map(thread => thread.time()));}- parent.time = Math.max(startTime, childTime);+ parent.time(Math.max(startTime, childTime));}diff --git a/packages/core/src/tweening/tween.ts b/packages/core/src/tweening/tween.tsindex 02b6b489..bd60acac 100644--- a/packages/core/src/tweening/tween.ts+++ b/packages/core/src/tweening/tween.ts@@ -11,8 +11,8 @@ export function* tween(const project = useProject();const thread = useThread();- const startTime = thread.time;- const endTime = thread.time + seconds;+ const startTime = thread.time();+ const endTime = thread.time() + seconds;onProgress(0, 0);while (endTime > project.time) {@@ -23,7 +23,7 @@ export function* tween(}yield;}- thread.time = endTime;+ thread.time(endTime);onProgress(1, seconds);onEnd?.(1, seconds);diff --git a/packages/core/src/utils/createComputedAsync.test.ts b/packages/core/src/utils/createComputedAsync.test.tsnew file mode 100644index 00000000..d5887f03--- /dev/null+++ b/packages/core/src/utils/createComputedAsync.test.ts@@ -0,0 +1,19 @@+import {createSignal} from './createSignal';+import {createComputedAsync} from './createComputedAsync';++function sleep(duration = 0) {+ return new Promise(resolve => setTimeout(resolve, duration));+}++describe('createComputedAsync()', () => {+ test('Value is updated when the promise resolves', async () => {+ const computed = createComputedAsync(() => sleep().then(() => true), false);+ const signal = createSignal(() => computed());++ expect(signal()).toBe(false);++ await sleep(1);++ expect(signal()).toBe(true);+ });+});diff --git a/packages/core/src/utils/createComputedAsync.ts b/packages/core/src/utils/createComputedAsync.tsnew file mode 100644index 00000000..9189e4bc--- /dev/null+++ b/packages/core/src/utils/createComputedAsync.ts@@ -0,0 +1,10 @@+import {Computed, createComputed} from './createComputed';+import {collectPromise} from './createSignal';++export function createComputedAsync<T>(+ factory: () => Promise<T>,+ initial: T = null,+): Computed<T> {+ const handle = createComputed(() => collectPromise(factory(), initial));+ return createComputed(() => handle().value);+}diff --git a/packages/core/src/utils/createSignal.ts b/packages/core/src/utils/createSignal.tsindex 81a4c832..06235ebb 100644--- a/packages/core/src/utils/createSignal.ts+++ b/packages/core/src/utils/createSignal.ts@@ -93,6 +93,7 @@ export interface Signal<TValue, TReturn = void>SignalUtils<TValue, TReturn> {}const collectionStack: DependencyContext[] = [];+let promises: PromiseHandle<any>[] = [];export function startCollecting(context: DependencyContext) {collectionStack.push(context);@@ -112,6 +113,38 @@ export function collect(subscribable: Subscribable<void>) {}}+export interface PromiseHandle<T> {+ promise: Promise<T>;+ value: T;+ stack: string;+}++export function collectPromise<T>(+ promise: Promise<T>,+ initialValue: T = null,+): PromiseHandle<T> {+ const handle: PromiseHandle<T> = {+ promise,+ value: initialValue,+ stack: new Error().stack,+ };+ if (collectionStack.length > 1) {+ const [, handler] = collectionStack.at(-2);+ promise.then(value => {+ handle.value = value;+ handler();+ });+ }+ promises.push(handle);+ return handle;+}++export function consumePromises(): PromiseHandle<any>[] {+ const result = promises;+ promises = [];+ return result;+}+export function isReactive<T>(value: SignalValue<T>): value is () => T {return typeof value === 'function';}diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.tsindex 2032e66a..2b42321a 100644--- a/packages/core/src/utils/index.ts+++ b/packages/core/src/utils/index.ts@@ -1,4 +1,5 @@export * from './createComputed';+export * from './createComputedAsync';export * from './createSignal';export * from './range';export * from './useAnimator';diff --git a/packages/core/src/utils/useTime.ts b/packages/core/src/utils/useTime.tsindex bf2a769b..d78daa46 100644--- a/packages/core/src/utils/useTime.ts+++ b/packages/core/src/utils/useTime.ts@@ -18,5 +18,5 @@ import {useThread} from './useThread';* ```*/export function useTime() {- return useThread().time;+ return useThread().time();}diff --git a/packages/ui/src/hooks/usePlayerState.ts b/packages/ui/src/hooks/usePlayerState.tsindex ec8624ef..d3ec865b 100644--- a/packages/ui/src/hooks/usePlayerState.ts+++ b/packages/ui/src/hooks/usePlayerState.ts@@ -1,8 +1,6 @@import {usePlayer} from '../contexts';import {useSubscribableValue} from './useSubscribable';-// TODO Save and restore the player state.-export function usePlayerState() {const player = usePlayer();return useSubscribableValue(player.onStateChanged);