Skip to content

Visualize Your Ideas With Code

feat: Promise support

aarthificial711f7937d86a
diff --git a/public/index.html b/public/index.html
index eb82e25c..0d2a42ce 100644
--- a/public/index.html
+++ b/public/index.html
@@ -71,6 +71,16 @@
<option value="0.25">0.25x</option>
</select>
</div>
+ <div>
+ <label for="controls-fps">FPS:</label>
+ <input
+ type="number"
+ readonly
+ id="controls-fps"
+ name="fps"
+ value="0"
+ />
+ </div>
</form>
<script src="index.js"></script>
</body>
diff --git a/src/Player.ts b/src/Player.ts
index bdffdf28..691b2920 100644
--- a/src/Player.ts
+++ b/src/Player.ts
@@ -9,8 +9,12 @@ class Controls {
private from: HTMLInputElement;
private current: HTMLInputElement;
private speed: HTMLInputElement;
+ private fps: HTMLInputElement;
private stepRequested: boolean = false;
private resetRequested: boolean = false;
+ private lastUpdate: number = 0;
+ private updateTimes: number[] = [];
+ private overallTime: number = 0;
public get isPlaying(): boolean {
if (this.stepRequested) {
@@ -48,17 +52,58 @@ class Controls {
this.from = form.from;
this.current = form.current;
this.speed = form.speed;
-
- form.next.addEventListener('click', () => {
- this.stepRequested = true;
- });
- form.refresh.addEventListener('click', () => {
- this.resetRequested = true;
+ this.fps = form.fps;
+
+ form.next.addEventListener('click', this.handleNext);
+ form.refresh.addEventListener('click', this.handleReset);
+
+ this.play.checked = localStorage.getItem('play') === 'true';
+ this.play.addEventListener('change', () => this.toggle(this.play.checked));
+
+ document.addEventListener('keydown', event => {
+ switch (event.key) {
+ case ' ':
+ this.toggle();
+ break;
+ case 'ArrowRight':
+ this.handleNext();
+ break;
+ }
});
}
+ public onReset() {
+ this.overallTime = 0;
+ this.updateTimes = [];
+ }
+
public onFrame(frame: number) {
+ const passed = performance.now() - this.lastUpdate;
+
+ this.overallTime += passed;
+ this.updateTimes.push(passed);
+ if (this.updateTimes.length > 10) {
+ this.overallTime -= this.updateTimes.shift();
+ }
+
+ const average = this.overallTime / this.updateTimes.length;
+ this.fps.value = Math.floor(1000 / average).toString();
this.current.value = Math.floor(frame).toString();
+
+ this.lastUpdate = performance.now();
+ }
+
+ private handleReset = () => {
+ this.resetRequested = true;
+ }
+
+ private handleNext = () => {
+ this.stepRequested = true;
+ }
+
+ private toggle = (value?: boolean) => {
+ this.play.checked = value ?? !this.play.checked;
+ localStorage.setItem('play', this.play.checked ? 'true' : 'false');
}
}
@@ -75,11 +120,12 @@ export function Player(factory: () => Project, audioSrc?: string) {
audio.play();
}
- const reset = () => {
+ const reset = async () => {
startTime = performance.now();
project.start();
- project.next();
+ await project.next();
project.draw();
+ controls.onReset();
controls.onFrame(project.frame);
finished = false;
if (audio) {
@@ -87,53 +133,53 @@ export function Player(factory: () => Project, audioSrc?: string) {
}
};
- const run = () => {
+ const run = async () => {
if (controls.shouldReset) {
- reset();
+ await reset();
}
if (!controls.isPlaying || audio?.currentTime < project.time) {
- requestAnimationFrame(run);
+ request();
return;
}
- try {
- if (finished) {
- if (controls.isLooping) {
- // Prevent animation from restarting too quickly.
- const animationDuration = performance.now() - startTime;
- if (animationDuration < MINIMUM_ANIMATION_DURATION) {
- setTimeout(run, MINIMUM_ANIMATION_DURATION - animationDuration);
- return;
- }
- reset();
- } else {
- requestAnimationFrame(run);
+ if (finished) {
+ if (controls.isLooping) {
+ // Prevent animation from restarting too quickly.
+ const animationDuration = performance.now() - startTime;
+ if (animationDuration < MINIMUM_ANIMATION_DURATION) {
+ setTimeout(run, MINIMUM_ANIMATION_DURATION - animationDuration);
return;
}
+ await reset();
+ } else {
+ request();
+ return;
}
+ }
- finished = project.next(controls.playbackSpeed);
+ finished = await project.next(controls.playbackSpeed);
- // Start from certain frame
- while (project.frame < controls.startFrom && !finished) {
- finished = project.next();
- }
+ // Start from certain frame
+ while (project.frame < controls.startFrom && !finished) {
+ finished = await project.next();
+ }
- // Synchronize animation with audio.
- if (audio?.currentTime - MAX_AUDIO_DESYNC > project.time) {
- while (audio.currentTime > project.time && !finished) {
- finished = project.next();
- }
+ // Synchronize animation with audio.
+ if (audio?.currentTime - MAX_AUDIO_DESYNC > project.time) {
+ while (audio.currentTime > project.time && !finished) {
+ finished = await project.next();
}
-
- project.draw();
- controls.onFrame(project.frame);
- requestAnimationFrame(run);
- } catch (e) {
- console.error(e);
}
+
+ project.draw();
+ controls.onFrame(project.frame);
+ request();
};
- reset();
- run();
+
+ const request = () => {
+ requestAnimationFrame(() => run().catch(console.error));
+ };
+
+ reset().then(request).catch(console.error);
}
diff --git a/src/Project.ts b/src/Project.ts
index 28034734..7d2ff3d4 100644
--- a/src/Project.ts
+++ b/src/Project.ts
@@ -49,6 +49,7 @@ export class Project extends Stage {
super({
width: Sizes[size][0],
height: Sizes[size][1],
+ listening: false,
...config,
});
@@ -89,8 +90,12 @@ export class Project extends Stage {
});
}
- public next(speed: number = 1): boolean {
- const result = this.runner.next();
+ public async next(speed: number = 1): Promise<boolean> {
+ let result = this.runner.next();
+ while (typeof result.value?.then === 'function') {
+ const value = await result.value;
+ result = this.runner.next(value);
+ }
this.frame += speed;
return result.done;
diff --git a/src/animations/threads.ts b/src/animations/threads.ts
index 608aab6a..9954f6d0 100644
--- a/src/animations/threads.ts
+++ b/src/animations/threads.ts
@@ -12,8 +12,8 @@ export interface ThreadsFactory {
export function* threads(factory: ThreadsFactory): Generator {
let runners: Generator[] = [];
- let cancelled: Set<Generator> = new Set<Generator>();
- let previous: Map<Generator, Generator> = new Map<Generator, Generator>();
+ let cancelled= new Set<Generator>();
+ let values = new Map<Generator, any>();
const join = function* (...tasks: Generator[]): Generator {
while (tasks.find(runner => runners.includes(runner))) {
yield;
@@ -33,13 +33,18 @@ export function* threads(factory: ThreadsFactory): Generator {
continue;
}
- const result = runner.next(previous.get(runner));
+ const result = runner.next(values.get(runner));
- if (result.value?.next) {
+ if (typeof result.value?.then === 'function') {
if (!result.done) {
runners.push(runner);
}
- previous.set(runner, result.value);
+ values.set(runner, yield result.value);
+ } else if (result.value?.next) {
+ if (!result.done) {
+ runners.push(runner);
+ }
+ values.set(runner, result.value);
cancelled.delete(result.value);
runners.push(result.value);
} else if (!result.done) {