Visualize Your Ideas With Code
feat(core): spawn function (#951)
Jacob51d8cf0b6459
diff --git a/packages/core/src/flow/run.ts b/packages/core/src/flow/run.tsindex 46ab98ec..a180614d 100644--- a/packages/core/src/flow/run.ts+++ b/packages/core/src/flow/run.ts@@ -1,26 +1,42 @@import {setTaskName, ThreadGenerator} from '../threading';-/**- * Turn the given generator function into a threadable generator.+ * Turn the given generator function into a task.+ *+ * @remarks+ * If you want to immediately run the generator in its own thread, you can use+ * {@link threading.spawn} instead. This function is useful when you want to+ * pass the created task to other flow functions.** @example* ```ts- * yield run(function* () {- * // do things- * });+ * yield* all(+ * run(function* () {+ * // do things+ * }),+ * rect.opacity(1, 1),+ * );* ```** @param runner - A generator function or a factory that creates the generator.*/+export function run(runner: () => ThreadGenerator): ThreadGenerator;/**- * Turn the given generator function into a threadable generator.+ * Turn the given generator function into a task.+ *+ * @remarks+ * If you want to immediately run the generator in its own thread, you can use+ * {@link threading.spawn} instead. This function is useful when you want to+ * pass the created task to other flow functions.** @example* ```ts- * yield run(function* () {- * // do things- * });+ * yield* all(+ * run(function* () {+ * // do things+ * }),+ * rect.opacity(1, 1),+ * );* ```** @param runner - A generator function or a factory that creates the generator.diff --git a/packages/core/src/threading/Thread.ts b/packages/core/src/threading/Thread.tsindex fede482d..67ab8b05 100644--- a/packages/core/src/threading/Thread.ts+++ b/packages/core/src/threading/Thread.ts@@ -1,7 +1,9 @@+import {noop} from '../flow';import {createSignal} from '../signals';-import {endThread, startThread} from '../utils';-import {ThreadGenerator} from './ThreadGenerator';-import {setTaskName} from './names';+import {endThread, startThread, useLogger} from '../utils';+import {ThreadGenerator, isThreadGenerator} from './ThreadGenerator';+import reusedGenerator from './__logs__/reused-generator.md';+import {getTaskName, setTaskName} from './names';/*** A class representing an individual thread.@@ -55,13 +57,25 @@ export class Thread {private isCanceled = false;private isPaused = false;private fixedTime = 0;+ private queue: ThreadGenerator[] = [];public constructor(/*** The generator wrapped by this thread.*/- public readonly runner: ThreadGenerator,- ) {}+ public readonly runner: ThreadGenerator & {task?: Thread},+ ) {+ if (this.runner.task) {+ useLogger().error({+ message: `The generator "${getTaskName(+ this.runner,+ )}" is already being executed by another thread.`,+ remarks: reusedGenerator,+ });+ this.runner = noop();+ }+ this.runner.task = this;+ }/*** Progress the wrapped generator once.@@ -94,8 +108,17 @@ export class Thread {this.children = this.children.filter(child => !child.canceled);}+ public spawn(+ child: ThreadGenerator | (() => ThreadGenerator),+ ): ThreadGenerator {+ if (!isThreadGenerator(child)) {+ child = child();+ }+ this.queue.push(child);+ return child;+ }+public add(child: Thread) {- child.cancel();child.parent = this;child.isCanceled = false;child.time(this.time());@@ -105,9 +128,16 @@ export class Thread {setTaskName(child.runner, `unknown ${this.children.length}`);}+ public drain(callback: (task: ThreadGenerator) => void) {+ this.queue.forEach(callback);+ this.queue = [];+ }+public cancel() {+ this.runner.return();this.isCanceled = true;this.parent = null;+ this.drain(task => task.return());}public pause(value: boolean) {diff --git a/packages/core/src/threading/__logs__/reused-generator.md b/packages/core/src/threading/__logs__/reused-generator.mdnew file mode 100644index 00000000..1f2c25ad--- /dev/null+++ b/packages/core/src/threading/__logs__/reused-generator.md@@ -0,0 +1,41 @@+This usually happens when you mistakenly reuse a generator that is already+running.++For example, using `yield` here will run the opacity generator concurrently and+store it in the `task` variable (in case you want to cancel or await it later):++```ts+const task = yield rect().opacity(1, 1);+```++Trying to `yield` this task again will cause the current error:++```ts+yield task;+```++Passing it to other flow functions will also cause the error:++```ts+// prettier-ignore+yield* all(task);+```++Try to investigate your code looking for `yield` statements whose return value+is reused in this way. Here's an example of a common mistake:++```ts+// wrong ✗+// prettier-ignore+yield* all(+ yield rect().opacity(1, 1),+ yield rect().x(200, 1)+);++// correct ✓+// prettier-ignore+yield* all(+ rect().opacity(1, 1),+ rect().x(200, 1)+);+```diff --git a/packages/core/src/threading/index.ts b/packages/core/src/threading/index.tsindex 0da23507..c45c010b 100644--- a/packages/core/src/threading/index.ts+++ b/packages/core/src/threading/index.ts@@ -9,4 +9,5 @@ export * from './ThreadGenerator';export * from './cancel';export * from './join';export * from './names';+export * from './spawn';export * from './threads';diff --git a/packages/core/src/threading/spawn.ts b/packages/core/src/threading/spawn.tsnew file mode 100644index 00000000..a95416d7--- /dev/null+++ b/packages/core/src/threading/spawn.ts@@ -0,0 +1,33 @@+import {useThread} from '../utils';+import {ThreadGenerator} from './ThreadGenerator';++/**+ * Run the given task concurrently.+ *+ * @example+ * Using an existing task:+ * ```ts+ * spawn(rect().opacity(1, 1));+ * ```+ * Using a generator function:+ * ```ts+ * spawn(function* () {+ * yield* rect().opacity(1, 1);+ * yield* waitFor('click');+ * yield* rect().opacity(0, 1);+ * });+ * ```+ * Await the spawned task:+ * ```ts+ * const task = spawn(rect().opacity(1, 1));+ * // do some other things+ * yield* join(task); // await the task+ * ```+ *+ * @param task - Either a generator function or a task to run.+ */+export function spawn(+ task: ThreadGenerator | (() => ThreadGenerator),+): ThreadGenerator {+ return useThread().spawn(task);+}diff --git a/packages/core/src/threading/threads.test.ts b/packages/core/src/threading/threads.test.tsindex df61fef1..1405b1ad 100644--- a/packages/core/src/threading/threads.test.ts+++ b/packages/core/src/threading/threads.test.ts@@ -2,6 +2,7 @@ import {afterAll, beforeAll, describe, expect, test} from 'vitest';import {PlaybackManager, PlaybackStatus} from '../app';import {noop, run} from '../flow';import {endPlayback, startPlayback, useThread} from '../utils';+import {spawn} from './spawn';import {threads} from './threads';describe('threads()', () => {@@ -9,25 +10,58 @@ describe('threads()', () => {beforeAll(() => startPlayback(status));afterAll(() => endPlayback(status));- test('Execution order', () => {+ test('Execution order - yield', () => {const order: number[] = [];const task = threads(function* () {order.push(0);yield run(function* () {order.push(1);yield;+ order.push(5);+ });+ yield run(function* () {+ order.push(2);+ yield;+ order.push(6);+ });+ order.push(3);+ yield noop();+ order.push(4);+ yield;+ order.push(7);+ });++ [...task];++ expect(order).toEqual([0, 1, 2, 3, 4, 5, 6, 7]);+ });++ test('Execution order - spawn', () => {+ const order: number[] = [];+ const task = threads(function* () {+ order.push(0);+ spawn(function* () {+ order.push(3);+ yield;+ order.push(6);+ });+ spawn(function* () {order.push(4);+ yield;+ order.push(7);});- order.push(2);+ order.push(1);yield noop();- order.push(3);+ order.push(2);yield;order.push(5);+ yield;+ order.push(8);});[...task];- expect(order).toEqual([0, 1, 2, 3, 4, 5]);+ expect(order).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8]);});test('Cancellation of child threads', () => {@@ -37,6 +71,11 @@ describe('threads()', () => {yield;}});+ spawn(function* () {+ for (let i = 0; i < 10; i++) {+ yield;+ }+ });yield;yield;});@@ -51,22 +90,38 @@ describe('threads()', () => {yield run(function* () {order.push(1);yield;- order.push(5);+ order.push(3);+ yield;+ order.push(8);+ });+ const yieldChild = useThread().children[0];+ spawn(function* () {+ order.push(4);+ yield;+ order.push(9);});- const child = useThread().children[0];- child.pause(true);order.push(2);yield;- order.push(3);- yield;- child.pause(false);- order.push(4);++ const spawnChild = useThread().children[1];+ yieldChild.pause(true);+ spawnChild.pause(true);++ order.push(5);yield;order.push(6);+ yield;++ yieldChild.pause(false);+ spawnChild.pause(false);++ order.push(7);+ yield;+ order.push(10);});[...task];- expect(order).toEqual([0, 1, 2, 3, 4, 5, 6]);+ expect(order).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);});});diff --git a/packages/core/src/threading/threads.ts b/packages/core/src/threading/threads.tsindex 06420471..5de1002f 100644--- a/packages/core/src/threading/threads.ts+++ b/packages/core/src/threading/threads.ts@@ -92,6 +92,12 @@ export function* threads(queue.push(thread);} else {thread.update(dt);+ thread.drain(task => {+ const child = new Thread(task);+ thread.add(child);+ newThreads.unshift(child);+ });+newThreads.unshift(thread);}}diff --git a/packages/internal/transformers/markdown-literals.js b/packages/internal/transformers/markdown-literals.jsindex e0319e29..b2c10145 100644--- a/packages/internal/transformers/markdown-literals.js+++ b/packages/internal/transformers/markdown-literals.js@@ -15,6 +15,10 @@ const marked = new Marked(},markedHighlight({highlight(code, lang) {+ code = code+ .split('\n')+ .filter(line => !line.includes('prettier-ignore'))+ .join('\n');const language = highlightJs.getLanguage(lang) ? lang : 'plaintext';return highlightJs.highlight(code, {language}).value;},