Visualize Your Ideas With Code
refactor: split player into smaller classes
aarthificial754fa6d27d41
diff --git a/public/index.html b/public/index.htmlindex 0de37d9a..3f4514c2 100644--- a/public/index.html+++ b/public/index.html@@ -35,10 +35,36 @@color: white;background: rgba(0, 0, 0, 0.3);}++ #ui {+ min-width: 360px;+ padding: 8px;+ padding-right: 24px;+ border-radius: 8px;+ display: grid;+ grid-auto-flow: row;+ grid-gap: 8px;+ position: absolute;+ top: 0;+ right: 0;+ color: white;+ background: rgba(0, 0, 0, 0.3);+ }++ #ui ul {+ padding-left: 16px;+ }++ .cancelled {+ color: red;+ }</style></head><body><div id="container"></div>+ <details id="ui">+ <summary>THREADS</summary>+ </details><form id="controls"><div><input type="checkbox" id="controls-play" name="play" checked />diff --git a/src/Project.ts b/src/Project.tsindex 5ac17bc5..11ab0135 100644--- a/src/Project.ts+++ b/src/Project.ts@@ -3,7 +3,8 @@ import {Rect} from 'konva/lib/shapes/Rect';import {Layer} from 'konva/lib/Layer';import {Vector2d} from 'konva/lib/types';import {Konva} from 'konva/lib/Global';-import {threads} from './animations';+import {threads, ThreadsCallback} from './animations';+import {Scene} from './Scene';Konva.autoDrawEnabled = false;@@ -20,6 +21,7 @@ export const PROJECT = Symbol('PROJECT');export class Project extends Stage {public readonly background: Rect;public readonly center: Vector2d;+ public threadsCallback: ThreadsCallback;public framesPerSeconds = 60;public frame: number = 0;public get time(): number {@@ -27,6 +29,7 @@ export class Project extends Stage {}private runner: Generator;+ private readonly scenes = new Set<Scene>();public constructor(private runnerFactory: (project: Project) => Generator,@@ -59,12 +62,29 @@ export class Project extends Stage {this.add(backgroundLayer);}+ public addScene(scene: Scene) {+ if (!this.scenes.has(scene)) {+ this.scenes.add(scene);+ this.add(scene);+ }+ }++ public removeScene(scene: Scene) {+ if (this.scenes.has(scene)) {+ this.scenes.delete(scene);+ scene.destroy();+ }+ }+public start() {- this.getLayers().forEach(- layer => layer.hasName('background') || layer.destroy(),- );+ this.scenes.forEach(scene => scene.destroy());+ this.scenes.clear();this.frame = 0;- this.runner = threads(() => this.runnerFactory(this));+ this.runner = threads(+ () => this.runnerFactory(this),+ (runners, children, cancelled) =>+ this.threadsCallback?.(runners, children, cancelled),+ );}public async next(speed: number = 1): Promise<boolean> {diff --git a/src/Scene.ts b/src/Scene.tsindex 0fe684b7..411c9c6d 100644--- a/src/Scene.ts+++ b/src/Scene.ts@@ -35,7 +35,7 @@ export class Scene extends Layer {}public run(): Generator {- this.project.add(this);+ this.project.addScene(this);const scene = this;this.task = (function* () {yield* scene.runner(scene, scene.project);@@ -78,7 +78,7 @@ export class Scene extends Layer {public *dispose() {this.state = SceneState.Disposed;yield* cancel(this.task);- this.destroy();+ this.project.removeScene(this);}public add(...children: (Shape | Group)[]): this {diff --git a/src/animations/threads.ts b/src/animations/threads.tsindex 0d4100f5..cb50fd1e 100644--- a/src/animations/threads.ts+++ b/src/animations/threads.ts@@ -5,6 +5,14 @@ export interface ThreadsFactory {(): Generator;}+export interface ThreadsCallback {+ (+ runners: Generator[],+ children: Map<Generator, Generator[]>,+ cancelled: Set<Generator>,+ ): void;+}+decorate(join, threadable());export function* join(all: boolean, ...tasks: Generator[]): Generator {yield* (yield {join: tasks, all}) as Generator;@@ -16,7 +24,7 @@ export function* cancel(...tasks: Generator[]): Generator {}decorate(threads, threadable());-export function* threads(factory: ThreadsFactory): Generator {+export function* threads(factory: ThreadsFactory, callback?: ThreadsCallback): Generator {let runners: Generator[] = [];let cancelled = new Set<Generator>();let values = new Map<Generator, any>();@@ -94,7 +102,10 @@ export function* threads(factory: ThreadsFactory): Generator {console.warn('Non-threadable task: ', value);}- GeneratorHelper.makeThreadable(value, `non-threadable ${childTasks.length}`);+ GeneratorHelper.makeThreadable(+ value,+ `non-threadable ${childTasks.length}`,+ );runners.push(runner);runners.push(value);} else if (value) {@@ -105,6 +116,7 @@ export function* threads(factory: ThreadsFactory): Generator {}}runners = newRunners;+ callback?.(runners, children, cancelled);if (runners.length > 0) yield;}}diff --git a/src/Player.ts b/src/player/Controls.tssimilarity index 55%rename from src/Player.tsrename to src/player/Controls.tsindex aef5ac14..a6441dcc 100644--- a/src/Player.ts+++ b/src/player/Controls.ts@@ -1,9 +1,4 @@-import {Project} from './Project';--const MINIMUM_ANIMATION_DURATION = 1000;-const MAX_AUDIO_DESYNC = 1 / 50;--class Controls {+export class Controls {private play: HTMLInputElement;private loop: HTMLInputElement;private from: HTMLInputElement;@@ -111,89 +106,4 @@ class Controls {this.play.checked = value ?? !this.play.checked;localStorage.setItem('play', this.play.checked ? 'true' : 'false');}-}--export function Player(factory: () => Project, audioSrc?: string) {- const controls = new Controls(- <HTMLFormElement>document.getElementById('controls'),- );- const project = factory();- let startTime = performance.now();- let finished = false;- let audio: HTMLAudioElement;- if (audioSrc) {- audio = new Audio(audioSrc);- audio.play();- }-- const reset = async () => {- startTime = performance.now();- project.start();- await project.next();- project.draw();- controls.onReset();- controls.onFrame(project.frame);- finished = false;- if (audio) {- audio.currentTime = 0;- }- };-- const run = async () => {- if (controls.shouldReset) {- await reset();- }-- if (!controls.isPlaying || audio?.currentTime < project.time) {- request();- return;- }-- 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 = await project.next(controls.playbackSpeed);-- // 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 = await project.next();- }- }-- project.draw();- controls.onFrame(project.frame);- request();- };-- const request = () => {- requestAnimationFrame(async () => {- try {- controls.loading = true;- await run();- controls.loading = false;- } catch (e) {- console.log(e);- }- });- };-- reset().then(request).catch(console.error);-}+}\ No newline at end of filediff --git a/src/player/Player.ts b/src/player/Player.tsnew file mode 100644index 00000000..02e362ed--- /dev/null+++ b/src/player/Player.ts@@ -0,0 +1,123 @@+import {Project} from '../Project';+import {Controls} from './Controls';+import {ThreadsMonitor} from "./ThreadsMonitor";++const MINIMUM_ANIMATION_DURATION = 1000;+const MAX_AUDIO_DESYNC = 1 / 50;++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;++ private startTime: number;+ private finished: boolean;++ 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.reset()+ .then(() => this.request())+ .catch(console.error);+ }++ private async reset() {+ this.startTime = performance.now();+ this.project.start();+ await this.project.next();+ this.project.draw();+ this.controls.onReset();+ this.controls.onFrame(this.project.frame);+ this.finished = false;+ if (this.audio) {+ this.audio.currentTime = 0;+ }+ }++ private async run() {+ if (this.controls.shouldReset) {+ await this.reset();+ }++ if (this.controls.playbackSpeed !== 1 && this.audio) {+ this.audio.currentTime = this.project.time;+ } else if (this.controls.isPlaying) {+ if (this.audio?.paused) {+ await this.audio?.play();+ }+ } else {+ if (!this.audio?.paused) {+ this.audio?.pause();+ }+ }++ if (+ !this.controls.isPlaying ||+ (this.controls.playbackSpeed === 1 &&+ 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);++ // Start from certain frame+ while (this.project.frame < this.controls.startFrom && !this.finished) {+ this.finished = await this.project.next();+ }++ // Synchronize animation with audio.+ if (+ this.controls.playbackSpeed === 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();+ }+ }++ this.project.draw();+ this.controls.onFrame(this.project.frame);+ this.request();+ }++ private request() {+ requestAnimationFrame(async () => {+ try {+ this.controls.loading = true;+ await this.run();+ this.controls.loading = false;+ } catch (e) {+ console.log(e);+ }+ });+ }+}diff --git a/src/player/ThreadsMonitor.ts b/src/player/ThreadsMonitor.tsnew file mode 100644index 00000000..034f863f--- /dev/null+++ b/src/player/ThreadsMonitor.ts@@ -0,0 +1,47 @@+import {GeneratorHelper} from '../helpers';++export class ThreadsMonitor {+ public constructor(private readonly root: HTMLElement) {}++ public 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) {+ let element = elements.get(runner);+ if (!element) {+ element = this.createRunnerElement(runner, cancelled);+ root.appendChild(element);+ elements.set(runner, element);+ }++ for (const child of children.get(runner) ?? []) {+ let childElement = elements.get(child);+ if (!childElement) {+ childElement = this.createRunnerElement(child, cancelled);+ elements.set(child, childElement);+ }+ element.appendChild(childElement);+ }+ }++ this.root.querySelector('ul')?.remove();+ this.root.appendChild(root);+ }++ private createRunnerElement(+ runner: Generator,+ cancelled: Set<Generator>,+ ): HTMLElement {+ const element = document.createElement('ul');+ const title = document.createElement('li');+ title.innerText = GeneratorHelper.getName(runner);+ element.appendChild(title);+ element.classList.toggle('cancelled', cancelled.has(runner));++ return element;+ }+}