Skip to content

Visualize Your Ideas With Code

refactor: decouple functions

aarthificial264769d522ee
diff --git a/src/Project.ts b/src/Project.ts
index 1762363b..9944e409 100644
--- a/src/Project.ts
+++ b/src/Project.ts
@@ -3,20 +3,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 {
- move,
- showTop,
- surfaceTransition,
- showSurface,
- tween,
- waitFor,
- waitUntil,
- sequence,
- threads,
- ThreadsJoin,
- ThreadsCancel,
- showCircle,
-} from './animations';
+import {threads} from './animations';
Konva.autoDrawEnabled = false;
@@ -28,6 +15,8 @@ const Sizes: Record<ProjectSize, [number, number]> = {
[ProjectSize.FullHD]: [1920, 1080],
};
+export const PROJECT = Symbol('PROJECT');
+
export class Project extends Stage {
public readonly background: Rect;
public readonly center: Vector2d;
@@ -75,18 +64,18 @@ export class Project extends Stage {
layer => layer.hasName('background') || layer.destroy(),
);
this.frame = 0;
- this.runner = this.threads((join, cancel) => {
- this.join = join;
- this.cancel = cancel;
- return this.runnerFactory(this);
- });
+ this.runner = threads(() => this.runnerFactory(this));
}
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);
+ while (result.value) {
+ if (typeof result.value.then === 'function') {
+ const value = await result.value;
+ result = this.runner.next(value);
+ } else if (result.value === PROJECT) {
+ result = this.runner.next(this);
+ }
}
this.frame += speed;
@@ -100,17 +89,4 @@ export class Project extends Stage {
public framesToSeconds(frames: number) {
return frames / this.framesPerSeconds;
}
-
- public join: ThreadsJoin;
- public cancel: ThreadsCancel;
- public threads = threads;
- public waitFor = waitFor;
- public waitUntil = waitUntil;
- public tween = tween;
- public moveNode = move;
- public showTop = showTop;
- public showCircle = showCircle;
- public surfaceTransition = surfaceTransition;
- public showSurface = showSurface;
- public sequence = sequence;
}
diff --git a/src/Scene.ts b/src/Scene.ts
index ed8f4a01..cf8d6881 100644
--- a/src/Scene.ts
+++ b/src/Scene.ts
@@ -1,5 +1,7 @@
-import {Layer} from 'konva/lib/Layer';
+import {Layer, LayerConfig} from 'konva/lib/Layer';
import {Project} from './Project';
+import {GeneratorHelper} from './helpers';
+import {cancel} from "./animations";
export interface SceneRunner {
(layer: Scene, project: Project): Generator;
@@ -14,26 +16,37 @@ export enum SceneState {
export class Scene extends Layer {
private state: SceneState = SceneState.Pending;
+ private task: Generator;
public constructor(
public readonly project: Project,
- private runner: SceneRunner,
+ private readonly runner: SceneRunner,
+ config?: LayerConfig,
) {
- super();
+ super(config);
}
- public *run(): Generator {
+ public run(): Generator {
this.project.add(this);
- yield* this.runner(this, this.project);
- this.state = SceneState.Finished;
- // @ts-ignore
- while (this.state !== SceneState.Disposed) {
- yield;
- }
+ const scene = this;
+ this.task = (function* () {
+ yield* scene.runner(scene, scene.project);
+ if (scene.state !== SceneState.Disposed) {
+ scene.state = SceneState.Finished;
+ }
+ while (scene.state !== SceneState.Disposed) {
+ yield;
+ }
+ })();
+ GeneratorHelper.makeThreadable(this.task, `${this.name()} [scene]`);
+
+ return this.task;
}
public activate() {
- this.state = SceneState.Started;
+ if (this.state === SceneState.Pending) {
+ this.state = SceneState.Started;
+ }
}
public *start(): Generator {
@@ -49,11 +62,14 @@ export class Scene extends Layer {
}
public deactivate() {
- this.state = SceneState.Finished;
+ if (this.state === SceneState.Started) {
+ this.state = SceneState.Finished;
+ }
}
- public dispose() {
+ public *dispose() {
this.state = SceneState.Disposed;
+ yield* cancel(this.task);
this.destroy();
}
}
diff --git a/src/animations/motion.ts b/src/animations/motion.ts
index bdbc5b0e..e0cdebe8 100644
--- a/src/animations/motion.ts
+++ b/src/animations/motion.ts
@@ -1,27 +1,26 @@
import {Node} from 'konva/lib/Node';
import {Vector2d} from 'konva/lib/types';
-import {Project} from "../Project";
+import {tween} from "./tween";
+import {decorate, threadable} from "../decorators";
export interface MoveConfig {
absolute?: boolean,
speed?: number,
}
+decorate(move, threadable());
export function move(
- this: Project,
node: Node,
position: Vector2d,
config?: MoveConfig,
): Generator;
export function move(
- this: Project,
node: Node,
positionX: number,
positionY: number,
config?: MoveConfig,
): Generator;
export function move(
- this: Project,
node: Node,
arg0: number | Vector2d,
arg1?: number | MoveConfig,
@@ -47,7 +46,7 @@ export function move(
Math.pow(positionFrom.y - positionTo.y, 2),
);
- return this.tween(distance / 1000 * (config.speed ?? 1), value =>
+ return tween(distance / 1000 * (config.speed ?? 1), value =>
node.position(value.vector2d(positionFrom, positionTo, value.easeInOutQuint())),
);
}
diff --git a/src/animations/scheduling.ts b/src/animations/scheduling.ts
index 76a67a0f..222ceee6 100644
--- a/src/animations/scheduling.ts
+++ b/src/animations/scheduling.ts
@@ -1,12 +1,12 @@
import type {Project} from '../Project';
+import {PROJECT} from '../Project';
+import {decorate, threadable} from "../decorators";
-export function* waitUntil(
- this: Project,
- targetTime = 0,
- after?: Generator,
-): Generator {
- const frames = this.secondsToFrames(targetTime);
- while (this.frame < frames) {
+decorate(waitUntil, threadable());
+export function* waitUntil(targetTime = 0, after?: Generator): Generator {
+ const project = (yield PROJECT) as Project;
+ const frames = project.secondsToFrames(targetTime);
+ while (project.frame < frames) {
yield;
}
@@ -15,14 +15,12 @@ export function* waitUntil(
}
}
-export function* waitFor(
- this: Project,
- seconds = 0,
- after?: Generator,
-): Generator {
- const frames = this.secondsToFrames(seconds);
- const startFrame = this.frame;
- while (this.frame - startFrame < frames) {
+decorate(waitFor, threadable());
+export function* waitFor(seconds = 0, after?: Generator): Generator {
+ const project = (yield PROJECT) as Project;
+ const frames = project.secondsToFrames(seconds);
+ const startFrame = project.frame;
+ while (project.frame - startFrame < frames) {
yield;
}
diff --git a/src/animations/sequence.ts b/src/animations/sequence.ts
index 6c5e993f..0e191587 100644
--- a/src/animations/sequence.ts
+++ b/src/animations/sequence.ts
@@ -1,25 +1,13 @@
-import {Project} from '../Project';
-
-export function* sequence(
- this: Project,
- delay: number,
- ...sequences: Generator[]
-): Generator {
- const delayFrames = this.secondsToFrames(delay);
- const startFrame = this.frame;
- let finished = 0;
- while (finished < sequences.length) {
- finished = 0;
-
- const frames = this.frame - startFrame;
- const amount = Math.floor(frames / delayFrames) + 1;
-
- for (let i = 0; i < Math.min(sequences.length, amount); i++) {
- if (sequences[i].next().done) {
- finished++;
- }
- }
-
- yield;
+import {waitFor} from './scheduling';
+import {join} from './threads';
+import {decorate, threadable} from "../decorators";
+
+decorate(sequence, threadable());
+export function* sequence(delay: number, ...sequences: Generator[]): Generator {
+ for (const sequence1 of sequences) {
+ yield sequence1;
+ yield* waitFor(delay);
}
+
+ yield* join(true, ...sequences);
}
diff --git a/src/animations/show.ts b/src/animations/show.ts
index 3dd813bd..eac8f157 100644
--- a/src/animations/show.ts
+++ b/src/animations/show.ts
@@ -1,30 +1,33 @@
import {Node} from 'konva/lib/Node';
-import {Project} from '../Project';
import {Surface} from '../components/Surface';
import {TimeTween} from './TimeTween';
import {Origin, originPosition, Spacing} from '../types';
import {chain} from '../flow';
import {Vector2d} from 'konva/lib/types';
+import {tween} from './tween';
+import {decorate, threadable} from "../decorators";
-export function showTop(this: Project, node: Node): [Generator, Generator] {
+decorate(showTop, threadable());
+export function showTop(node: Node): [Generator, Generator] {
const to = node.offsetY();
const from = to - 40;
node.offsetY(from);
node.opacity(0);
return [
- this.tween(0.5, value => {
+ tween(0.5, value => {
node.opacity(Math.min(1, value.linear(0, 2)));
node.offsetY(value.easeOutExpo(from, to));
}),
- this.tween(0.5, value => {
+ tween(0.5, value => {
node.opacity(Math.min(1, value.linear(2, 0)));
node.offsetY(value.easeInExpo(to, from));
}),
];
}
-export function showSurface(this: Project, surface: Surface): Generator {
+decorate(showSurface, threadable());
+export function showSurface(surface: Surface): Generator {
const marginFrom = new Spacing();
const margin = surface.getMargin();
const toMask = surface.getMask();
@@ -37,7 +40,7 @@ export function showSurface(this: Project, surface: Surface): Generator {
surface.setMargin(0);
surface.setMask(fromMask);
- return this.tween(0.5, value => {
+ return tween(0.5, value => {
surface.setMask({
...toMask,
width: value.easeInOutCubic(fromMask.width, toMask.width),
@@ -50,12 +53,15 @@ export function showSurface(this: Project, surface: Surface): Generator {
});
}
+decorate(showCircle, threadable());
export function showCircle(
- this: Project,
surface: Surface,
origin?: Origin | Vector2d,
): Generator {
- const position = typeof origin === 'object' ? origin : originPosition(origin ?? surface.getOrigin());
+ const position =
+ typeof origin === 'object'
+ ? origin
+ : originPosition(origin ?? surface.getOrigin());
const mask = surface.getAbsoluteCircleMask({
circleMask: {
...position,
@@ -67,9 +73,10 @@ export function showCircle(
mask.radius = 0;
return chain(
- this.tween(target / 2000, value => {
+ tween(target / 2000, value => {
mask.radius = value.easeInOutCubic(0, target);
}),
() => surface.setCircleMask(null),
);
}
+
diff --git a/src/animations/surfaceTransition.ts b/src/animations/surfaceTransition.ts
index c32e69a3..ce2eed2b 100644
--- a/src/animations/surfaceTransition.ts
+++ b/src/animations/surfaceTransition.ts
@@ -1,6 +1,7 @@
import {Surface} from '../components/Surface';
-import {Project} from '../Project';
import {TimeTween} from './TimeTween';
+import {tween} from "./tween";
+import {decorate, threadable} from "../decorators";
export interface SurfaceTransitionConfig {
reverse?: boolean;
@@ -9,7 +10,8 @@ export interface SurfaceTransitionConfig {
onToOpacityChange?: (surface: Surface, value: TimeTween) => boolean | void;
}
-export function surfaceTransition(this: Project, fromSurfaceOriginal: Surface) {
+decorate(surfaceTransition, threadable());
+export function surfaceTransition(fromSurfaceOriginal: Surface) {
const fromSurface = fromSurfaceOriginal
.clone()
.moveTo(fromSurfaceOriginal.parent)
@@ -18,7 +20,6 @@ export function surfaceTransition(this: Project, fromSurfaceOriginal: Surface) {
fromSurfaceOriginal.hide();
const from = fromSurfaceOriginal.getMask();
- const project = this;
return function* (target: Surface, config: SurfaceTransitionConfig = {}) {
const to = target.getMask();
const toPos = target.getPosition();
@@ -40,7 +41,7 @@ export function surfaceTransition(this: Project, fromSurfaceOriginal: Surface) {
config.onSurfaceChange?.(fromSurface);
let check = true;
- yield* project.tween(0.6, value => {
+ yield* tween(0.6, value => {
if (value.value > 1 / 3) {
if (check) {
target.show();
diff --git a/src/animations/threads.ts b/src/animations/threads.ts
index 5d81d5a8..0d4100f5 100644
--- a/src/animations/threads.ts
+++ b/src/animations/threads.ts
@@ -1,41 +1,67 @@
-export interface ThreadsJoin {
- (...tasks: Generator[]): Generator;
+import {GeneratorHelper} from '../helpers';
+import {decorate, threadable} from '../decorators';
+
+export interface ThreadsFactory {
+ (): Generator;
}
-export interface ThreadsCancel {
- (...tasks: Generator[]): void;
+decorate(join, threadable());
+export function* join(all: boolean, ...tasks: Generator[]): Generator {
+ yield* (yield {join: tasks, all}) as Generator;
}
-export interface ThreadsFactory {
- (join: ThreadsJoin, cancel: ThreadsCancel): Generator;
+decorate(cancel, threadable());
+export function* cancel(...tasks: Generator[]): Generator {
+ yield {cancel: tasks};
}
+decorate(threads, threadable());
export function* threads(factory: ThreadsFactory): Generator {
let runners: Generator[] = [];
let cancelled = new Set<Generator>();
let values = new Map<Generator, any>();
let children = new Map<Generator, Generator[]>();
- const join = function* (...tasks: Generator[]): Generator {
- while (tasks.find(runner => runners.includes(runner))) {
- yield;
+
+ 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 cancel = (...tasks: Generator[]) => {
+ }
+
+ const cancelInternal = (tasks: Generator[]) => {
tasks.forEach(task => cancelled.add(task));
};
- runners.push(factory(join, cancel));
+ 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];
- const childTasks = children.get(runner) ?? [];
+ // 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);
- cancel(...childTasks);
+ cancelInternal(childTasks);
continue;
}
@@ -43,21 +69,37 @@ export function* threads(factory: ThreadsFactory): Generator {
values.delete(runner);
if (result.done) {
+ cancelledRunners.add(runner);
cancelled.delete(runner);
children.delete(runner);
- cancel(...childTasks);
+ cancelInternal(childTasks);
continue;
}
- if (typeof result.value?.then === 'function') {
- values.set(runner, yield result.value);
+ 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);
- } else if (result.value?.next) {
- values.set(runner, result.value);
- cancelled.delete(result.value);
- childTasks.push(result.value);
+ runners.push(value);
+ } else if (value) {
+ values.set(runner, yield value);
runners.push(runner);
- runners.push(result.value);
} else {
newRunners.push(runner);
}
diff --git a/src/animations/tween.ts b/src/animations/tween.ts
index 9b990948..5e503eed 100644
--- a/src/animations/tween.ts
+++ b/src/animations/tween.ts
@@ -1,20 +1,22 @@
import {TimeTween} from './TimeTween';
-import {Project} from '../Project';
+import {PROJECT, Project} from '../Project';
+import {decorate, threadable} from "../decorators";
+decorate(tween, threadable());
export function* tween(
- this: Project,
duration: number,
callback: (value: TimeTween, time: number) => void,
): Generator {
- const frames = this.secondsToFrames(duration);
- let startFrame = this.frame;
+ const project = (yield PROJECT) as Project;
+ const frames = project.secondsToFrames(duration);
+ let startFrame = project.frame;
const timeTween = new TimeTween(0);
- while (this.frame - startFrame < frames) {
- const time = this.framesToSeconds(this.frame - startFrame);
- timeTween.value = (this.frame - startFrame) / frames;
+ while (project.frame - startFrame < frames) {
+ const time = project.framesToSeconds(project.frame - startFrame);
+ timeTween.value = (project.frame - startFrame) / frames;
callback(timeTween, time);
yield;
}
timeTween.value = 1;
- callback(timeTween, this.framesToSeconds(frames));
+ callback(timeTween, project.framesToSeconds(frames));
}
diff --git a/src/components/LayoutGroup.ts b/src/components/LayoutGroup.ts
index cdf7fca4..26c19c79 100644
--- a/src/components/LayoutGroup.ts
+++ b/src/components/LayoutGroup.ts
@@ -13,15 +13,10 @@ import {
import Konva from 'konva';
import {IRect} from 'konva/lib/types';
import Vector2d = Konva.Vector2d;
-import {Project} from '../Project';
export type LayoutGroupConfig = Partial<LayoutAttrs> & ContainerConfig;
export abstract class LayoutGroup extends Group implements ILayoutNode {
- public get project(): Project {
- return <Project>this.getStage();
- }
-
public constructor(config?: LayoutGroupConfig) {
super({
color: '#242424',
@@ -36,6 +31,7 @@ export abstract class LayoutGroup extends Group implements ILayoutNode {
public setRadius(value: number): this {
this.attrs.radius = value;
+ this.fireLayoutChange();
return this;
}
@@ -45,6 +41,7 @@ export abstract class LayoutGroup extends Group implements ILayoutNode {
public setMargin(value: PossibleSpacing): this {
this.attrs.margin = new Spacing(value);
+ this.fireLayoutChange();
return this;
}
@@ -54,6 +51,7 @@ export abstract class LayoutGroup extends Group implements ILayoutNode {
public setPadd(value: PossibleSpacing): this {
this.attrs.padd = new Spacing(value);
+ this.fireLayoutChange();
return this;
}
@@ -63,6 +61,7 @@ export abstract class LayoutGroup extends Group implements ILayoutNode {
public setColor(value: string): this {
this.attrs.color = value;
+ this.fireLayoutChange();
return this;
}
diff --git a/src/components/LayoutShape.ts b/src/components/LayoutShape.ts
index dab205c7..143c2c44 100644
--- a/src/components/LayoutShape.ts
+++ b/src/components/LayoutShape.ts
@@ -11,15 +11,10 @@ import {
} from './ILayoutNode';
import {Origin, Size, PossibleSpacing, Spacing} from '../types';
import {IRect, Vector2d} from 'konva/lib/types';
-import {Project} from "../Project";
export type LayoutShapeConfig = Partial<LayoutAttrs> & ShapeConfig;
export abstract class LayoutShape extends Shape implements ILayoutNode {
- public get project(): Project {
- return <Project>this.getStage();
- }
-
public constructor(config?: LayoutShapeConfig) {
super(config);
this.on(LAYOUT_CHANGE_EVENT, () => this.handleLayoutChange());
@@ -30,6 +25,7 @@ export abstract class LayoutShape extends Shape implements ILayoutNode {
public setRadius(value: number): this {
this.attrs.radius = value;
+ this.fireLayoutChange();
return this;
}
@@ -39,6 +35,7 @@ export abstract class LayoutShape extends Shape implements ILayoutNode {
public setMargin(value: PossibleSpacing): this {
this.attrs.margin = new Spacing(value);
+ this.fireLayoutChange();
return this;
}
@@ -48,6 +45,7 @@ export abstract class LayoutShape extends Shape implements ILayoutNode {
public setPadd(value: PossibleSpacing): this {
this.attrs.padd = new Spacing(value);
+ this.fireLayoutChange();
return this;
}
@@ -57,6 +55,7 @@ export abstract class LayoutShape extends Shape implements ILayoutNode {
public setColor(value: string): this {
this.attrs.color = value;
+ this.fireLayoutChange();
return this;
}
diff --git a/src/components/LayoutText.ts b/src/components/LayoutText.ts
index c03275fc..44ebb18e 100644
--- a/src/components/LayoutText.ts
+++ b/src/components/LayoutText.ts
@@ -9,18 +9,14 @@ import {
LAYOUT_CHANGE_EVENT,
LayoutAttrs,
} from './ILayoutNode';
-import {Project} from '../Project';
import {Origin, Size, PossibleSpacing, Spacing} from '../types';
+import {tween} from "../animations";
export interface LayoutTextConfig extends Partial<LayoutAttrs>, TextConfig {
minWidth?: number;
}
export class LayoutText extends Text implements ILayoutNode {
- public get project(): Project {
- return <Project>this.getStage();
- }
-
private overrideWidth: number | null = null;
private isConstructed = false;
@@ -57,6 +53,7 @@ export class LayoutText extends Text implements ILayoutNode {
public setRadius(value: number): this {
this.attrs.radius = value;
+ this.fireLayoutChange();
return this;
}
@@ -66,6 +63,7 @@ export class LayoutText extends Text implements ILayoutNode {
public setMargin(value: PossibleSpacing): this {
this.attrs.margin = new Spacing(value);
+ this.fireLayoutChange();
return this;
}
@@ -75,6 +73,7 @@ export class LayoutText extends Text implements ILayoutNode {
public setPadd(value: PossibleSpacing): this {
this.attrs.padd = new Spacing(value);
+ this.fireLayoutChange();
return this;
}
@@ -84,6 +83,7 @@ export class LayoutText extends Text implements ILayoutNode {
public setColor(value: string): this {
this.attrs.color = value;
+ this.fireLayoutChange();
return this;
}
@@ -93,6 +93,7 @@ export class LayoutText extends Text implements ILayoutNode {
public setMinWidth(value: number): this {
this.attrs.minWidth = value;
+ this.fireLayoutChange();
return this;
}
@@ -146,7 +147,7 @@ export class LayoutText extends Text implements ILayoutNode {
const toWidth = this.getLayoutSize({text, minWidth: 0}).width;
this.overrideWidth = fromWidth;
- yield* this.project.tween(0.3, value => {
+ yield* tween(0.3, value => {
this.overrideWidth = value.easeInOutCubic(fromWidth, toWidth);
this.setText(value.text(fromText, text, value.easeInOutCubic()));
});
diff --git a/src/components/Sprite.ts b/src/components/Sprite.ts
index f4387554..f4493c5c 100644
--- a/src/components/Sprite.ts
+++ b/src/components/Sprite.ts
@@ -2,10 +2,16 @@ import {Context} from 'konva/lib/Context';
import {Util} from 'konva/lib/Util';
import {GetSet} from 'konva/lib/types';
import {Factory} from 'konva/lib/Factory';
-import {getBooleanValidator, getNumberValidator, getStringValidator,} from 'konva/lib/Validators';
-import {Project} from '../Project';
-import {LayoutShape, LayoutShapeConfig} from "./LayoutShape";
-import {Size} from "../types";
+import {
+ getBooleanValidator,
+ getNumberValidator,
+ getStringValidator,
+} from 'konva/lib/Validators';
+import {LayoutShape, LayoutShapeConfig} from './LayoutShape';
+import {Size} from '../types';
+import {cancel, waitFor} from '../animations';
+import {threadable} from '../decorators';
+import {GeneratorHelper} from 'MC/helpers';
interface FrameData {
fileName: string;
@@ -45,17 +51,13 @@ export class Sprite extends LayoutShape {
fileName: '',
};
private frameId: number = 0;
- private stopped: boolean = false;
+ private task: Generator | null = null;
private readonly computeCanvas: HTMLCanvasElement;
public get context(): CanvasRenderingContext2D {
return this.computeCanvas.getContext('2d');
}
- public get project(): Project {
- return <Project>this.getStage();
- }
-
constructor(config?: SpriteConfig) {
super(config);
this.animationData = config.animationData;
@@ -91,8 +93,8 @@ export class Sprite extends LayoutShape {
}
private recalculate() {
- const skin = this.animationData.skins[this.skin()];
- const animation = this.animationData.animations[this.animation()];
+ const skin = this.animationData?.skins[this.skin()];
+ const animation = this.animationData?.animations[this.animation()];
if (!animation || animation.frames.length === 0) return;
this.frameId %= animation.frames.length;
@@ -130,24 +132,41 @@ export class Sprite extends LayoutShape {
}
public play(): Generator {
- this.stopped = false;
- return this.playRunner();
+ const runTask = this.playRunner();
+ if (this.task) {
+ const previousTask = this.task;
+ this.task = (function* () {
+ yield* cancel(previousTask);
+ yield* runTask;
+ })();
+ GeneratorHelper.makeThreadable(this.task, runTask);
+ } else {
+ this.task = runTask;
+ }
+
+ return this.task;
}
+ public *stop() {
+ if (this.task) {
+ yield* cancel(this.task);
+ this.task = null;
+ }
+ }
+
+ @threadable()
private *playRunner() {
- while (!this.stopped) {
+ this.frameId = 0;
+ while (this.task !== null) {
if (this.playing()) {
this.frameId++;
this.recalculate();
}
- yield* this.project.waitFor(1 / this.fps());
+ yield* waitFor(1 / this.fps());
}
}
- public stop() {
- this.stopped = true;
- }
-
+ @threadable()
public *waitForFrame(frame: number): Generator {
let limit = 1000;
while (this.frameId !== frame && limit > 0) {
@@ -161,7 +180,21 @@ export class Sprite extends LayoutShape {
}
}
-Factory.addGetterSetter(Sprite, 'animation', '', getStringValidator());
-Factory.addGetterSetter(Sprite, 'skin', '', getStringValidator());
+Factory.addGetterSetter(
+ Sprite,
+ 'animation',
+ '',
+ getStringValidator(),
+ //@ts-ignore
+ Sprite.prototype.recalculate,
+);
+Factory.addGetterSetter(
+ Sprite,
+ 'skin',
+ '',
+ getStringValidator(),
+ //@ts-ignore
+ Sprite.prototype.recalculate,
+);
Factory.addGetterSetter(Sprite, 'playing', false, getBooleanValidator());
Factory.addGetterSetter(Sprite, 'fps', 10, getNumberValidator());
diff --git a/src/components/Surface.ts b/src/components/Surface.ts
index ca7ec197..134df2ca 100644
--- a/src/components/Surface.ts
+++ b/src/components/Surface.ts
@@ -3,7 +3,6 @@ import {ContainerConfig} from 'konva/lib/Container';
import {Rect} from 'konva/lib/shapes/Rect';
import {Shape} from 'konva/lib/Shape';
import {parseColor} from 'mix-color';
-import {Project} from '../Project';
import {LayoutGroup} from './LayoutGroup';
import {Origin, Size} from '../types';
import {
@@ -15,6 +14,7 @@ import {
} from './ILayoutNode';
import {CanvasHelper} from '../helpers';
import {Context} from 'konva/lib/Context';
+import {tween} from "../animations";
export type LayoutData = LayoutAttrs & Size;
export interface SurfaceMask {
@@ -107,10 +107,6 @@ export class Surface extends LayoutGroup {
return this;
}
- public get project(): Project {
- return <Project>this.getStage();
- }
-
public *doRipple() {
if (this.surfaceMask) return;
const opaque = parseColor(this.layoutData.color);
@@ -123,7 +119,7 @@ export class Surface extends LayoutGroup {
.cornerRadius(this.layoutData.radius)
.fill(`rgba(${opaque.r}, ${opaque.g}, ${opaque.b}, ${0.5})`);
- yield* this.project.tween(1, value => {
+ yield* tween(1, value => {
const width = this.layoutData.width + value.easeOutExpo(0, 100);
const height = this.layoutData.height + value.easeOutExpo(0, 100);
const radius = this.layoutData.radius + value.easeOutExpo(0, 50);
@@ -145,8 +141,8 @@ export class Surface extends LayoutGroup {
this.ripple.hide();
}
- public getChild(): LayoutNode {
- return this.child;
+ public getChild<T extends LayoutNode>(): T {
+ return <T>this.child;
}
public setMask(data: SurfaceMask) {
diff --git a/src/decorators/decorate.ts b/src/decorators/decorate.ts
new file mode 100644
index 00000000..bc08e3d4
--- /dev/null
+++ b/src/decorators/decorate.ts
@@ -0,0 +1,7 @@
+export function decorate(fn: Function, ...decorators: MethodDecorator[]) {
+ const target = {[fn.name]: fn};
+ const descriptor = Object.getOwnPropertyDescriptor(target, fn.name);
+ for (let i = decorators.length - 1; i >= 0; i--) {
+ decorators[i](target, fn.name, descriptor);
+ }
+}
\ No newline at end of file
diff --git a/src/decorators/index.ts b/src/decorators/index.ts
new file mode 100644
index 00000000..6c53c311
--- /dev/null
+++ b/src/decorators/index.ts
@@ -0,0 +1,2 @@
+export * from './decorate';
+export * from './threadable';
\ No newline at end of file
diff --git a/src/decorators/threadable.ts b/src/decorators/threadable.ts
new file mode 100644
index 00000000..87572a9e
--- /dev/null
+++ b/src/decorators/threadable.ts
@@ -0,0 +1,10 @@
+export function threadable(customName?: string): MethodDecorator {
+ return function (
+ target: any,
+ propertyKey: string,
+ descriptor: PropertyDescriptor,
+ ) {
+ descriptor.value.prototype.name = customName ?? propertyKey;
+ descriptor.value.prototype.threadable = true;
+ };
+}
diff --git a/src/flow/all.ts b/src/flow/all.ts
index 06a53544..901468e2 100644
--- a/src/flow/all.ts
+++ b/src/flow/all.ts
@@ -1,16 +1,10 @@
-// TODO Support threading
-export function* all(...sequences: Generator[]): Generator {
- while (sequences.length > 0) {
- for (let i = sequences.length - 1; i >= 0; i--) {
- const result = sequences[i].next();
- if (result.done) {
- sequences.splice(i, 1);
- }
- if (result.value) {
- console.warn('Unexpected value: ', result.value);
- }
- }
+import {join} from '../animations';
+import {decorate, threadable} from "../decorators";
- yield;
+decorate(all, threadable());
+export function* all(...tasks: Generator[]): Generator {
+ for (const task of tasks) {
+ yield task;
}
+ yield* join(true, ...tasks);
}
diff --git a/src/flow/any.ts b/src/flow/any.ts
index 38401dee..c5280278 100644
--- a/src/flow/any.ts
+++ b/src/flow/any.ts
@@ -1,12 +1,10 @@
-export function* any(...sequences: Generator[]): Generator {
- while (sequences.length > 0) {
- for (let i = sequences.length - 1; i >= 0; i--) {
- const result = sequences[i].next();
- if (result.done) {
- return;
- }
- }
+import {join} from '../animations';
+import {decorate, threadable} from '../decorators';
- yield;
+decorate(any, threadable());
+export function* any(...tasks: Generator[]): Generator {
+ for (const task of tasks) {
+ yield task;
}
+ yield* join(false, ...tasks);
}
diff --git a/src/flow/chain.ts b/src/flow/chain.ts
index d0d1005f..3cf0b6e0 100644
--- a/src/flow/chain.ts
+++ b/src/flow/chain.ts
@@ -1,7 +1,11 @@
+import {decorate, threadable} from "../decorators";
+
function isGenerator(value: any): value is Generator {
return Symbol.iterator in value;
}
+
+decorate(chain, threadable());
export function* chain(...args: (Generator | Function)[]) {
for (const generator of args) {
if (isGenerator(generator)) {
diff --git a/src/flow/loop.ts b/src/flow/loop.ts
index b759f290..bbbbc703 100644
--- a/src/flow/loop.ts
+++ b/src/flow/loop.ts
@@ -1,3 +1,6 @@
+import {decorate, threadable} from "../decorators";
+
+decorate(loop, threadable());
export function* loop(iterations: number, factory: () => Generator) {
for (let i = 0; i < iterations; i++) {
yield* factory();
diff --git a/src/helpers/GeneratorHelper.ts b/src/helpers/GeneratorHelper.ts
new file mode 100644
index 00000000..a196ca4e
--- /dev/null
+++ b/src/helpers/GeneratorHelper.ts
@@ -0,0 +1,17 @@
+export namespace GeneratorHelper {
+ export function makeThreadable(
+ task: Generator,
+ source: Generator | string,
+ ): void {
+ const prototype = Object.getPrototypeOf(task);
+ if (!prototype.threadable) {
+ prototype.threadable = true;
+ prototype.name =
+ typeof source === 'string' ? source : Object.getPrototypeOf(source).name;
+ }
+ }
+
+ export function getName(task: Generator): string {
+ return Object.getPrototypeOf(task).name ?? null;
+ }
+}
diff --git a/src/helpers/index.ts b/src/helpers/index.ts
index facb8cbf..11ec4110 100644
--- a/src/helpers/index.ts
+++ b/src/helpers/index.ts
@@ -1 +1,2 @@
export {CanvasHelper} from './CanvasHelper';
+export {GeneratorHelper} from './GeneratorHelper';
diff --git a/tsconfig.json b/tsconfig.json
index 7fbd1a31..f244f51f 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -10,6 +10,7 @@
"moduleResolution": "node",
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
+ "experimentalDecorators": true,
"paths": {
"MC/*": [
"../src/*",