Skip to content

Visualize Your Ideas With Code

refactor: object-oriented threads

aarthificialb03f311fb9f0
diff --git a/src/Project.ts b/src/Project.ts
index d55816a3..cad1d789 100644
--- a/src/Project.ts
+++ b/src/Project.ts
@@ -5,7 +5,7 @@ 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 {ThreadsCallback} from './animations';
+import {ThreadsCallback} from './threading';
import {Scene, SceneRunner} from './Scene';
Konva.autoDrawEnabled = false;
diff --git a/src/Scene.ts b/src/Scene.ts
index 8f15819a..bd8ea659 100644
--- a/src/Scene.ts
+++ b/src/Scene.ts
@@ -1,6 +1,6 @@
import type {Project} from './Project';
import {Layer, LayerConfig} from 'konva/lib/Layer';
-import {threads, ThreadsCallback} from './animations';
+import {threads, ThreadsCallback} from './threading';
import {Debug} from './components';
import {Node} from 'konva/lib/Node';
import {Group} from 'konva/lib/Group';
diff --git a/src/animations/index.ts b/src/animations/index.ts
index 16fc439f..1d4d198e 100644
--- a/src/animations/index.ts
+++ b/src/animations/index.ts
@@ -3,4 +3,3 @@ export * from './show';
export * from './surfaceTransition';
export * from './scheduling';
export * from './sequence';
-export * from './threads';
\ No newline at end of file
diff --git a/src/animations/sequence.ts b/src/animations/sequence.ts
index 0e191587..fe82dd26 100644
--- a/src/animations/sequence.ts
+++ b/src/animations/sequence.ts
@@ -1,6 +1,6 @@
import {waitFor} from './scheduling';
-import {join} from './threads';
-import {decorate, threadable} from "../decorators";
+import {decorate, threadable} from '../decorators';
+import {join} from '../threading';
decorate(sequence, threadable());
export function* sequence(delay: number, ...sequences: Generator[]): Generator {
@@ -9,5 +9,5 @@ export function* sequence(delay: number, ...sequences: Generator[]): Generator {
yield* waitFor(delay);
}
- yield* join(true, ...sequences);
+ yield* join(...sequences);
}
diff --git a/src/animations/threads.ts b/src/animations/threads.ts
deleted file mode 100644
index 440c8787..00000000
--- a/src/animations/threads.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import {GeneratorHelper} from '../helpers';
-import {decorate, threadable} from '../decorators';
-
-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;
-}
-
-decorate(cancel, threadable());
-export function* cancel(...tasks: Generator[]): Generator {
- yield {cancel: tasks};
-}
-
-decorate(threads, threadable());
-export function* threads(
- factory: ThreadsFactory,
- callback?: ThreadsCallback,
-): Generator {
- let runners: Generator[] = [];
- let cancelled = new Set<Generator>();
- let values = new Map<Generator, any>();
- let children = new Map<Generator, Generator[]>();
-
- decorate(joinInternal, threadable());
- function* joinInternal(tasks: Generator[], all: boolean): Generator {
- if (all) {
- while (tasks.find(runner => runners.includes(runner))) {
- yield;
- }
- } else {
- while (!tasks.find(runner => !runners.includes(runner))) {
- yield;
- }
- }
- }
-
- const cancelInternal = (tasks: Generator[]) => {
- tasks.forEach(task => cancelled.add(task));
- };
-
- const root = factory();
- GeneratorHelper.makeThreadable(root, 'root');
- runners.push(root);
- while (runners.length > 0) {
- const newRunners = [];
- const cancelledRunners = new Set<Generator>();
- for (let i = 0; i < runners.length; i++) {
- const runner = runners[i];
- // FIXME Keep track of child-parent relations instead.
- const childTasks = (children.get(runner) ?? []).filter(child =>
- runners.includes(child),
- );
- children.set(runner, childTasks);
-
- if (cancelledRunners.has(runner)) {
- continue;
- }
-
- if (cancelled.has(runner)) {
- cancelledRunners.add(runner);
- cancelled.delete(runner);
- children.delete(runner);
- cancelInternal(childTasks);
- continue;
- }
-
- const result = runner.next(values.get(runner));
- values.delete(runner);
-
- if (result.done) {
- cancelledRunners.add(runner);
- cancelled.delete(runner);
- children.delete(runner);
- cancelInternal(childTasks);
- continue;
- }
-
- let value = result.value;
- if (value?.join) {
- value = joinInternal(value.join, value.all);
- } else if (value?.cancel) {
- cancelInternal(value.cancel);
- runners.push(runner);
- continue;
- }
-
- if (value?.next) {
- values.set(runner, value);
- cancelled.delete(value);
- childTasks.push(value);
-
- if (!Object.getPrototypeOf(value).threadable) {
- console.warn('Non-threadable task: ', value);
- }
-
- GeneratorHelper.makeThreadable(
- value,
- `non-threadable ${childTasks.length}`,
- );
- runners.push(runner);
- runners.push(value);
- } else if (value) {
- values.set(runner, yield value);
- runners.push(runner);
- } else {
- newRunners.push(runner);
- }
- }
- runners = newRunners;
- callback?.(runners, children, cancelled);
- if (runners.length > 0) yield;
- }
-}
diff --git a/src/components/Sprite.ts b/src/components/Sprite.ts
index a49f173a..612836ce 100644
--- a/src/components/Sprite.ts
+++ b/src/components/Sprite.ts
@@ -2,10 +2,11 @@ import {Context} from 'konva/lib/Context';
import {Util} from 'konva/lib/Util';
import {GetSet, Vector2d} from 'konva/lib/types';
import {LayoutShape, LayoutShapeConfig} from './LayoutShape';
-import {cancel, waitFor} from '../animations';
+import {waitFor} from '../animations';
import {getset, KonvaNode, threadable} from '../decorators';
import {GeneratorHelper} from '../helpers';
import {map} from '../tweening';
+import {cancel} from '../threading';
export interface SpriteData {
fileName: string;
@@ -146,6 +147,7 @@ export class Sprite extends LayoutShape {
return this.task;
}
+ @threadable()
public *stop() {
if (this.task) {
yield* cancel(this.task);
diff --git a/src/flow/all.ts b/src/flow/all.ts
index 901468e2..1970c9d6 100644
--- a/src/flow/all.ts
+++ b/src/flow/all.ts
@@ -1,10 +1,10 @@
-import {join} from '../animations';
-import {decorate, threadable} from "../decorators";
+import {join} from '../threading';
+import {decorate, threadable} from '../decorators';
decorate(all, threadable());
export function* all(...tasks: Generator[]): Generator {
for (const task of tasks) {
yield task;
}
- yield* join(true, ...tasks);
+ yield* join(...tasks);
}
diff --git a/src/flow/any.ts b/src/flow/any.ts
index c5280278..3f040123 100644
--- a/src/flow/any.ts
+++ b/src/flow/any.ts
@@ -1,4 +1,4 @@
-import {join} from '../animations';
+import {join} from '../threading';
import {decorate, threadable} from '../decorators';
decorate(any, threadable());
diff --git a/src/player/ThreadsMonitor.ts b/src/player/ThreadsMonitor.ts
index 31abfddb..fd29dc1b 100644
--- a/src/player/ThreadsMonitor.ts
+++ b/src/player/ThreadsMonitor.ts
@@ -1,52 +1,51 @@
import {GeneratorHelper} from '../helpers';
import {Player} from './Player';
+import {Thread} from '../threading';
+
+const STORAGE_KEY = 'threads-monitor-state';
export class ThreadsMonitor {
+ private list = document.createElement('ul');
+
public constructor(
private readonly player: Player,
- private readonly root: HTMLElement,
+ private readonly root: HTMLDetailsElement,
) {
+ const savedState = localStorage.getItem(STORAGE_KEY);
+ if (savedState) {
+ this.root.open = JSON.parse(savedState);
+ }
+
this.player.project.threadsCallback = this.render;
+ this.root.addEventListener('toggle', this.handleToggle);
+ this.root.appendChild(this.list);
}
- 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) {
- let element = elements.get(runner);
- if (!element) {
- element = this.createRunnerElement(runner, cancelled);
- root.appendChild(element);
- elements.set(runner, element);
- }
+ private handleToggle = () => {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(this.root.open));
+ };
- 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);
+ private render = (rootThread: Thread) => {
+ if (!this.root.open) return;
+
+ this.list.firstElementChild?.remove();
+ const queue: [Thread, HTMLElement][] = [[rootThread, this.list]];
+ while (queue.length > 0) {
+ const [thread, parent] = queue.shift();
+ const element = this.createRunnerElement(thread);
+ parent.appendChild(element);
+ for (const child of thread.children) {
+ queue.push([child, element]);
}
}
-
- this.root.querySelector('ul')?.remove();
- this.root.appendChild(root);
};
- private createRunnerElement(
- runner: Generator,
- cancelled: Set<Generator>,
- ): HTMLElement {
+ private createRunnerElement(thread: Thread): HTMLElement {
const element = document.createElement('ul');
const title = document.createElement('li');
- title.innerText = GeneratorHelper.getName(runner);
+ title.innerText = GeneratorHelper.getName(thread.runner);
element.appendChild(title);
- element.classList.toggle('cancelled', cancelled.has(runner));
+ element.classList.toggle('cancelled', thread.canceled);
return element;
}
diff --git a/src/threading/Thread.ts b/src/threading/Thread.ts
new file mode 100644
index 00000000..aa0ff0b6
--- /dev/null
+++ b/src/threading/Thread.ts
@@ -0,0 +1,43 @@
+import {GeneratorHelper} from '../helpers';
+
+export class Thread {
+ public children: Thread[] = [];
+ public value: any;
+ private parent: Thread = null;
+
+ public get canceled(): boolean {
+ return this._canceled || (this.parent?.canceled ?? false);
+ }
+
+ private _canceled: boolean = false;
+
+ public constructor(public readonly runner: Generator) {}
+
+ public next(): IteratorResult<unknown> {
+ const result = this.runner.next(this.value);
+ this.value = null;
+ return result;
+ }
+
+ public add(child: Thread) {
+ child.cancel();
+ child.parent = this;
+ child._canceled = false;
+ this.children.push(child);
+
+ if (!Object.getPrototypeOf(child.runner).threadable) {
+ console.warn('Non-threadable task: ', child.runner);
+ GeneratorHelper.makeThreadable(
+ child.runner,
+ `non-threadable ${this.children.length}`,
+ );
+ }
+ }
+
+ public cancel() {
+ if (!this.parent) return;
+ this.parent.children = this.parent.children.filter(child => child !== this);
+ this.parent = null;
+ this._canceled = true;
+ }
+}
diff --git a/src/threading/cancel.ts b/src/threading/cancel.ts
new file mode 100644
index 00000000..f549a1f0
--- /dev/null
+++ b/src/threading/cancel.ts
@@ -0,0 +1,8 @@
+import {decorate, threadable} from '../decorators';
+
+export const THREAD_CANCEL = Symbol('Thread cancel command');
+
+decorate(cancel, threadable());
+export function* cancel(...tasks: Generator[]): Generator {
+ yield {[THREAD_CANCEL]: tasks};
+}
diff --git a/src/threading/index.ts b/src/threading/index.ts
new file mode 100644
index 00000000..45476ada
--- /dev/null
+++ b/src/threading/index.ts
@@ -0,0 +1,4 @@
+export * from './threads';
+export * from './Thread';
+export * from './join';
+export * from './cancel';
diff --git a/src/threading/join.ts b/src/threading/join.ts
new file mode 100644
index 00000000..cde198fc
--- /dev/null
+++ b/src/threading/join.ts
@@ -0,0 +1,20 @@
+import {decorate, threadable} from '../decorators';
+
+export const THREAD_JOIN = Symbol('Thread join command');
+
+decorate(join, threadable());
+export function join(all: boolean, ...tasks: Generator[]): Generator;
+export function join(...tasks: Generator[]): Generator;
+export function* join(
+ first: Generator | boolean,
+ ...tasks: Generator[]
+): Generator {
+ let all = true;
+ if (typeof first === 'boolean') {
+ all = first;
+ } else {
+ tasks.push(first);
+ }
+
+ yield* (yield {[THREAD_JOIN]: tasks, all}) as Generator;
+}
diff --git a/src/threading/threads.ts b/src/threading/threads.ts
new file mode 100644
index 00000000..620dc424
--- /dev/null
+++ b/src/threading/threads.ts
@@ -0,0 +1,96 @@
+import {GeneratorHelper} from '../helpers';
+import {decorate, threadable} from '../decorators';
+import {Thread} from './Thread';
+import {THREAD_JOIN} from './join';
+import {THREAD_CANCEL} from './cancel';
+
+export interface ThreadsFactory {
+ (): Generator;
+}
+
+export interface ThreadsCallback {
+ (root: Thread): void;
+}
+
+decorate(threads, threadable());
+export function* threads(
+ factory: ThreadsFactory,
+ callback?: ThreadsCallback,
+): Generator {
+ let threads: Thread[] = [];
+ const find = (runner: Generator) =>
+ threads.find(thread => thread.runner === runner);
+
+ decorate(joinInternal, threadable());
+ function* joinInternal(tasks: Generator[], all: boolean): Generator {
+ if (all) {
+ while (tasks.find(runner => find(runner))) {
+ yield;
+ }
+ } else {
+ while (!tasks.find(runner => !find(runner))) {
+ yield;
+ }
+ }
+ }
+
+ const root = factory();
+ GeneratorHelper.makeThreadable(root, 'root');
+ const rootThread = new Thread(root);
+ callback?.(rootThread);
+ threads.push(rootThread);
+ while (threads.length > 0) {
+ let hasChanged = false;
+ const newThreads = [];
+
+ for (let i = 0; i < threads.length; i++) {
+ const thread = threads[i];
+ if (thread.canceled) {
+ continue;
+ }
+
+ const result = thread.next();
+ if (result.done) {
+ hasChanged = true;
+ thread.cancel();
+ continue;
+ }
+
+ let value = result.value;
+ if (value?.[THREAD_JOIN]) {
+ value = joinInternal(value[THREAD_JOIN], value.all);
+ } else if (value?.[THREAD_CANCEL]) {
+ value[THREAD_CANCEL].forEach((runner: Generator) => {
+ const cancelThread = find(runner);
+ if (cancelThread) {
+ cancelThread.cancel();
+ }
+ });
+ threads.push(thread);
+ continue;
+ }
+
+ if (value?.next) {
+ const child = find(value) ?? new Thread(value);
+ thread.value = value;
+ if (child.canceled) {
+ console.warn('Reusing a canceled thread: ', child);
+ }
+ thread.add(child);
+ hasChanged = true;
+
+ threads.push(thread);
+ threads.push(child);
+ } else if (value) {
+ thread.value = yield value;
+ threads.push(thread);
+ } else {
+ newThreads.push(thread);
+ }
+ }
+
+ threads = newThreads;
+ if (hasChanged) callback?.(rootThread);
+ if (threads.length > 0) yield;
+ }
+}