Skip to content

Visualize Your Ideas With Code

feature: timeline

aarthificialbf2a80dafc59
diff --git a/package-lock.json b/package-lock.json
index c6e33d55..75a7fdfa 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -14,6 +14,7 @@
"image-size": "^1.0.1",
"konva": "^8.3.2",
"mix-color": "^1.1.2",
+ "strongly-typed-events": "^3.0.1",
"three": "^0.138.3",
"ts-loader": "^9.2.6",
"typescript": "^4.5.5",
@@ -3482,6 +3483,80 @@
"node": ">= 0.6"
}
},
+ "node_modules/ste-core": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ste-core/-/ste-core-3.0.1.tgz",
+ "integrity": "sha512-xrfkfjVB2e6dFx8/yu1oYQQj/xwBJHBqLtg1wXVNYVa/6T8zdVw2iV82gcbQUlVNn7gxpKBk5guqP4Bhm4QRrQ==",
+ "engines": {
+ "node": ">=4.2.4"
+ }
+ },
+ "node_modules/ste-events": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ste-events/-/ste-events-3.0.1.tgz",
+ "integrity": "sha512-K9dt5IjY8I+K4ON3t22Dlt34mU4x2XJwQ13H3Uaj4dqig50rfnYmAOprhI8mdcHPmRku1LtR/+6uo3kQZxDgFw==",
+ "dependencies": {
+ "ste-core": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=4.2.4"
+ }
+ },
+ "node_modules/ste-promise-events": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ste-promise-events/-/ste-promise-events-3.0.1.tgz",
+ "integrity": "sha512-KJyNRSrpQ3U7rJq1Xw5D13nZJZTFrYF7/NpZmKC9oTi7Z5X4O6U2ga+k/qNlsi/Aq3U0z/7Zl6f57pr6MhQC/Q==",
+ "dependencies": {
+ "ste-core": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=4.2.4"
+ }
+ },
+ "node_modules/ste-promise-signals": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ste-promise-signals/-/ste-promise-signals-3.0.1.tgz",
+ "integrity": "sha512-XpFz/coOZ9ibPMBfYXg+qzSDQ3MOOWrB77DjrBH8cf3gpESSK62WKd24gdKMOPNj5kwEyUQgazJx2+CCiQMdiA==",
+ "dependencies": {
+ "ste-core": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=4.2.4"
+ }
+ },
+ "node_modules/ste-promise-simple-events": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ste-promise-simple-events/-/ste-promise-simple-events-3.0.1.tgz",
+ "integrity": "sha512-p3hpQLP0LCUNxaeLDPPl/5Uek48F/4qCjb7E5DiIpndYvZYg5ktLsCLpF+trcB0mhTYdVLcIIYhjwXMs0PbmBg==",
+ "dependencies": {
+ "ste-core": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=4.2.4"
+ }
+ },
+ "node_modules/ste-signals": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ste-signals/-/ste-signals-3.0.1.tgz",
+ "integrity": "sha512-jdRfpZbbloxYsDon3lzAxSPwOOfvSZypVzdSz/DcSZrpL6Nek/zA43uKXMqfOkUACUmiuR7347/ZuTrXCMTEkg==",
+ "dependencies": {
+ "ste-core": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=4.2.4"
+ }
+ },
+ "node_modules/ste-simple-events": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ste-simple-events/-/ste-simple-events-3.0.1.tgz",
+ "integrity": "sha512-5DgUXYF2eHKa5s2XxZsQeOesfuealapbJVEilTmcvnz5tw3wagL9lwGVkPGq8Eg/kCnuRYajn0p4YT7tpTQO2w==",
+ "dependencies": {
+ "ste-core": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=4.2.4"
+ }
+ },
"node_modules/string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
@@ -3522,6 +3597,23 @@
"node": ">=6"
}
},
+ "node_modules/strongly-typed-events": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/strongly-typed-events/-/strongly-typed-events-3.0.1.tgz",
+ "integrity": "sha512-9n2TiOEWvrjlHqT1OrnuCIe9HeaQk5FlmP1FMAmOmv0DFxrUYswCxsr8jF+/Hm8oYUFgdFxxWwgeb8WwImArSw==",
+ "dependencies": {
+ "ste-core": "^3.0.1",
+ "ste-events": "^3.0.1",
+ "ste-promise-events": "^3.0.1",
+ "ste-promise-signals": "^3.0.1",
+ "ste-promise-simple-events": "^3.0.1",
+ "ste-signals": "^3.0.1",
+ "ste-simple-events": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=4.2.4"
+ }
+ },
"node_modules/supports-color": {
"version": "8.1.1",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
@@ -6808,6 +6900,59 @@
"resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz",
"integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow="
},
+ "ste-core": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ste-core/-/ste-core-3.0.1.tgz",
+ "integrity": "sha512-xrfkfjVB2e6dFx8/yu1oYQQj/xwBJHBqLtg1wXVNYVa/6T8zdVw2iV82gcbQUlVNn7gxpKBk5guqP4Bhm4QRrQ=="
+ },
+ "ste-events": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ste-events/-/ste-events-3.0.1.tgz",
+ "integrity": "sha512-K9dt5IjY8I+K4ON3t22Dlt34mU4x2XJwQ13H3Uaj4dqig50rfnYmAOprhI8mdcHPmRku1LtR/+6uo3kQZxDgFw==",
+ "requires": {
+ "ste-core": "^3.0.1"
+ }
+ },
+ "ste-promise-events": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ste-promise-events/-/ste-promise-events-3.0.1.tgz",
+ "integrity": "sha512-KJyNRSrpQ3U7rJq1Xw5D13nZJZTFrYF7/NpZmKC9oTi7Z5X4O6U2ga+k/qNlsi/Aq3U0z/7Zl6f57pr6MhQC/Q==",
+ "requires": {
+ "ste-core": "^3.0.1"
+ }
+ },
+ "ste-promise-signals": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ste-promise-signals/-/ste-promise-signals-3.0.1.tgz",
+ "integrity": "sha512-XpFz/coOZ9ibPMBfYXg+qzSDQ3MOOWrB77DjrBH8cf3gpESSK62WKd24gdKMOPNj5kwEyUQgazJx2+CCiQMdiA==",
+ "requires": {
+ "ste-core": "^3.0.1"
+ }
+ },
+ "ste-promise-simple-events": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ste-promise-simple-events/-/ste-promise-simple-events-3.0.1.tgz",
+ "integrity": "sha512-p3hpQLP0LCUNxaeLDPPl/5Uek48F/4qCjb7E5DiIpndYvZYg5ktLsCLpF+trcB0mhTYdVLcIIYhjwXMs0PbmBg==",
+ "requires": {
+ "ste-core": "^3.0.1"
+ }
+ },
+ "ste-signals": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ste-signals/-/ste-signals-3.0.1.tgz",
+ "integrity": "sha512-jdRfpZbbloxYsDon3lzAxSPwOOfvSZypVzdSz/DcSZrpL6Nek/zA43uKXMqfOkUACUmiuR7347/ZuTrXCMTEkg==",
+ "requires": {
+ "ste-core": "^3.0.1"
+ }
+ },
+ "ste-simple-events": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ste-simple-events/-/ste-simple-events-3.0.1.tgz",
+ "integrity": "sha512-5DgUXYF2eHKa5s2XxZsQeOesfuealapbJVEilTmcvnz5tw3wagL9lwGVkPGq8Eg/kCnuRYajn0p4YT7tpTQO2w==",
+ "requires": {
+ "ste-core": "^3.0.1"
+ }
+ },
"string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
@@ -6839,6 +6984,20 @@
"resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz",
"integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA=="
},
+ "strongly-typed-events": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/strongly-typed-events/-/strongly-typed-events-3.0.1.tgz",
+ "integrity": "sha512-9n2TiOEWvrjlHqT1OrnuCIe9HeaQk5FlmP1FMAmOmv0DFxrUYswCxsr8jF+/Hm8oYUFgdFxxWwgeb8WwImArSw==",
+ "requires": {
+ "ste-core": "^3.0.1",
+ "ste-events": "^3.0.1",
+ "ste-promise-events": "^3.0.1",
+ "ste-promise-signals": "^3.0.1",
+ "ste-promise-simple-events": "^3.0.1",
+ "ste-signals": "^3.0.1",
+ "ste-simple-events": "^3.0.1"
+ }
+ },
"supports-color": {
"version": "8.1.1",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
diff --git a/package.json b/package.json
index 3e5c0409..2e0fbdd8 100644
--- a/package.json
+++ b/package.json
@@ -16,6 +16,7 @@
"image-size": "^1.0.1",
"konva": "^8.3.2",
"mix-color": "^1.1.2",
+ "strongly-typed-events": "^3.0.1",
"three": "^0.138.3",
"ts-loader": "^9.2.6",
"typescript": "^4.5.5",
diff --git a/public/index.html b/public/index.html
index 2be2bd17..7b8f09b9 100644
--- a/public/index.html
+++ b/public/index.html
@@ -58,6 +58,44 @@
.cancelled {
color: red;
}
+
+ #timeline {
+ padding: 16px;
+ position: absolute;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ }
+
+ .track {
+ border-radius: 4px;
+ height: 8px;
+ background: rgba(255, 255, 255, 0.3);
+ position: relative;
+ }
+
+ .fill {
+ background-color: white;
+ border-radius: 4px;
+ width: 25%;
+ position: absolute;
+ top: 0;
+ left: 0;
+ bottom: 0;
+ }
+
+ .fill-start {
+ background-color: #FF5F5D;
+ }
+
+ .marker {
+ position: absolute;
+ top: 12px;
+ bottom: 12px;
+ width: 8px;
+ border-radius: 4px;
+ background-color: #FF5F5D;
+ }
</style>
</head>
<body>
@@ -65,6 +103,14 @@
<details id="ui">
<summary>THREADS</summary>
</details>
+ <div id="timeline">
+ <div class="track">
+ <div class="fill fill-seek"></div>
+ <div class="fill fill-time"></div>
+ <div class="fill fill-start"></div>
+ </div>
+ <div class="marker"></div>
+ </div>
<form id="controls">
<div>
<input type="checkbox" id="controls-play" name="play" checked />
diff --git a/src/patches/Node.ts b/src/patches/Node.ts
index 7a675a7b..536c12c0 100644
--- a/src/patches/Node.ts
+++ b/src/patches/Node.ts
@@ -20,6 +20,8 @@ function patchedPosition(
.key(value, time)
.run();
}
- return oldPosition.call(this, value);
+ return value === undefined
+ ? oldPosition.call(this)
+ : oldPosition.call(this, value);
}
Node.prototype.position = patchedPosition;
diff --git a/src/player/Controls.ts b/src/player/Controls.ts
index 448954dc..9acedc8b 100644
--- a/src/player/Controls.ts
+++ b/src/player/Controls.ts
@@ -1,3 +1,5 @@
+import {Player, PlayerRenderEvent, PlayerState} from './Player';
+
export class Controls {
private play: HTMLInputElement;
private loop: HTMLInputElement;
@@ -6,35 +8,15 @@ export class Controls {
private speed: HTMLInputElement;
private fps: HTMLInputElement;
private loadingIndicator: HTMLElement;
- private stepRequested: boolean = false;
- private resetRequested: boolean = false;
- private rendering: boolean = false;
private lastUpdate: number = 0;
private updateTimes: number[] = [];
private overallTime: number = 0;
private directory: FileSystemDirectoryHandle;
- public set loading(value: boolean) {
- this.loadingIndicator.hidden = !value;
- }
-
- public get isLooping(): boolean {
- return this.loop.checked;
- }
-
- public get startFrom(): number {
- return parseInt(this.from.value);
- }
-
- public get playbackSpeed(): number {
- return parseFloat(this.speed.value);
- }
-
- public get isRendering(): boolean {
- return this.rendering;
- }
-
- public constructor(private form: HTMLFormElement) {
+ public constructor(
+ private readonly player: Player,
+ private readonly form: HTMLFormElement,
+ ) {
this.play = form.play;
this.loop = form.loop;
this.from = form.from;
@@ -43,53 +25,66 @@ export class Controls {
this.fps = form.fps;
this.loadingIndicator = document.getElementById('loading');
- form.next.addEventListener('click', this.handleNext);
- form.refresh.addEventListener('click', this.handleReset);
- form.render.addEventListener('click', () => this.toggleRendering());
- this.current.addEventListener(
- 'click',
- () => (this.from.value = this.current.value),
+ this.play.addEventListener('change', () =>
+ this.player.togglePlayback(this.play.checked),
+ );
+ this.loop.addEventListener('change', () =>
+ this.player.updateState({loop: this.loop.checked}),
+ );
+ this.from.addEventListener('change', () =>
+ this.player.updateState({startFrame: parseInt(this.from.value)}),
+ );
+ this.speed.addEventListener('change', () =>
+ this.player.updateState({speed: parseFloat(this.speed.value)}),
);
- this.play.checked = localStorage.getItem('play') === 'true';
- this.play.addEventListener('change', () =>
- this.togglePlayback(this.play.checked),
+ form.refresh.addEventListener('click', () => this.player.requestReset());
+ form.next.addEventListener('click', () => this.player.requestNextFrame());
+ form.render.addEventListener('click', () => this.player.toggleRendering());
+
+ this.current.addEventListener('click', () =>
+ this.player.updateState({startFrame: parseInt(this.current.value)}),
);
document.addEventListener('keydown', event => {
switch (event.key) {
case ' ':
event.preventDefault();
- this.togglePlayback();
+ this.player.togglePlayback();
break;
case 'ArrowRight':
event.preventDefault();
- this.handleNext();
+ this.player.requestNextFrame();
break;
}
});
- }
-
- public consumeState() {
- const state = {
- isPlaying: this.play.checked || this.stepRequested,
- shouldReset: this.resetRequested,
- };
- this.stepRequested = false;
- this.resetRequested = false;
-
- return state;
+ this.player.StateChanged.sub(this.handleStateUpdate);
+ this.player.RenderChanged.sub(this.handleRenderChange);
}
- public onReset() {
- this.overallTime = 0;
- this.updateTimes = [];
- }
+ public handleStateUpdate = (state: PlayerState) => {
+ if (state.frame === state.startFrame || state.frame === 0) {
+ this.overallTime = 0;
+ this.updateTimes = [];
+ }
+
+ this.updateFramerate(state.frame);
+ this.play.checked = !state.paused;
+ this.loop.checked = state.loop;
+ this.from.value = state.startFrame.toString();
+ this.current.value = state.frame.toString();
+ this.speed.value = state.speed.toString();
+ this.loadingIndicator.hidden = !state.loading;
+ };
- public onFrame(frame: number) {
+ private previousFrame: number = 0;
+ public updateFramerate(frame: number) {
const passed = performance.now() - this.lastUpdate;
+ if (this.previousFrame === frame) return;
+ this.previousFrame = frame;
+
this.overallTime += passed;
this.updateTimes.push(passed);
if (this.updateTimes.length > 10) {
@@ -103,9 +98,9 @@ export class Controls {
this.lastUpdate = performance.now();
}
- public async onRender(frame: number, content: Blob) {
+ public handleRenderChange = async ({frame, blob}: PlayerRenderEvent) => {
const name = frame.toString().padStart(6, '0');
- const size = content.size / 1024;
+ const size = blob.size / 1024;
try {
this.directory ??= await window.showDirectoryPicker();
@@ -113,30 +108,13 @@ export class Controls {
create: true,
});
const stream = await file.createWritable();
- await stream.write(content);
+ await stream.write(blob);
await stream.close();
console.log(`Frame: ${name}, Size: ${Math.round(size)} kB`);
- this.onFrame(frame);
+ this.updateFramerate(frame);
} catch (e) {
console.error(e);
- await this.toggleRendering(false);
+ this.player.toggleRendering(false);
}
- }
-
- private handleReset = () => {
- this.resetRequested = true;
- };
-
- private handleNext = () => {
- this.stepRequested = true;
- };
-
- private togglePlayback = (value?: boolean) => {
- this.play.checked = value ?? !this.play.checked;
- localStorage.setItem('play', this.play.checked ? 'true' : 'false');
- };
-
- public toggleRendering = async (value?: boolean) => {
- this.rendering = value ?? !this.rendering;
};
}
diff --git a/src/player/Player.ts b/src/player/Player.ts
index c4bfca23..cbca8001 100644
--- a/src/player/Player.ts
+++ b/src/player/Player.ts
@@ -1,145 +1,299 @@
import {Project} from '../Project';
-import {Controls} from './Controls';
-import {ThreadsMonitor} from './ThreadsMonitor';
+import {
+ PromiseSimpleEventDispatcher,
+ SimpleEventDispatcher,
+} from 'strongly-typed-events';
const MINIMUM_ANIMATION_DURATION = 1000;
const MAX_AUDIO_DESYNC = 1 / 50;
+export interface PlayerState {
+ duration: number;
+ frame: number;
+ startFrame: number;
+ paused: boolean;
+ loading: boolean;
+ finished: boolean;
+ loop: boolean;
+ speed: number;
+ render: boolean;
+}
+
+interface PlayerCommands {
+ next: boolean;
+ reset: boolean;
+ seek: number;
+}
+
+export interface PlayerRenderEvent {
+ frame: number;
+ blob: Blob;
+}
+
export class Player {
- private readonly controls = new Controls(
- <HTMLFormElement>document.getElementById('controls'),
- );
- private readonly threads = new ThreadsMonitor(
- <HTMLElement>document.getElementById('ui'),
- );
- private readonly project: Project;
- private readonly audio: HTMLAudioElement = null;
+ public get StateChanged() {
+ return this.stateChanged.asEvent();
+ }
+ public get RenderChanged() {
+ return this.renderChanged.asEvent();
+ }
+ public readonly project: Project;
+
+ private readonly stateChanged = new SimpleEventDispatcher<PlayerState>();
+ private readonly renderChanged =
+ new PromiseSimpleEventDispatcher<PlayerRenderEvent>();
+ private readonly audio: HTMLAudioElement = null;
private startTime: number;
- private finished: boolean;
+ private ignoreAudioEvents = false;
+
+ private state: PlayerState = {
+ duration: 100,
+ frame: 0,
+ startFrame: 0,
+ paused: true,
+ loading: false,
+ finished: false,
+ loop: true,
+ speed: 1,
+ render: false,
+ };
+
+ private commands: PlayerCommands = {
+ next: false,
+ reset: true,
+ seek: -1,
+ };
+
+ public updateState(newState: Partial<PlayerState>) {
+ this.state = {
+ ...this.state,
+ ...newState,
+ };
+ this.stateChanged.dispatch(this.state);
+ }
+
+ private consumeCommands(): PlayerCommands {
+ const commands = {...this.commands};
+ this.commands.next = false;
+ this.commands.reset = false;
+ this.commands.seek = -1;
+
+ return commands;
+ }
public constructor(factory: () => Project, audioSrc?: string) {
this.project = factory();
this.startTime = performance.now();
- this.finished = false;
- this.project.threadsCallback = this.threads.render.bind(this.threads);
if (audioSrc) {
this.audio = new Audio(audioSrc);
+ this.audio.addEventListener('durationchange', () => {
+ this.updateState({
+ duration: this.project.secondsToFrames(this.audio.duration),
+ });
+ this.requestSeek(this.state.duration);
+ });
+ this.audio.addEventListener('play', () => {
+ if (!this.ignoreAudioEvents) {
+ this.updateState({paused: this.audio.paused});
+ }
+ });
+ this.audio.addEventListener('pause', () => {
+ if (!this.ignoreAudioEvents) {
+ this.updateState({paused: this.audio.paused});
+ }
+ });
}
- this.reset()
- .then(() => this.request())
- .catch(console.error);
+ this.request();
}
- private async reset() {
+ private async reset(state: PlayerState): Promise<PlayerState> {
this.project.start();
- this.finished = await this.project.next();
- while (this.project.frame < this.controls.startFrom && !this.finished) {
- this.finished = await this.project.next();
+ state.finished = await this.project.next();
+ while (this.project.frame < state.startFrame && !state.finished) {
+ state.finished = await this.project.next();
}
this.project.draw();
- this.controls.onReset();
- this.controls.onFrame(this.project.frame);
this.startTime = performance.now();
if (this.audio) {
- this.audio.currentTime = 0;
+ this.audio.currentTime = Math.max(
+ 0,
+ this.project.framesToSeconds(state.startFrame - 3),
+ );
}
+ state.frame = this.project.frame;
+
+ this.updateState({
+ finished: state.finished,
+ frame: state.frame,
+ });
+
+ return state;
}
- private async run() {
- const {isPlaying, shouldReset} = this.controls.consumeState();
+ public requestNextFrame(): void {
+ this.commands.next = true;
+ }
+
+ public requestReset(): void {
+ this.commands.reset = true;
+ }
- if (shouldReset) {
- await this.reset();
+ public requestSeek(value: number): void {
+ this.commands.seek = value;
+ if (value < this.state.startFrame) {
+ this.updateState({startFrame: value});
}
+ }
- if (this.controls.isRendering) {
+ public togglePlayback(value?: boolean): void {
+ this.updateState({
+ paused: !(value ?? this.state.paused),
+ });
+ }
+
+ public toggleRendering(value?: boolean): void {
+ this.updateState({
+ render: !(value ?? this.state.render),
+ });
+ }
+
+ private async run() {
+ let commands = this.consumeCommands();
+ let state = {...this.state};
+ if (commands.seek >= state.startFrame) {
+ state.startFrame = commands.seek;
+ }
+ if (commands.reset || (commands.seek >= 0 && state.frame > commands.seek)) {
+ state = await this.reset(state);
+ }
+
+ // rendering
+ if (state.render) {
+ this.ignoreAudioEvents = true;
if (!this.audio?.paused) {
this.audio?.pause();
}
- this.finished = await this.project.next();
+ state.finished = await this.project.next();
this.project.draw();
- await this.controls.onRender(this.project.frame, await this.getContent());
- if (this.finished) {
- await this.controls.toggleRendering(false);
+ await this.renderChanged.dispatch({
+ frame: this.project.frame,
+ blob: await this.getContent(),
+ });
+ if (state.finished) {
+ state.render = false;
}
+ this.updateState({
+ finished: state.finished,
+ render: state.render,
+ frame: this.project.frame,
+ });
this.request();
+ this.ignoreAudioEvents = false;
return;
}
- if (this.controls.playbackSpeed !== 1 && this.audio) {
+ // synchronize audio.
+ if (state.speed !== 1 && this.audio) {
this.audio.currentTime = this.project.time;
- } else if (isPlaying) {
- if (this.audio?.paused) {
- await this.audio?.play();
+ }
+
+ // pause / play audio.
+ if (this.audio && this.audio.paused !== state.paused) {
+ this.ignoreAudioEvents = true;
+ if (state.paused) {
+ this.audio.pause();
+ } else {
+ this.audio.currentTime = Math.max(
+ 0,
+ this.project.framesToSeconds(this.project.frame - 3),
+ );
+ await this.audio.play();
}
- } else {
- if (!this.audio?.paused) {
- this.audio?.pause();
+ this.ignoreAudioEvents = false;
+ }
+
+ // handle finishing
+ if (state.finished) {
+ this.updateState({
+ duration: this.project.frame,
+ finished: state.finished,
+ });
+
+ if (state.loop) {
+ this.requestReset();
+ }
+
+ // Prevent animation from restarting too quickly.
+ const animationDuration = performance.now() - this.startTime;
+ if (animationDuration < MINIMUM_ANIMATION_DURATION) {
+ setTimeout(
+ () => this.request(),
+ MINIMUM_ANIMATION_DURATION - animationDuration,
+ );
+ } else {
+ this.request();
}
+ return;
}
+ // do nothing if paused or is ahead of the audio.
if (
- !isPlaying ||
- (this.controls.playbackSpeed === 1 &&
- this.audio &&
- this.audio.currentTime < this.project.time)
+ this.project.frame >= state.startFrame &&
+ !commands.next &&
+ (state.paused ||
+ (state.speed === 1 &&
+ this.audio &&
+ this.audio.currentTime < this.project.time))
) {
this.request();
return;
}
- if (this.finished) {
- if (this.controls.isLooping) {
- // Prevent animation from restarting too quickly.
- const animationDuration = performance.now() - this.startTime;
- if (animationDuration < MINIMUM_ANIMATION_DURATION) {
- setTimeout(
- () => this.run(),
- MINIMUM_ANIMATION_DURATION - animationDuration,
- );
- return;
- }
- await this.reset();
- } else {
- this.request();
- return;
- }
- }
-
- this.finished = await this.project.next(this.controls.playbackSpeed);
+ state.finished = await this.project.next(state.speed);
// Start from certain frame
- while (this.project.frame < this.controls.startFrom && !this.finished) {
- this.finished = await this.project.next();
+ if (this.project.frame < state.startFrame) {
+ while (this.project.frame < state.startFrame && !state.finished) {
+ state.finished = await this.project.next();
+ }
+ if (this.audio) {
+ this.audio.currentTime = this.project.framesToSeconds(
+ state.startFrame - 3,
+ );
+ }
}
// Synchronize animation with audio.
if (
- this.controls.playbackSpeed === 1 &&
+ state.speed === 1 &&
this.audio?.currentTime - MAX_AUDIO_DESYNC > this.project.time
) {
- while (this.audio.currentTime > this.project.time && !this.finished) {
- this.finished = await this.project.next();
+ while (this.audio.currentTime > this.project.time && !state.finished) {
+ state.finished = await this.project.next();
}
}
this.project.draw();
- this.controls.onFrame(this.project.frame);
+ this.updateState({
+ finished: state.finished,
+ duration: state.duration,
+ frame: this.project.frame,
+ });
this.request();
}
private request() {
requestAnimationFrame(async () => {
try {
- this.controls.loading = true;
+ this.updateState({loading: true});
await this.run();
- this.controls.loading = false;
+ this.updateState({loading: false});
} catch (e) {
- console.log(e);
+ console.error(e);
}
});
}
diff --git a/src/player/ThreadsMonitor.ts b/src/player/ThreadsMonitor.ts
index 034f863f..31abfddb 100644
--- a/src/player/ThreadsMonitor.ts
+++ b/src/player/ThreadsMonitor.ts
@@ -1,13 +1,19 @@
import {GeneratorHelper} from '../helpers';
+import {Player} from './Player';
export class ThreadsMonitor {
- public constructor(private readonly root: HTMLElement) {}
+ public constructor(
+ private readonly player: Player,
+ private readonly root: HTMLElement,
+ ) {
+ this.player.project.threadsCallback = this.render;
+ }
- public render(
+ private render = (
runners: Generator[],
children: Map<Generator, Generator[]>,
cancelled: Set<Generator>,
- ) {
+ ) => {
const elements = new Map<Generator, HTMLElement>();
const root = document.createElement('ul');
for (const runner of runners) {
@@ -30,7 +36,7 @@ export class ThreadsMonitor {
this.root.querySelector('ul')?.remove();
this.root.appendChild(root);
- }
+ };
private createRunnerElement(
runner: Generator,
diff --git a/src/player/Timeline.ts b/src/player/Timeline.ts
new file mode 100644
index 00000000..cb8f0a8d
--- /dev/null
+++ b/src/player/Timeline.ts
@@ -0,0 +1,72 @@
+import {clampRemap} from '../tweening';
+import {Player, PlayerState} from './Player';
+
+export class Timeline {
+ private readonly fillTime: HTMLElement;
+ private readonly fillSeek: HTMLElement;
+ private readonly fillStart: HTMLElement;
+ private readonly track: HTMLElement;
+ private readonly marker: HTMLElement;
+
+ private duration: number;
+
+ public constructor(
+ private readonly player: Player,
+ private readonly root: HTMLElement,
+ ) {
+ this.fillTime = root.querySelector('.fill-time')!;
+ this.fillSeek = root.querySelector('.fill-seek')!;
+ this.fillStart = root.querySelector('.fill-start')!;
+ this.track = root.querySelector('.track')!;
+ this.marker = root.querySelector('.marker')!;
+
+ this.fillSeek.style.opacity = '0';
+
+ this.player.StateChanged.sub(this.update);
+ this.root.addEventListener('click', e => {
+ this.player.requestSeek(this.mousePositionToFrame(e.clientX));
+ });
+ this.root.addEventListener('contextmenu', e => {
+ e.preventDefault();
+ this.player.updateState({
+ startFrame: this.mousePositionToFrame(e.clientX),
+ });
+ });
+ this.root.addEventListener('mousemove', e => {
+ const rect = this.track.getBoundingClientRect();
+ const x = e.clientX - rect.left;
+ this.fillSeek.style.width = `${x}px`;
+ });
+ this.root.addEventListener('mouseleave', () => {
+ this.fillSeek.style.opacity = '0';
+ });
+ this.root.addEventListener('mouseenter', () => {
+ this.fillSeek.style.opacity = '0.32';
+ });
+ }
+
+ private mousePositionToFrame(position: number) {
+ const rect = this.track.getBoundingClientRect();
+ const x = position - rect.left;
+ return Math.floor(clampRemap(0, rect.width, 0, this.duration, x));
+ }
+
+ private update = (state: PlayerState) => {
+ this.duration = state.duration;
+ const width = this.track.clientWidth;
+ const fillWidth = clampRemap(1, state.duration, 8, width, state.frame);
+ const startWidth = clampRemap(
+ 1,
+ state.duration,
+ 8,
+ width,
+ state.startFrame,
+ );
+ const left =
+ clampRemap(1, state.duration, 0, width - 8, state.startFrame) + 16;
+
+ this.marker.style.left = `${left}px`;
+ this.fillTime.style.width = `${fillWidth}px`;
+ this.fillStart.style.width = `${startWidth}px`;
+ };
+}