Skip to content

Visualize Your Ideas With Code

feat: remove strongly-typed-events (#48)

Jacob41947b5ab6a2
diff --git a/package-lock.json b/package-lock.json
index 0d4f117e..f3dff28f 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@motion-canvas/core",
- "version": "2.2.0",
+ "version": "4.1.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "@motion-canvas/core",
- "version": "2.2.0",
+ "version": "4.1.0",
"license": "MIT",
"dependencies": {
"@types/prismjs": "^1.26.0",
@@ -20,7 +20,6 @@
"mp4box": "^0.5.2",
"prismjs": "^1.28.0",
"source-map": "^0.7.4",
- "strongly-typed-events": "^3.0.2",
"three": "^0.141.0",
"ts-loader": "^9.3.0",
"typescript": "^4.7.3",
@@ -9637,80 +9636,6 @@
"node": ">= 0.8"
}
},
- "node_modules/ste-core": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/ste-core/-/ste-core-3.0.2.tgz",
- "integrity": "sha512-jX6MwOP78lt5AJsDouGrXEAd4ivYF/xLgzUDa5bpVfScIVhs2K5yG+ZxGJzpyEZFFseYJYhyLvsLDCLETW4W/w==",
- "engines": {
- "node": ">=4.2.4"
- }
- },
- "node_modules/ste-events": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/ste-events/-/ste-events-3.0.2.tgz",
- "integrity": "sha512-lfNXJJLhDsZUyOLYkdldlFGzgWyI+FMza1x9VNzKKa6MV86yvUig6u6e8qOl0QMMXVreWqCf2jeFC3BczZwtcg==",
- "dependencies": {
- "ste-core": "^3.0.2"
- },
- "engines": {
- "node": ">=4.2.4"
- }
- },
- "node_modules/ste-promise-events": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/ste-promise-events/-/ste-promise-events-3.0.2.tgz",
- "integrity": "sha512-JUvHOYGzZgwyy6kg/FJH7cQKp179BgOqeKhlxS31gAjrzKpNLGmgMRnjW+/NPyOmuEBDpaA6uV3lbQ5rc3BDVg==",
- "dependencies": {
- "ste-core": "^3.0.2"
- },
- "engines": {
- "node": ">=4.2.4"
- }
- },
- "node_modules/ste-promise-signals": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/ste-promise-signals/-/ste-promise-signals-3.0.2.tgz",
- "integrity": "sha512-YbPJJFVxXEwvKXTguItJFhukz6kT3n0BsY/wzw9B4mKo6hQlxCMtYdR72r1WwthnMvk0NDI1gP4JV+f5rOHEvA==",
- "dependencies": {
- "ste-core": "^3.0.2"
- },
- "engines": {
- "node": ">=4.2.4"
- }
- },
- "node_modules/ste-promise-simple-events": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/ste-promise-simple-events/-/ste-promise-simple-events-3.0.2.tgz",
- "integrity": "sha512-DbIwA1Gz0sYk6ruUAew4M7i1p1U6ULAITy7a25/bAxxA7l2nMlk3Cd54CSNqGVdBHnrR8Nv4rC9e99LXs+BiFA==",
- "dependencies": {
- "ste-core": "^3.0.2"
- },
- "engines": {
- "node": ">=4.2.4"
- }
- },
- "node_modules/ste-signals": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/ste-signals/-/ste-signals-3.0.2.tgz",
- "integrity": "sha512-bWDtxCBs7cq3bModkFGyTRzAGm9QSAlrGXV7xxKmgyc2VMkF/E79Y4k3CcMEVT7Odj1ieL8Fg8m21gL43sOLSg==",
- "dependencies": {
- "ste-core": "^3.0.2"
- },
- "engines": {
- "node": ">=4.2.4"
- }
- },
- "node_modules/ste-simple-events": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/ste-simple-events/-/ste-simple-events-3.0.2.tgz",
- "integrity": "sha512-NvHH+JX6SjpMtgmcAwqMAsJ6nyGdGp1/oaGTdK/RVQGIAL0bLKRnHAyiH+ygMJ3P2SPPUPApIjqoq1VGK2uH8A==",
- "dependencies": {
- "ste-core": "^3.0.2"
- },
- "engines": {
- "node": ">=4.2.4"
- }
- },
"node_modules/stream-combiner2": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/stream-combiner2/-/stream-combiner2-1.1.1.tgz",
@@ -9824,23 +9749,6 @@
"node": ">=0.10.0"
}
},
- "node_modules/strongly-typed-events": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/strongly-typed-events/-/strongly-typed-events-3.0.2.tgz",
- "integrity": "sha512-9KKqQwqjXc6zbqi1iIFoAX+9jPoBIFcel43HCBWYskgEpg3g8R1J3hTzUH8GYfu1EOYwEIjL6Yw0KnceSdDjLw==",
- "dependencies": {
- "ste-core": "^3.0.2",
- "ste-events": "^3.0.2",
- "ste-promise-events": "^3.0.2",
- "ste-promise-signals": "^3.0.2",
- "ste-promise-simple-events": "^3.0.2",
- "ste-signals": "^3.0.2",
- "ste-simple-events": "^3.0.2"
- },
- "engines": {
- "node": ">=4.2.4"
- }
- },
"node_modules/supports-color": {
"version": "5.5.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
@@ -18033,59 +17941,6 @@
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
"integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ=="
},
- "ste-core": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/ste-core/-/ste-core-3.0.2.tgz",
- "integrity": "sha512-jX6MwOP78lt5AJsDouGrXEAd4ivYF/xLgzUDa5bpVfScIVhs2K5yG+ZxGJzpyEZFFseYJYhyLvsLDCLETW4W/w=="
- },
- "ste-events": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/ste-events/-/ste-events-3.0.2.tgz",
- "integrity": "sha512-lfNXJJLhDsZUyOLYkdldlFGzgWyI+FMza1x9VNzKKa6MV86yvUig6u6e8qOl0QMMXVreWqCf2jeFC3BczZwtcg==",
- "requires": {
- "ste-core": "^3.0.2"
- }
- },
- "ste-promise-events": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/ste-promise-events/-/ste-promise-events-3.0.2.tgz",
- "integrity": "sha512-JUvHOYGzZgwyy6kg/FJH7cQKp179BgOqeKhlxS31gAjrzKpNLGmgMRnjW+/NPyOmuEBDpaA6uV3lbQ5rc3BDVg==",
- "requires": {
- "ste-core": "^3.0.2"
- }
- },
- "ste-promise-signals": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/ste-promise-signals/-/ste-promise-signals-3.0.2.tgz",
- "integrity": "sha512-YbPJJFVxXEwvKXTguItJFhukz6kT3n0BsY/wzw9B4mKo6hQlxCMtYdR72r1WwthnMvk0NDI1gP4JV+f5rOHEvA==",
- "requires": {
- "ste-core": "^3.0.2"
- }
- },
- "ste-promise-simple-events": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/ste-promise-simple-events/-/ste-promise-simple-events-3.0.2.tgz",
- "integrity": "sha512-DbIwA1Gz0sYk6ruUAew4M7i1p1U6ULAITy7a25/bAxxA7l2nMlk3Cd54CSNqGVdBHnrR8Nv4rC9e99LXs+BiFA==",
- "requires": {
- "ste-core": "^3.0.2"
- }
- },
- "ste-signals": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/ste-signals/-/ste-signals-3.0.2.tgz",
- "integrity": "sha512-bWDtxCBs7cq3bModkFGyTRzAGm9QSAlrGXV7xxKmgyc2VMkF/E79Y4k3CcMEVT7Odj1ieL8Fg8m21gL43sOLSg==",
- "requires": {
- "ste-core": "^3.0.2"
- }
- },
- "ste-simple-events": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/ste-simple-events/-/ste-simple-events-3.0.2.tgz",
- "integrity": "sha512-NvHH+JX6SjpMtgmcAwqMAsJ6nyGdGp1/oaGTdK/RVQGIAL0bLKRnHAyiH+ygMJ3P2SPPUPApIjqoq1VGK2uH8A==",
- "requires": {
- "ste-core": "^3.0.2"
- }
- },
"stream-combiner2": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/stream-combiner2/-/stream-combiner2-1.1.1.tgz",
@@ -18180,20 +18035,6 @@
"integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=",
"dev": true
},
- "strongly-typed-events": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/strongly-typed-events/-/strongly-typed-events-3.0.2.tgz",
- "integrity": "sha512-9KKqQwqjXc6zbqi1iIFoAX+9jPoBIFcel43HCBWYskgEpg3g8R1J3hTzUH8GYfu1EOYwEIjL6Yw0KnceSdDjLw==",
- "requires": {
- "ste-core": "^3.0.2",
- "ste-events": "^3.0.2",
- "ste-promise-events": "^3.0.2",
- "ste-promise-signals": "^3.0.2",
- "ste-promise-simple-events": "^3.0.2",
- "ste-signals": "^3.0.2",
- "ste-simple-events": "^3.0.2"
- }
- },
"supports-color": {
"version": "5.5.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
diff --git a/package.json b/package.json
index 8ccbdf7a..de9be65f 100644
--- a/package.json
+++ b/package.json
@@ -44,7 +44,6 @@
"mp4box": "^0.5.2",
"prismjs": "^1.28.0",
"source-map": "^0.7.4",
- "strongly-typed-events": "^3.0.2",
"three": "^0.141.0",
"ts-loader": "^9.3.0",
"typescript": "^4.7.3",
diff --git a/src/Meta.ts b/src/Meta.ts
index e033e45c..c2294976 100644
--- a/src/Meta.ts
+++ b/src/Meta.ts
@@ -1,4 +1,4 @@
-import {SimpleEventDispatcher} from 'strongly-typed-events';
+import {ValueDispatcher} from './events';
/**
* Represents the contents of a meta file.
@@ -18,22 +18,20 @@ export class Meta<T extends Metadata = Metadata> {
*
* @event T
*/
- public get Changed() {
- return this.changed.asEvent();
+ public get onDataChanged() {
+ return this.data.subscribable;
}
+ private readonly data = new ValueDispatcher(<T>{version: META_VERSION});
- private data: T;
private rawData: string;
private source: string;
- private changed = new SimpleEventDispatcher<T>();
private constructor() {
- this.data = <T>{version: META_VERSION};
- this.rawData = JSON.stringify(this.data, undefined, 2);
+ this.rawData = JSON.stringify(this.data.current, undefined, 2);
}
- public getData(): T {
- return this.data;
+ public getData() {
+ return this.data.current;
}
/**
@@ -48,12 +46,11 @@ export class Meta<T extends Metadata = Metadata> {
}
public async setData(data: Partial<T>) {
- this.data = {
- ...this.data,
+ this.data.current = {
+ ...this.data.current,
...data,
};
- this.rawData = JSON.stringify(this.data, undefined, 2);
- this.changed.dispatch(this.data);
+ this.rawData = JSON.stringify(this.data.current, undefined, 2);
const response = await fetch(`/meta/${this.source}`, {
method: 'POST',
body: this.rawData,
@@ -105,9 +102,8 @@ export class Meta<T extends Metadata = Metadata> {
try {
const data: Metadata = JSON.parse(rawData);
data.version ??= META_VERSION;
- meta.data = data;
+ meta.data.current = data;
meta.rawData = rawData;
- meta.changed.dispatch(data);
} catch (e) {
console.error(`Error when parsing ${decodeURIComponent(source)}:`);
console.error(e);
diff --git a/src/Project.ts b/src/Project.ts
index d66def5d..46057e93 100644
--- a/src/Project.ts
+++ b/src/Project.ts
@@ -7,9 +7,9 @@ import {Vector2d} from 'konva/lib/types';
import {Konva} from 'konva/lib/Global';
import {Thread, ThreadsCallback} from './threading';
import {Scene, SceneRunner} from './Scene';
-import {SimpleEventDispatcher} from 'strongly-typed-events';
import {KonvaNode} from './decorators';
import {Meta, Metadata} from './Meta';
+import {ValueDispatcher} from './events';
Konva.autoDrawEnabled = false;
@@ -26,9 +26,10 @@ export type ProjectMetadata = Metadata;
@KonvaNode()
export class Project extends Stage {
- public get ScenesChanged() {
- return this.scenesChanged.asEvent();
+ public get onScenesChanged() {
+ return this.scenes.subscribable;
}
+ private readonly scenes = new ValueDispatcher<Scene[]>([]);
public readonly version = CORE_VERSION;
public readonly meta: Meta<ProjectMetadata>;
@@ -42,10 +43,6 @@ export class Project extends Stage {
return this.framesToSeconds(this.frame);
}
- public get scenes(): Scene[] {
- return Object.values(this.sceneLookup);
- }
-
public get thread(): Thread {
return this.currentThread;
}
@@ -64,7 +61,6 @@ export class Project extends Stage {
}
private framesPerSeconds = 30;
- private readonly scenesChanged = new SimpleEventDispatcher<Scene[]>();
private readonly sceneLookup: Record<string, Scene> = {};
private previousScene: Scene = null;
private currentScene: Scene = null;
@@ -176,7 +172,8 @@ export class Project extends Stage {
this.frame = 0;
let offset = 0;
- for (const scene of this.scenes) {
+ const scenes = Object.values(this.sceneLookup);
+ for (const scene of scenes) {
if (scene.isMarkedAsCached()) {
scene.firstFrame += offset;
this.frame = scene.lastFrame;
@@ -201,7 +198,7 @@ export class Project extends Stage {
}
this.currentScene = initialScene;
- this.scenesChanged.dispatch(this.scenes);
+ this.scenes.current = scenes;
}
public async seek(frame: number, speed = 1): Promise<boolean> {
diff --git a/src/TimeEvents.ts b/src/TimeEvents.ts
index e328c282..1c193d04 100644
--- a/src/TimeEvents.ts
+++ b/src/TimeEvents.ts
@@ -1,5 +1,5 @@
import type {Scene} from './Scene';
-import {SimpleEventDispatcher} from 'strongly-typed-events';
+import {ValueDispatcher} from './events';
/**
* Represents a time event at runtime.
@@ -45,11 +45,11 @@ export class TimeEvents {
*
* @event TimeEvent[]
*/
- public get Changed() {
- return this.changed.asEvent();
+ public get onChanged() {
+ return this.events.subscribable;
}
+ private readonly events = new ValueDispatcher<TimeEvent[]>([]);
- private readonly changed = new SimpleEventDispatcher<TimeEvent[]>();
private registeredEvents: Record<string, TimeEvent> = {};
private lookup: Record<string, TimeEvent> = {};
private previousReference: SavedTimeEvent[];
@@ -68,7 +68,7 @@ export class TimeEvents {
this.load(scene.meta.getData().timeEvents ?? []);
}
- scene.meta.Changed.subscribe(event => {
+ scene.meta.onDataChanged.subscribe(event => {
// Ignore the event if `timeEvents` hasn't changed.
// This may happen when another part of metadata has changed triggering
// this event.
@@ -79,11 +79,7 @@ export class TimeEvents {
this.load(event.timeEvents ?? []);
scene.reload();
window.player.reload();
- });
- }
-
- public toArray(): TimeEvent[] {
- return Object.values(this.registeredEvents);
+ }, false);
}
public get(name: string) {
@@ -110,7 +106,7 @@ export class TimeEvents {
offset,
};
this.registeredEvents[name] = this.lookup[name];
- this.changed.dispatch(this.toArray());
+ this.events.current = Object.values(this.registeredEvents);
this.scene.reload();
}
@@ -179,7 +175,7 @@ export class TimeEvents {
*/
public onCache() {
this.preserveTiming = true;
- this.changed.dispatch(this.toArray());
+ this.events.current = Object.values(this.registeredEvents);
if (this.ignoreSave) {
this.ignoreSave = false;
diff --git a/src/events/AsyncEventDispatcher.ts b/src/events/AsyncEventDispatcher.ts
new file mode 100644
index 00000000..0e7412ff
--- /dev/null
+++ b/src/events/AsyncEventDispatcher.ts
@@ -0,0 +1,49 @@
+import {EventDispatcherBase, Subscribable} from './EventDispatcherBase';
+
+export interface AsyncEventHandler<T> {
+ (value: T): Promise<void>;
+}
+
+/**
+ * Dispatches an asynchronous {@link SubscribableEvent}.
+ *
+ * The {@link dispatch} method returns a promise that resolves when all the
+ * handlers resolve.
+ *
+ * Example:
+ * ```ts
+ * class Example {
+ * // expose the event to external classes
+ * public get onValueChanged {
+ * return this.value.subscribable;
+ * }
+ * // create a private dispatcher
+ * private value = new AsyncEventDispatcher<number>();
+ *
+ * private async dispatchExample() {
+ * // dispatching returns a Promise.
+ * await this.value.dispatch(0);
+ * }
+ * }
+ * ```
+ *
+ * @template T Type of the argument passed to subscribers.
+ */
+export class AsyncEventDispatcher<T> extends EventDispatcherBase<
+ T,
+ AsyncEventHandler<T>
+> {
+ public async dispatch(value: T): Promise<void> {
+ await Promise.all(this.notifySubscribers(value));
+ }
+}
+
+/**
+ * Provides safe access to the public interface of {@link AsyncEventDispatcher}.
+ *
+ * External classes can use it to subscribe to an event without being able to
+ * dispatch it.
+ *
+ * @template T Type of the argument passed to subscribers.
+ */
+export type SubscribableAsyncEvent<T> = Subscribable<T, AsyncEventHandler<T>>;
diff --git a/src/events/EventDispatcher.ts b/src/events/EventDispatcher.ts
new file mode 100644
index 00000000..978d05a5
--- /dev/null
+++ b/src/events/EventDispatcher.ts
@@ -0,0 +1,39 @@
+import {EventDispatcherBase, Subscribable} from './EventDispatcherBase';
+
+/**
+ * Dispatches a {@link SubscribableEvent}.
+ *
+ * Example:
+ * ```ts
+ * class Example {
+ * // expose the event to external classes
+ * public get onValueChanged {
+ * return this.value.subscribable;
+ * }
+ * // create a private dispatcher
+ * private value = new EventDispatcher<number>();
+ *
+ * private dispatchExample() {
+ * // dispatching will notify all subscribers.
+ * this.value.dispatch(0);
+ * }
+ * }
+ * ```
+ *
+ * @template T Type of the value argument to subscribers.
+ */
+export class EventDispatcher<T> extends EventDispatcherBase<T> {
+ public dispatch(value: T) {
+ this.notifySubscribers(value);
+ }
+}
+
+/**
+ * Provides safe access to the public interface of {@link EventDispatcher}.
+ *
+ * External classes can use it to subscribe to an event without being able to
+ * dispatch it.
+ *
+ * @template T Type of the argument passed to subscribers.
+ */
+export type SubscribableEvent<T> = Subscribable<T>;
diff --git a/src/events/EventDispatcherBase.ts b/src/events/EventDispatcherBase.ts
new file mode 100644
index 00000000..a027c02b
--- /dev/null
+++ b/src/events/EventDispatcherBase.ts
@@ -0,0 +1,76 @@
+export interface EventHandler<T> {
+ (value: T): any;
+}
+
+/**
+ * A base for dispatching {@link Subscribable}s.
+ *
+ * @template TValue Type of the argument passed to subscribers.
+ * @template THandler Type of the callback function.
+ */
+export abstract class EventDispatcherBase<
+ TValue,
+ THandler extends EventHandler<TValue> = EventHandler<TValue>,
+> {
+ public readonly subscribable: Subscribable<TValue, THandler> =
+ new Subscribable(this);
+
+ private subscribers = new Set<THandler>();
+
+ /**
+ * @inheritDoc SubscribableEvent.subscribe
+ */
+ public subscribe(handler: THandler) {
+ this.subscribers.add(handler);
+ return () => this.unsubscribe(handler);
+ }
+
+ /**
+ * @inheritDoc SubscribableEvent.unsubscribe
+ */
+ public unsubscribe(handler: THandler) {
+ this.subscribers.delete(handler);
+ }
+
+ protected notifySubscribers(value: TValue): ReturnType<THandler>[] {
+ return [...this.subscribers].map(handler => handler(value));
+ }
+}
+
+/**
+ * Provides safe access to the public interface of {@link EventDispatcherBase}.
+ *
+ * External classes can use it to subscribe to an event without being able to
+ * dispatch it.
+ *
+ * @template TValue Type of the argument passed to subscribers.
+ * @template THandler Type of the callback function.
+ */
+export class Subscribable<
+ TValue,
+ THandler extends EventHandler<TValue> = EventHandler<TValue>,
+> {
+ public constructor(
+ protected dispatcher: EventDispatcherBase<TValue, THandler>,
+ ) {}
+
+ /**
+ * Subscribe to the event.
+ *
+ * @param handler
+ *
+ * @return Callback function that cancels the subscription.
+ */
+ public subscribe(handler: THandler) {
+ return this.dispatcher.subscribe(handler);
+ }
+
+ /**
+ * Unsubscribe from the event.
+ *
+ * @param handler
+ */
+ public unsubscribe(handler: THandler) {
+ this.dispatcher.unsubscribe(handler);
+ }
+}
diff --git a/src/events/ValueDispatcher.ts b/src/events/ValueDispatcher.ts
new file mode 100644
index 00000000..755a56f2
--- /dev/null
+++ b/src/events/ValueDispatcher.ts
@@ -0,0 +1,113 @@
+import {
+ Subscribable,
+ EventDispatcherBase,
+ EventHandler,
+} from './EventDispatcherBase';
+
+/**
+ * Dispatches a {@link SubscribableValueEvent}
+ *
+ * Changing the value stored by a value dispatcher will immediately notify all
+ * its subscribers.
+ *
+ * Example:
+ * ```ts
+ * class Example {
+ * // expose the event to external classes
+ * public get onValueChanged {
+ * return this.value.subscribable;
+ * }
+ * // create a private dispatcher
+ * private value = new ValueDispatcher(0);
+ *
+ * private changingValueExample() {
+ * // changing the value will notify all subscribers.
+ * this.value.current = 7;
+ * }
+ * }
+ * ```
+ *
+ * @template T Type of the value passed to subscribers.
+ */
+export class ValueDispatcher<T> extends EventDispatcherBase<T> {
+ public readonly subscribable: SubscribableValueEvent<T> =
+ new SubscribableValueEvent(this);
+
+ /**
+ * Set the current value of this dispatcher.
+ *
+ * Setting the value will immediately notify all subscribers.
+ *
+ * @param value
+ */
+ public set current(value: T) {
+ this.value = value;
+ this.notifySubscribers(value);
+ }
+
+ /**
+ * @inheritDoc SubscribableValueEvent.current
+ */
+ public get current() {
+ return this.value;
+ }
+
+ /**
+ * @param value Initial value.
+ */
+ public constructor(private value: T) {
+ super();
+ }
+
+ /**
+ * @inheritDoc SubscribableValueEvent.subscribe
+ */
+ public subscribe(handler: EventHandler<T>, dispatchImmediately = true) {
+ const unsubscribe = super.subscribe(handler);
+ if (dispatchImmediately) {
+ handler(this.value);
+ }
+ return unsubscribe;
+ }
+}
+
+/**
+ * Provides safe access to the public interface of {@link ValueDispatcher}.
+ *
+ * External classes can use it to subscribe to an event without being able to
+ * dispatch it.
+ *
+ * @template T Type of the value passed to subscribers.
+ */
+export class SubscribableValueEvent<T> extends Subscribable<
+ T,
+ EventHandler<T>
+> {
+ /**
+ * Get the most recent value of this dispatcher.
+ */
+ public get current() {
+ return (<ValueDispatcher<T>>this.dispatcher).current;
+ }
+
+ /**
+ * Subscribe to the event.
+ *
+ * Subscribing will immediately invoke the handler with the most recent value.
+ *
+ * @param handler
+ * @param dispatchImmediately Whether the handler should be immediately
+ * invoked with the most recent value.
+ *
+ * @return Callback function that cancels the subscription.
+ */
+ public subscribe(
+ handler: EventHandler<T>,
+ dispatchImmediately = true,
+ ): () => void {
+ return (<ValueDispatcher<T>>this.dispatcher).subscribe(
+ handler,
+ dispatchImmediately,
+ );
+ }
+}
diff --git a/src/events/index.ts b/src/events/index.ts
new file mode 100644
index 00000000..90dc1995
--- /dev/null
+++ b/src/events/index.ts
@@ -0,0 +1,4 @@
+export * from './AsyncEventDispatcher';
+export * from './EventDispatcher';
+export * from './EventDispatcherBase';
+export * from './ValueDispatcher';
diff --git a/src/media/AudioManager.ts b/src/media/AudioManager.ts
index 618fb179..c7c6f3f9 100644
--- a/src/media/AudioManager.ts
+++ b/src/media/AudioManager.ts
@@ -1,29 +1,23 @@
import {AudioData} from './AudioData';
-import {SimpleEventDispatcher} from 'strongly-typed-events';
+import {ValueDispatcher} from '../events';
export class AudioManager {
- public get DataChanged() {
- return this.dataChanged.asEvent();
+ public get onDataChanged() {
+ return this.data.subscribable;
}
+ private readonly data = new ValueDispatcher<AudioData>(null);
- public get OffsetChanged() {
- return this.dataChanged.asEvent();
+ public get onOffsetChanged() {
+ return this.offset.subscribable;
}
+ private readonly offset = new ValueDispatcher(0);
private static readonly context = new AudioContext();
private readonly audioElement: HTMLAudioElement = new Audio();
private source: string = null;
- private offset = 0;
private error = false;
- private data: AudioData = null;
- private dataChanged = new SimpleEventDispatcher<AudioData>();
- private offsetChanged = new SimpleEventDispatcher<number>();
private abortController: AbortController = null;
- public getData() {
- return this.data;
- }
-
public getTime() {
return this.toAbsoluteTime(this.audioElement.currentTime);
}
@@ -33,8 +27,7 @@ export class AudioManager {
}
public setOffset(value: number) {
- this.offset = value;
- this.offsetChanged.dispatch(value);
+ this.offset.current = value;
}
public setMuted(isMuted: boolean) {
@@ -54,15 +47,15 @@ export class AudioManager {
}
public isInRange(time: number) {
- return time >= this.offset && time < this.audioElement.duration;
+ return time >= this.offset.current && time < this.audioElement.duration;
}
public toRelativeTime(time: number) {
- return Math.max(0, time - this.offset);
+ return Math.max(0, time - this.offset.current);
}
public toAbsoluteTime(time: number) {
- return time + this.offset;
+ return time + this.offset.current;
}
public isReady() {
@@ -98,8 +91,7 @@ export class AudioManager {
}
private async loadData(signal: AbortSignal) {
- this.data = null;
- this.dataChanged.dispatch(this.data);
+ this.data.current = null;
const response = await fetch(this.source, {signal});
const rawBuffer = await response.arrayBuffer();
@@ -151,13 +143,12 @@ export class AudioManager {
}
}
- this.data = {
+ this.data.current = {
peaks,
absoluteMax,
length: samples,
sampleRate: (audioBuffer.sampleRate / sampleSize) * 2,
};
- this.dataChanged.dispatch(this.data);
}
private decodeAudioData(buffer: ArrayBuffer): Promise<AudioBuffer> {
diff --git a/src/player/Player.ts b/src/player/Player.ts
index f6a4b121..c4e1a852 100644
--- a/src/player/Player.ts
+++ b/src/player/Player.ts
@@ -1,10 +1,10 @@
-import {
- PromiseSimpleEventDispatcher,
- SimpleEventDispatcher,
-} from 'strongly-typed-events';
-
import {AudioManager} from '../media';
import type {Project} from '../Project';
+import {
+ AsyncEventDispatcher,
+ EventDispatcher,
+ ValueDispatcher,
+} from '../events';
const MAX_AUDIO_DESYNC = 1 / 50;
@@ -23,52 +23,54 @@ export interface PlayerState extends Record<string, unknown> {
scale: number;
}
-export interface PlayerTime {
- duration: number;
- durationTime: number;
- frame: number;
- completion: number;
- time: number;
-}
-
interface PlayerCommands {
reset: boolean;
seek: number;
recalculate: boolean;
}
-export interface PlayerRenderEvent {
+export interface RenderData {
frame: number;
data: Blob;
}
export class Player {
- public get StateChanged() {
- return this.stateChanged.asEvent();
+ public get onStateChanged() {
+ return this.state.subscribable;
}
+ private readonly state = new ValueDispatcher<PlayerState>({
+ duration: Infinity,
+ startFrame: 0,
+ endFrame: Infinity,
+ paused: true,
+ loading: false,
+ finished: false,
+ loop: true,
+ speed: 1,
+ render: false,
+ muted: true,
+ fps: 30,
+ scale: 1,
+ });
- public get TimeChanged() {
- return this.timeChanged.asEvent();
+ public get onFrameChanged() {
+ return this.frame.subscribable;
}
+ private readonly frame = new ValueDispatcher(0);
- public get FrameRendered() {
- return this.frameRendered.asEvent();
+ public get onFrameRendered() {
+ return this.frameRendered.subscribable;
}
+ private readonly frameRendered = new AsyncEventDispatcher<RenderData>();
- public get Reloaded() {
- return this.reloaded.asEvent();
+ public get onReloaded() {
+ return this.reloaded.subscribable;
}
-
- private readonly stateChanged = new SimpleEventDispatcher<PlayerState>();
- private readonly timeChanged = new SimpleEventDispatcher<PlayerTime>();
- private readonly frameRendered =
- new PromiseSimpleEventDispatcher<PlayerRenderEvent>();
- private readonly reloaded = new SimpleEventDispatcher<number>();
+ private readonly reloaded = new EventDispatcher<number>();
private startTime: number;
private renderTime = 0;
private requestId: number = null;
- private frame = 0;
private commands: PlayerCommands = {
reset: true,
@@ -76,46 +78,17 @@ export class Player {
recalculate: true,
};
- private state: PlayerState = {
- duration: Infinity,
- startFrame: 0,
- endFrame: Infinity,
- paused: true,
- loading: false,
- finished: false,
- loop: true,
- speed: 1,
- render: false,
- muted: true,
- fps: 30,
- scale: 1,
- };
-
public constructor(
public readonly project: Project,
public readonly audio: AudioManager,
) {
this.startTime = performance.now();
- this.project.framerate = this.state.fps;
- this.project.resolutionScale = this.state.scale;
+ this.project.framerate = this.state.current.fps;
+ this.project.resolutionScale = this.state.current.scale;
this.request();
}
- public getState(): PlayerState {
- return {...this.state};
- }
-
- public getTime(): PlayerTime {
- return {
- frame: this.frame,
- time: this.project.framesToSeconds(this.frame),
- duration: this.state.duration,
- durationTime: this.project.framesToSeconds(this.state.duration),
- completion: this.frame / this.state.duration,
- };
- }
-
public loadState(state: Partial<PlayerState>) {
this.updateState(state);
this.project.framerate = state.fps;
@@ -126,26 +99,20 @@ export class Player {
private updateState(newState: Partial<PlayerState>) {
let changed = false;
for (const prop in newState) {
- if (newState[prop] !== this.state[prop]) {
+ if (newState[prop] !== this.state.current[prop]) {
changed = true;
break;
}
}
if (changed) {
- this.state = {
- ...this.state,
+ this.state.current = {
+ ...this.state.current,
...newState,
};
- this.stateChanged.dispatch(this.state);
}
}
- private updateFrame(value: number) {
- this.frame = value;
- this.timeChanged.dispatch(this.getTime());
- }
-
private consumeCommands(): PlayerCommands {
const commands = {...this.commands};
this.commands.reset = false;
@@ -163,10 +130,10 @@ export class Player {
}
public setRange(
- startFrame = this.state.startFrame,
- endFrame = this.state.endFrame,
+ startFrame = this.state.current.startFrame,
+ endFrame = this.state.current.endFrame,
) {
- if (endFrame >= this.state.duration || !endFrame) {
+ if (endFrame >= this.state.current.duration || !endFrame) {
endFrame = Infinity;
}
@@ -194,15 +161,15 @@ export class Player {
}
public setFramerate(fps: number) {
- const ratio = fps / this.state.fps;
+ const ratio = fps / this.state.current.fps;
this.project.framerate = fps;
this.updateState({
fps,
- startFrame: Math.floor(this.state.startFrame * ratio),
- endFrame: Math.floor(this.state.endFrame * ratio),
- duration: Math.floor(this.state.duration * ratio),
+ startFrame: Math.floor(this.state.current.startFrame * ratio),
+ endFrame: Math.floor(this.state.current.endFrame * ratio),
+ duration: Math.floor(this.state.current.duration * ratio),
});
- this.requestSeek(Math.floor(this.frame * ratio));
+ this.requestSeek(Math.floor(this.frame.current * ratio));
this.reload();
}
@@ -213,11 +180,11 @@ export class Player {
}
public requestPreviousFrame(): void {
- this.commands.seek = this.frame - 1;
+ this.commands.seek = this.frame.current - 1;
}
public requestNextFrame(): void {
- this.commands.seek = this.frame + 1;
+ this.commands.seek = this.frame.current + 1;
}
public requestReset(): void {
@@ -225,18 +192,18 @@ export class Player {
}
public requestSeek(value: number): void {
- this.commands.seek = this.clampRange(value, this.state);
+ this.commands.seek = this.clampRange(value, this.state.current);
}
- public toggleLoop(value = !this.state.loop) {
+ public toggleLoop(value = !this.state.current.loop) {
this.updateState({loop: value});
}
- public togglePlayback(value: boolean = this.state.paused): void {
+ public togglePlayback(value: boolean = this.state.current.paused): void {
this.updateState({paused: !value});
}
- public toggleRendering(value = !this.state.render): void {
+ public toggleRendering(value = !this.state.current.render): void {
if (value) {
this.requestSeek(0);
this.reload();
@@ -244,13 +211,13 @@ export class Player {
this.updateState({render: value});
}
- public toggleAudio(value: boolean = this.state.muted): void {
+ public toggleAudio(value: boolean = this.state.current.muted): void {
this.updateState({muted: !value});
}
private async run() {
const commands = this.consumeCommands();
- const state = {...this.state};
+ const state = {...this.state.current};
if (state.finished && state.loop && commands.seek < 0) {
commands.seek = state.startFrame;
}
@@ -260,7 +227,7 @@ export class Player {
const startTime = performance.now();
await this.project.recalculate();
const duration = this.project.frame;
- const frame = commands.seek < 0 ? this.frame : commands.seek;
+ const frame = commands.seek < 0 ? this.frame.current : commands.seek;
const finished = await this.project.seek(frame);
this.project.draw();
this.updateState({
@@ -271,8 +238,8 @@ export class Player {
? duration
: state.endFrame,
});
- if (this.frame + 1 !== this.project.frame) {
- this.updateFrame(this.project.frame);
+ if (this.frame.current + 1 !== this.project.frame) {
+ this.frame.current = this.project.frame;
}
this.request();
this.reloaded.dispatch(performance.now() - startTime);
@@ -294,7 +261,7 @@ export class Player {
if (state.render) {
state.finished = await this.project.next();
this.project.draw();
- await this.frameRendered.dispatchAsync({
+ await this.frameRendered.dispatch({
frame: this.project.frame,
data: await this.project.getBlob(),
});
@@ -305,7 +272,7 @@ export class Player {
this.updateState({
finished: state.finished,
});
- this.updateFrame(this.project.frame);
+ this.frame.current = this.project.frame;
this.request();
return;
}
@@ -363,7 +330,7 @@ export class Player {
this.updateState({
finished: state.finished || this.project.frame >= state.endFrame,
});
- this.updateFrame(this.project.frame);
+ this.frame.current = this.project.frame;
this.request();
}
@@ -388,7 +355,7 @@ export class Player {
private request() {
this.requestId = requestAnimationFrame(async time => {
- if (time - this.renderTime >= 990 / this.state.fps) {
+ if (time - this.renderTime >= 990 / this.state.current.fps) {
this.renderTime = time;
try {
await this.run();
diff --git a/typedoc.json b/typedoc.json
index 2396015b..85661abd 100644
--- a/typedoc.json
+++ b/typedoc.json
@@ -4,11 +4,12 @@
"entryPoints": [
"src",
"src/animations",
- "src/audio",
"src/components",
"src/decorators",
+ "src/events",
"src/flow",
"src/helpers",
+ "src/media",
"src/player",
"src/styles",
"src/themes",
@@ -16,7 +17,6 @@
"src/transitions",
"src/tweening",
"src/types",
- "src/utils",
- "src/video"
+ "src/utils"
]
}