Skip to content

Visualize Your Ideas With Code

feat: jsx

aarthificial3a633e882714
diff --git a/src/Project.ts b/src/Project.ts
index 9944e409..5ac17bc5 100644
--- a/src/Project.ts
+++ b/src/Project.ts
@@ -75,6 +75,9 @@ export class Project extends Stage {
result = this.runner.next(value);
} else if (result.value === PROJECT) {
result = this.runner.next(this);
+ } else {
+ console.log('Invalid value: ', result.value);
+ result = this.runner.next();
}
}
this.frame += speed;
diff --git a/src/animations/TimeTween.ts b/src/animations/TimeTween.ts
index 59302a19..21a25933 100644
--- a/src/animations/TimeTween.ts
+++ b/src/animations/TimeTween.ts
@@ -30,6 +30,14 @@ export class TimeTween {
return TimeTween.map(from, to, value ?? this.value);
}
+ public sin(from = 0, to = 1, value?: number) {
+ return TimeTween.remap(-1, 1, from, to, Math.sin(value ?? this.value));
+ }
+
+ public cos(from = 0, to = 1, value?: number) {
+ return TimeTween.remap(-1, 1, from, to, Math.cos(value ?? this.value));
+ }
+
public easeInCirc(from = 0, to = 1) {
const value = 1 - Math.sqrt(1 - Math.pow(this.value, 2));
return TimeTween.map(from, to, value);
diff --git a/src/animations/motion.ts b/src/animations/motion.ts
index e0cdebe8..616ffea0 100644
--- a/src/animations/motion.ts
+++ b/src/animations/motion.ts
@@ -46,7 +46,7 @@ export function move(
Math.pow(positionFrom.y - positionTo.y, 2),
);
- return tween(distance / 1000 * (config.speed ?? 1), value =>
+ return tween(config.speed ?? (distance / 1000), value =>
node.position(value.vector2d(positionFrom, positionTo, value.easeInOutQuint())),
);
}
diff --git a/src/animations/surfaceTransition.ts b/src/animations/surfaceTransition.ts
index ce22cc8d..141b68c6 100644
--- a/src/animations/surfaceTransition.ts
+++ b/src/animations/surfaceTransition.ts
@@ -1,13 +1,22 @@
import {Surface} from '../components/Surface';
import {TimeTween} from './TimeTween';
-import {tween} from "./tween";
-import {decorate, threadable} from "../decorators";
+import {tween} from './tween';
+import {decorate, threadable} from '../decorators';
export interface SurfaceTransitionConfig {
reverse?: boolean;
onSurfaceChange?: (surface: Surface) => void;
- onFromOpacityChange?: (surface: Surface, value: TimeTween) => boolean | void;
- onToOpacityChange?: (surface: Surface, value: TimeTween) => boolean | void;
+ onFromOpacityChange?: (
+ surface: Surface,
+ value: TimeTween,
+ relativeValue: TimeTween,
+ ) => boolean | void;
+ onToOpacityChange?: (
+ surface: Surface,
+ value: TimeTween,
+ relativeValue: TimeTween,
+ ) => boolean | void;
+ transitionTime?: number;
}
decorate(surfaceTransition, threadable());
@@ -20,11 +29,17 @@ export function surfaceTransition(fromSurfaceOriginal: Surface) {
fromSurfaceOriginal.hide();
const from = fromSurfaceOriginal.getMask();
- return function* (target: Surface, config: SurfaceTransitionConfig = {}) {
+ decorate(surfaceTransitionExecutor, threadable());
+ function* surfaceTransitionExecutor(
+ target: Surface,
+ config: SurfaceTransitionConfig = {},
+ ) {
+ const transitionTime = config.transitionTime ?? 1 / 3;
const to = target.getMask();
const toPos = target.getPosition();
const fromPos = fromSurface.getPosition();
+ const relativeValue = new TimeTween(0);
const fromDelta = fromSurface.getOriginDelta(target.getOrigin());
const fromNewPos = {
x: fromPos.x + fromDelta.x,
@@ -42,7 +57,14 @@ export function surfaceTransition(fromSurfaceOriginal: Surface) {
let check = true;
yield* tween(0.6, value => {
- if (value.value > 1 / 3) {
+ if (value.value > transitionTime) {
+ relativeValue.value = TimeTween.clampRemap(
+ transitionTime,
+ 1,
+ 0,
+ 1,
+ value.value,
+ );
if (check) {
target.show();
fromSurface.destroy();
@@ -52,13 +74,15 @@ export function surfaceTransition(fromSurfaceOriginal: Surface) {
...from,
...value.rectArc(from, to, config.reverse),
radius: value.easeInOutCubic(from.radius, to.radius),
- color: value.color(from.color, target.getChild().getColor(), value.easeInOutQuint()),
+ color: value.color(
+ from.color,
+ target.getChild().getColor(),
+ value.easeInOutQuint(),
+ ),
});
target.setPosition(value.rectArc(fromNewPos, toPos, config.reverse));
- if (!config.onToOpacityChange?.(target, value)) {
- target
- .getChild()
- .opacity(Math.max(TimeTween.map(0, 1, value.linear(-1 / 2, 1)), 0));
+ if (!config.onToOpacityChange?.(target, value, relativeValue)) {
+ target.getChild().opacity(relativeValue.value);
}
if (check) {
@@ -66,25 +90,36 @@ export function surfaceTransition(fromSurfaceOriginal: Surface) {
check = false;
}
} else {
+ relativeValue.value = TimeTween.clampRemap(
+ 0,
+ transitionTime,
+ 1,
+ 0,
+ value.value,
+ );
fromSurface.setMask({
...from,
...value.rectArc(from, to, config.reverse),
radius: value.easeInOutCubic(from.radius, to.radius),
- color: value.color(from.color, target.getChild().getColor(), value.easeInOutQuint()),
+ color: value.color(
+ from.color,
+ target.getChild().getColor(),
+ value.easeInOutQuint(),
+ ),
});
fromSurface.setPosition(
value.rectArc(fromPos, toNewPos, config.reverse),
);
- if (!config.onFromOpacityChange?.(target, value)) {
- fromSurface
- .getChild()
- .opacity(TimeTween.map(1, 0, value.linear(0, 3)));
+ if (!config.onFromOpacityChange?.(target, value, relativeValue)) {
+ fromSurface.getChild().opacity(relativeValue.value);
}
}
});
target.setMask(null);
target.show();
- };
+ }
+
+ return surfaceTransitionExecutor;
}
diff --git a/src/components/Arrow.ts b/src/components/Arrow.ts
index e132c786..054dc0bc 100644
--- a/src/components/Arrow.ts
+++ b/src/components/Arrow.ts
@@ -7,6 +7,7 @@ import {
getNumberArrayValidator,
getNumberValidator,
} from 'konva/lib/Validators';
+import {clamp} from 'three/src/math/MathUtils';
export interface ArrowConfig extends ShapeConfig {
radius?: number;
@@ -98,9 +99,7 @@ class CircleSegment extends Segment {
private counter: boolean,
) {
super();
- this.delta = this.counter
- ? this.deltaAngle
- : this.deltaAngle + Math.PI * 2;
+ this.delta = this.counter ? this.deltaAngle : this.deltaAngle + Math.PI * 2;
this.length = Math.abs(this.delta * radius);
}
@@ -247,6 +246,14 @@ export class Arrow extends Shape<ArrowConfig> {
context.fillShape(this);
}
+ public getStart(): number {
+ return clamp(this.attrs.start ?? 0, 0, 1);
+ }
+
+ public getEnd(): number {
+ return clamp(this.attrs.end ?? 1, 0, 1);
+ }
+
private drawArrow(
context: Context,
center: Vector2d,
diff --git a/src/components/ColorPicker.ts b/src/components/ColorPicker.ts
index c18318d6..40caf415 100644
--- a/src/components/ColorPicker.ts
+++ b/src/components/ColorPicker.ts
@@ -2,10 +2,9 @@ import {LinearLayout, LinearLayoutConfig} from 'MC/components/LinearLayout';
import {Rect} from 'konva/lib/shapes/Rect';
import {Range, RangeConfig} from 'MC/components/Range';
import {Node} from 'konva/lib/Node';
-import {GetSet} from 'konva/lib/types';
-import {getset} from 'MC/decorators';
-import mixColor, {parseColor} from "mix-color";
-import {TimeTween} from "MC/animations";
+import {AnimatedGetSet, getset} from '../decorators';
+import mixColor, {parseColor} from 'mix-color';
+import {TimeTween} from '../animations';
export interface ColorPickerConfig extends LinearLayoutConfig {
previewColor?: string;
@@ -23,9 +22,9 @@ const colorRangeConfig: RangeConfig = {
export class ColorPicker extends LinearLayout {
@getset('#000000', ColorPicker.prototype.updateColor)
- public previewColor: GetSet<ColorPickerConfig['previewColor'], this>;
+ public previewColor: AnimatedGetSet<ColorPickerConfig['previewColor'], this>;
@getset(0, ColorPicker.prototype.updateDissolve)
- public dissolve: GetSet<ColorPickerConfig['dissolve'], this>;
+ public dissolve: AnimatedGetSet<ColorPickerConfig['dissolve'], this>;
public readonly preview: Rect;
public readonly r: Range;
@@ -74,6 +73,10 @@ export class ColorPicker extends LinearLayout {
this.g.value(color.g);
this.b.value(color.b);
this.a.value(color.a);
+ this.r.foregroundColor(this.previewColor());
+ this.g.foregroundColor(this.previewColor());
+ this.b.foregroundColor(this.previewColor());
+ this.a.foregroundColor(this.previewColor());
this.preview.fill(this.previewColor());
}
@@ -100,4 +103,15 @@ export class ColorPicker extends LinearLayout {
clone(obj?: any): this {
return Node.prototype.clone.call(this, obj);
}
+
+ protected handleLayoutChange() {
+ if (this.preview) {
+ const rangeWidth = this.preview.width() - 80;
+ this.r.width(rangeWidth);
+ this.g.width(rangeWidth);
+ this.b.width(rangeWidth);
+ this.a.width(rangeWidth);
+ }
+ super.handleLayoutChange();
+ }
}
diff --git a/src/components/LayoutShape.ts b/src/components/LayoutShape.ts
index bca8900c..3a777dcd 100644
--- a/src/components/LayoutShape.ts
+++ b/src/components/LayoutShape.ts
@@ -23,7 +23,7 @@ export abstract class LayoutShape extends Shape implements ILayoutNode {
public getLayoutSize(custom?: LayoutShapeConfig): Size {
const padding =
- (custom?.padd === null || custom?.padd === undefined)
+ custom?.padd === null || custom?.padd === undefined
? this.getPadd()
: new Spacing(custom.padd);
@@ -116,6 +116,11 @@ export abstract class LayoutShape extends Shape implements ILayoutNode {
return getClientRect(this, config);
}
+ public subscribe(event: string, handler: () => void): () => void {
+ this.on(event, handler);
+ return () => this.off(event, handler);
+ }
+
protected fireLayoutChange() {
this.getParent()?.fire(LAYOUT_CHANGE_EVENT, undefined, true);
}
diff --git a/src/components/Range.ts b/src/components/Range.ts
index be305e0d..c0dfbab6 100644
--- a/src/components/Range.ts
+++ b/src/components/Range.ts
@@ -1,7 +1,6 @@
import {LayoutShape, LayoutShapeConfig} from './LayoutShape';
import {Context} from 'konva/lib/Context';
-import {GetSet} from 'konva/lib/types';
-import {getset, KonvaNode} from 'MC/decorators';
+import {AnimatedGetSet, getset, KonvaNode} from 'MC/decorators';
import {CanvasHelper} from 'MC/helpers';
import {TimeTween} from 'MC/animations';
@@ -18,19 +17,19 @@ export interface RangeConfig extends LayoutShapeConfig {
@KonvaNode()
export class Range extends LayoutShape {
@getset([0, 1])
- public range: GetSet<RangeConfig['range'], this>;
+ public range: AnimatedGetSet<RangeConfig['range'], this>;
@getset(0.5)
- public value: GetSet<RangeConfig['value'], this>;
+ public value: AnimatedGetSet<RangeConfig['value'], this>;
@getset(0)
- public precision: GetSet<RangeConfig['precision'], this>;
+ public precision: AnimatedGetSet<RangeConfig['precision'], this>;
@getset('#141414')
- public backgroundColor: GetSet<RangeConfig['backgroundColor'], this>;
+ public backgroundColor: AnimatedGetSet<RangeConfig['backgroundColor'], this>;
@getset('rgba(255, 255, 255, 0.24)')
- public foregroundColor: GetSet<RangeConfig['foregroundColor'], this>;
+ public foregroundColor: AnimatedGetSet<RangeConfig['foregroundColor'], this>;
@getset('rgba(255, 255, 255, 0.54')
- public textColor: GetSet<RangeConfig['textColor'], this>;
+ public textColor: AnimatedGetSet<RangeConfig['textColor'], this>;
@getset(null)
- public label: GetSet<RangeConfig['label'], this>;
+ public label: AnimatedGetSet<RangeConfig['label'], this>;
public constructor(config?: RangeConfig) {
super(config);
diff --git a/src/components/Sprite.ts b/src/components/Sprite.ts
index c82799e8..abc06ab5 100644
--- a/src/components/Sprite.ts
+++ b/src/components/Sprite.ts
@@ -1,15 +1,9 @@
import {Context} from 'konva/lib/Context';
import {Util} from 'konva/lib/Util';
import {GetSet, Vector2d} from 'konva/lib/types';
-import {Factory} from 'konva/lib/Factory';
-import {
- getBooleanValidator,
- getNumberValidator,
- getStringValidator,
-} from 'konva/lib/Validators';
import {LayoutShape, LayoutShapeConfig} from './LayoutShape';
-import {cancel, waitFor} from '../animations';
-import {KonvaNode, threadable} from '../decorators';
+import {cancel, TimeTween, waitFor} from '../animations';
+import {AnimatedGetSet, getset, KonvaNode, threadable} from '../decorators';
import {GeneratorHelper} from '../helpers';
import {ImageData} from 'canvas';
@@ -32,6 +26,8 @@ export interface SpriteConfig extends LayoutShapeConfig {
skin?: string;
playing?: boolean;
fps?: number;
+ mask?: string;
+ maskBlend?: number;
}
export const SPRITE_CHANGE_EVENT = 'spriteChange';
@@ -40,10 +36,18 @@ const COMPUTE_CANVAS_SIZE = 1024;
@KonvaNode()
export class Sprite extends LayoutShape {
+ @getset('', Sprite.prototype.recalculate)
public animation: GetSet<string, this>;
+ @getset('', Sprite.prototype.recalculate)
public skin: GetSet<string, this>;
+ @getset(false)
public playing: GetSet<boolean, this>;
- public fps: GetSet<number, this>;
+ @getset(10)
+ public fps: AnimatedGetSet<number, this>;
+ @getset('', Sprite.prototype.recalculate)
+ public mask: GetSet<string, this>;
+ @getset('', Sprite.prototype.recalculate)
+ public maskBlend: AnimatedGetSet<number, this>;
private readonly animationData: SpriteData;
private frame: FrameData = {
@@ -93,6 +97,8 @@ export class Sprite extends LayoutShape {
private recalculate() {
const skin = this.animationData?.skins[this.skin()];
const animation = this.animationData?.animations[this.animation()];
+ const mask = this.animationData?.skins[this.mask()];
+ const blend = this.maskBlend();
if (!animation || animation.frames.length === 0) return;
this.frameId %= animation.frames.length;
@@ -107,7 +113,7 @@ export class Sprite extends LayoutShape {
if (skin) {
for (let y = 0; y < this.frame.height; y++) {
for (let x = 0; x < this.frame.width; x++) {
- const id = (y * this.frame.width + x) * 4;
+ const id = this.positionToId({x, y});
const skinX = this.frame.data[id];
const skinY = this.frame.data[id + 1];
const skinId = ((skin.height - 1 - skinY) * skin.width + skinX) * 4;
@@ -120,15 +126,21 @@ export class Sprite extends LayoutShape {
(skin.data[skinId + 3] / 255) *
255,
);
+
+ if (mask) {
+ this.imageData.data[id + 3] *= TimeTween.map(
+ 1,
+ mask.data[id] / 255,
+ blend,
+ );
+ }
}
}
} else {
this.imageData.data.set(this.frame.data);
}
- this.context.clearRect(0, 0, this.frame.width, this.frame.height);
this.context.putImageData(this.imageData, 0, 0);
-
this.fire(SPRITE_CHANGE_EVENT);
this.fireLayoutChange();
}
@@ -182,7 +194,7 @@ export class Sprite extends LayoutShape {
}
public getColorAt(position: Vector2d): string {
- const id = (position.y * this.imageData.width + position.x) * 4;
+ const id = this.positionToId(position);
return `rgba(${this.imageData.data[id]
.toString()
.padStart(3, ' ')}, ${this.imageData.data[id + 1]
@@ -191,23 +203,8 @@ export class Sprite extends LayoutShape {
.toString()
.padStart(3, ' ')}, ${this.imageData.data[id + 3] / 255})`;
}
-}
-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());
+ public positionToId(position: Vector2d): number {
+ return (position.y * this.imageData.width + position.x) * 4;
+ }
+}
diff --git a/src/decorators/getset.ts b/src/decorators/getset.ts
index 68bfd640..0cae5df0 100644
--- a/src/decorators/getset.ts
+++ b/src/decorators/getset.ts
@@ -1,7 +1,83 @@
-import {Factory} from "konva/lib/Factory";
+import {Factory} from 'konva/lib/Factory';
+import {Util} from 'konva/lib/Util';
+import {tween} from '../animations';
+import {Spacing} from '../types';
-export function getset(defaultValue?: any, after?: () => void): PropertyDecorator {
+function addSetter(constructor: Function, attr: string, after: () => void) {
+ const method = `set${Util._capitalize(attr)}`;
+ if (!constructor.prototype[method]) {
+ overWriteSetter(constructor, attr, after);
+ }
+}
+
+function overWriteSetter(
+ constructor: Function,
+ attr: string,
+ after?: () => void,
+) {
+ const setter = `set${Util._capitalize(attr)}`;
+ const getter = `get${Util._capitalize(attr)}`;
+ constructor.prototype[setter] = function (val: any, time?: any) {
+ if (time !== undefined) {
+ const from = this[getter]();
+ let mapper = 'linear';
+ if (typeof val === 'string') {
+ if (val.startsWith('#') || val.startsWith('rgb')) {
+ mapper = 'color';
+ } else {
+ mapper = 'text';
+ }
+ } else if (typeof val === 'object') {
+ if ('x' in val) {
+ if ('width' in val) {
+ mapper = 'rectArc';
+ }
+ mapper = 'vector2d';
+ } else if (val instanceof Spacing) {
+ mapper = 'spacing';
+ }
+ }
+
+ return tween(time, value => {
+ // @ts-ignore
+ this._setAttr(attr, value[mapper](from, val, value.easeInOutCubic()));
+ after?.call(this);
+ });
+ }
+
+ this._setAttr(attr, val);
+ after?.call(this);
+
+ return this;
+ };
+}
+
+function addOverloadedGetterSetter(constructor: Function, attr: string) {
+ const capitalizedAttr = Util._capitalize(attr);
+ const setter = 'set' + capitalizedAttr;
+ const getter = 'get' + capitalizedAttr;
+
+ constructor.prototype[attr] = function (...args: any[]) {
+ if (args.length) {
+ return this[setter](...args);
+ }
+ return this[getter]();
+ };
+}
+
+export function getset(
+ defaultValue?: any,
+ after?: () => void,
+): PropertyDecorator {
return function (target, propertyKey) {
- Factory.addGetterSetter(target.constructor, propertyKey, defaultValue, undefined, after);
+ Factory.addGetter(target.constructor, propertyKey, defaultValue);
+ addSetter(target.constructor, <string>propertyKey, after);
+ addOverloadedGetterSetter(target.constructor, <string>propertyKey);
};
-}
\ No newline at end of file
+}
+
+export interface AnimatedGetSet<Type, This> {
+ (): Type;
+ (value: Type): This;
+ (value: Type, time: number): Generator;
+}
diff --git a/src/flow/chain.ts b/src/flow/chain.ts
index 3cf0b6e0..f18ab9ed 100644
--- a/src/flow/chain.ts
+++ b/src/flow/chain.ts
@@ -1,10 +1,9 @@
import {decorate, threadable} from "../decorators";
-function isGenerator(value: any): value is Generator {
+export 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) {
diff --git a/src/flow/delay.ts b/src/flow/delay.ts
new file mode 100644
index 00000000..53e2c36b
--- /dev/null
+++ b/src/flow/delay.ts
@@ -0,0 +1,8 @@
+import {waitFor} from '../animations';
+import {decorate, threadable} from '../decorators';
+
+decorate(delay, threadable());
+export function* delay(time: number, task: Generator): Generator {
+ yield* waitFor(time);
+ yield* task;
+}
diff --git a/src/flow/index.ts b/src/flow/index.ts
index 0d1ff2fd..d4eb428f 100644
--- a/src/flow/index.ts
+++ b/src/flow/index.ts
@@ -1,4 +1,5 @@
export * from './all';
export * from './any';
export * from './chain';
+export * from './delay';
export * from './loop';
diff --git a/src/flow/loop.ts b/src/flow/loop.ts
index bbbbc703..54b64ee3 100644
--- a/src/flow/loop.ts
+++ b/src/flow/loop.ts
@@ -1,8 +1,13 @@
-import {decorate, threadable} from "../decorators";
+import {decorate, threadable} from '../decorators';
decorate(loop, threadable());
-export function* loop(iterations: number, factory: () => Generator) {
+export function* loop(iterations: number, factory: () => Generator | void) {
for (let i = 0; i < iterations; i++) {
- yield* factory();
+ const generator = factory();
+ if (generator) {
+ yield* generator;
+ } else {
+ yield;
+ }
}
}
diff --git a/src/jsx-runtime.ts b/src/jsx-runtime.ts
new file mode 100644
index 00000000..01b08ab9
--- /dev/null
+++ b/src/jsx-runtime.ts
@@ -0,0 +1,25 @@
+import {Node} from 'konva/lib/Node';
+import {Container} from 'konva/lib/Container';
+
+export const Fragment = Symbol.for('mc.fragment');
+export function jsx<TNode extends Node, TConfig>(
+ type: new (config?: TConfig) => TNode,
+ config: TConfig & {children?: Node | Node[], ref?: {value: TNode}},
+ maybeKey: string,
+): TNode {
+ const {children, ref, ...rest} = config;
+ const node = new type(<TConfig>rest);
+ if (children && node instanceof Container) {
+ if (Array.isArray(children)) {
+ node.add(...children);
+ } else {
+ node.add(children);
+ }
+ }
+ if (ref) {
+ ref.value = node;
+ }
+
+ return node;
+}
+export {jsx as jsxs};
diff --git a/tsconfig.json b/tsconfig.json
index f244f51f..8d3d9252 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -11,6 +11,8 @@
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
+ "jsx": "react-jsx",
+ "jsxImportSource": "MC",
"paths": {
"MC/*": [
"../src/*",