Visualize Your Ideas With Code
refactor: better property animations
aarthificial4d0cde121fac
diff --git a/src/Project.ts b/src/Project.tsindex 11ab0135..014563cd 100644--- a/src/Project.ts+++ b/src/Project.ts@@ -1,3 +1,5 @@+import './patches';+import {Stage, StageConfig} from 'konva/lib/Stage';import {Rect} from 'konva/lib/shapes/Rect';import {Layer} from 'konva/lib/Layer';@@ -5,6 +7,7 @@ import {Vector2d} from 'konva/lib/types';import {Konva} from 'konva/lib/Global';import {threads, ThreadsCallback} from './animations';import {Scene} from './Scene';+import {PROJECT} from './symbols';Konva.autoDrawEnabled = false;@@ -16,8 +19,6 @@ 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;diff --git a/src/animations/TimeTween.ts b/src/animations/TimeTween.tsdeleted file mode 100644index 21a25933..00000000--- a/src/animations/TimeTween.ts+++ /dev/null@@ -1,183 +0,0 @@-import {IRect, Vector2d} from 'konva/lib/types';-import mixColor from 'mix-color';-import {PossibleSpacing, Spacing} from '../types';--export class TimeTween {- public constructor(public value: number) {}-- public easeInOutCirc(from = 0, to = 1, value?: number) {- value ??= this.value;- value =- value < 0.5- ? (1 - Math.sqrt(1 - Math.pow(2 * value, 2))) / 2- : (Math.sqrt(1 - Math.pow(-2 * value + 2, 2)) + 1) / 2;- return TimeTween.map(from, to, value);- }-- public easeOutExpo(from = 0, to = 1, value?: number) {- value ??= this.value;- value = value === 1 ? 1 : 1 - Math.pow(2, -10 * value);- return TimeTween.map(from, to, value);- }-- public easeInExpo(from = 0, to = 1, value?: number) {- value ??= this.value;- value = value === 0 ? 0 : Math.pow(2, 10 * value - 10);- return TimeTween.map(from, to, value);- }-- public linear(from = 0, to = 1, value?: number) {- 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);- }-- public easeOutCirc(from = 0, to = 1) {- const value = Math.sqrt(1 - Math.pow(this.value - 1, 2));- return TimeTween.map(from, to, value);- }-- public easeInOutCubic(from = 0, to = 1, value?: number) {- value ??= this.value;- value =- value < 0.5- ? 4 * value * value * value- : 1 - Math.pow(-2 * value + 2, 3) / 2;- return TimeTween.map(from, to, value);- }-- public easeInOutQuint(from = 0, to = 1) {- const value =- this.value < 0.5- ? 16 * this.value * this.value * this.value * this.value * this.value- : 1 - Math.pow(-2 * this.value + 2, 5) / 2;- return TimeTween.map(from, to, value);- }-- public text(from: string, to: string, value?: number) {- // left to right- if (to.length > from.length) {- const current = Math.floor(to.length * (value ?? this.value));- const currentLength = Math.floor(- TimeTween.map(from.length - 1, to.length, value ?? this.value),- );- let text = '';- for (let i = 0; i < to.length; i++) {- if (i < current) {- text += to[i];- } else if (from[i] || i <= currentLength) {- text += from[i] ?? to[i];- }- }-- return text;- }- // right to left- else {- const current = Math.round(from.length * (1 - (value ?? this.value)));- const currentLength = Math.floor(- TimeTween.map(from.length + 1, to.length, value ?? this.value),- );- let text = [];- for (let i = from.length - 1; i >= 0; i--) {- if (i < current) {- text.unshift(from[i]);- } else if (to[i] || i < currentLength) {- text.unshift(to[i] ?? from[i]);- }- }-- return text.join('');- }- }-- public color(from: string, to: string, value?: number) {- return mixColor(from, to, value ?? this.value);- }-- public vector2d(from: Vector2d, to: Vector2d, value?: number) {- return {- x: TimeTween.map(from.x, to.x, value ?? this.value),- y: TimeTween.map(from.y, to.y, value ?? this.value),- };- }-- public spacing(from: Spacing, to: Spacing, value?: number): PossibleSpacing {- return [- TimeTween.map(from.top, to.top, value ?? this.value),- TimeTween.map(from.right, to.right, value ?? this.value),- TimeTween.map(from.bottom, to.bottom, value ?? this.value),- TimeTween.map(from.left, to.left, value ?? this.value),- ];- }-- public rectArc(- from: Partial<IRect>,- to: Partial<IRect>,- reverse?: boolean,- value?: number,- ) {- value ??= this.easeInOutQuint(0, Math.PI / 2);- let xValue = Math.sin(value);- let yValue = 1 - Math.cos(value);- if (reverse) {- [xValue, yValue] = [yValue, xValue];- }-- return {- x: TimeTween.map(from.x ?? 0, to.x ?? 0, xValue),- y: TimeTween.map(from.y ?? 0, to.y ?? 0, yValue),- width: TimeTween.map(from.width ?? 0, to.width ?? 0, xValue),- height: TimeTween.map(from.height ?? 0, to.height ?? 0, yValue),- };- }-- public static vector2d(from: Vector2d, to: Vector2d, value: number) {- return {- x: TimeTween.map(from.x, to.x, value),- y: TimeTween.map(from.y, to.y, value),- };- }-- public static map(from: number, to: number, value: number) {- return from + (to - from) * value;- }-- public static remap(- fromIn: number,- toIn: number,- fromOut: number,- toOut: number,- value: number,- ) {- return fromOut + ((value - fromIn) * (toOut - fromOut)) / (toIn - fromIn);- }-- public static clampRemap(- fromIn: number,- toIn: number,- fromOut: number,- toOut: number,- value: number,- ) {- const remappedValue = TimeTween.remap(fromIn, toIn, fromOut, toOut, value);- if (fromOut > toOut) [fromOut, toOut] = [toOut, fromOut];-- return remappedValue < fromOut- ? fromOut- : remappedValue > toOut- ? toOut- : remappedValue;- }-}diff --git a/src/animations/index.ts b/src/animations/index.tsindex ee9aa8ca..16fc439f 100644--- a/src/animations/index.ts+++ b/src/animations/index.ts@@ -1,9 +1,6 @@export * from './motion';export * from './show';-export * from '../utils/pop';export * from './surfaceTransition';-export * from './tween';-export * from './TimeTween';export * from './scheduling';export * from './sequence';export * from './threads';\ No newline at end of filediff --git a/src/animations/motion.ts b/src/animations/motion.tsindex 616ffea0..c2581d71 100644--- a/src/animations/motion.ts+++ b/src/animations/motion.ts@@ -1,11 +1,11 @@import {Node} from 'konva/lib/Node';import {Vector2d} from 'konva/lib/types';-import {tween} from "./tween";-import {decorate, threadable} from "../decorators";+import {decorate, threadable} from '../decorators';+import {tween, easeInOutQuint, vector2dTween} from '../tweening';export interface MoveConfig {- absolute?: boolean,- speed?: number,+ absolute?: boolean;+ speed?: number;}decorate(move, threadable());@@ -46,7 +46,9 @@ export function move(Math.pow(positionFrom.y - positionTo.y, 2),);- return tween(config.speed ?? (distance / 1000), value =>- node.position(value.vector2d(positionFrom, positionTo, value.easeInOutQuint())),+ return tween(config.speed ?? distance / 1000, value =>+ node.position(+ vector2dTween(positionFrom, positionTo, easeInOutQuint(value)),+ ),);}diff --git a/src/animations/scheduling.ts b/src/animations/scheduling.tsindex 222ceee6..858a4507 100644--- a/src/animations/scheduling.ts+++ b/src/animations/scheduling.ts@@ -1,6 +1,6 @@import type {Project} from '../Project';-import {PROJECT} from '../Project';import {decorate, threadable} from "../decorators";+import {PROJECT} from "../symbols";decorate(waitUntil, threadable());export function* waitUntil(targetTime = 0, after?: Generator): Generator {diff --git a/src/animations/show.ts b/src/animations/show.tsindex d841c6fd..32f30e12 100644--- a/src/animations/show.ts+++ b/src/animations/show.ts@@ -1,10 +1,17 @@import {Node} from 'konva/lib/Node';-import {Surface} from '../components/Surface';-import {TimeTween} from './TimeTween';+import {Surface} from '../components';import {Origin, originPosition, Spacing} from '../types';import {chain} from '../flow';import {Vector2d} from 'konva/lib/types';-import {tween} from './tween';+import {+ clampRemap,+ easeInExpo,+ easeInOutCubic,+ easeOutExpo,+ linear,+ spacingTween,+ tween,+} from '../tweening';import {decorate, threadable} from '../decorators';decorate(showTop, threadable());@@ -16,12 +23,12 @@ export function showTop(node: Node): [Generator, Generator] {return [tween(0.5, value => {- node.opacity(Math.min(1, value.linear(0, 2)));- node.offsetY(value.easeOutExpo(from, to));+ node.opacity(Math.min(1, linear(value, 0, 2)));+ node.offsetY(easeOutExpo(value, from, to));}),tween(0.5, value => {- node.opacity(Math.min(1, value.linear(2, 0)));- node.offsetY(value.easeInExpo(to, from));+ node.opacity(Math.min(1, linear(value, 2, 0)));+ node.offsetY(easeInExpo(value, to, from));}),];}@@ -45,13 +52,13 @@ export function showSurface(surface: Surface): Generator {value => {surface.setMask({...toMask,- width: value.easeInOutCubic(fromMask.width, toMask.width),- height: value.easeInOutCubic(fromMask.height, toMask.height),+ width: easeInOutCubic(value, fromMask.width, toMask.width),+ height: easeInOutCubic(value, fromMask.height, toMask.height),});surface.setMargin(- value.spacing(marginFrom, margin, value.easeInOutCubic()),+ spacingTween(marginFrom, margin, easeInOutCubic(value)),);- surface.opacity(TimeTween.clampRemap(0.3, 1, 0, 1, value.value));+ surface.opacity(clampRemap(0.3, 1, 0, 1, value));},() => surface.setMask(null),);@@ -78,7 +85,7 @@ export function showCircle(return chain(tween(target / 2000, value => {- mask.radius = value.easeInOutCubic(0, target);+ mask.radius = easeInOutCubic(value, 0, target);}),() => surface.setCircleMask(null),);diff --git a/src/animations/surfaceTransition.ts b/src/animations/surfaceTransition.tsindex 7f61edea..ecb2120b 100644--- a/src/animations/surfaceTransition.ts+++ b/src/animations/surfaceTransition.ts@@ -1,6 +1,12 @@-import {Surface} from '../components/Surface';-import {TimeTween} from './TimeTween';-import {tween} from './tween';+import {Surface} from '../components';+import {+ clampRemap,+ colorTween,+ easeInOutCubic,+ easeInOutQuint,+ rectArcTween,+ tween,+} from '../tweening';import {decorate, threadable} from '../decorators';export interface SurfaceTransitionConfig {@@ -8,13 +14,13 @@ export interface SurfaceTransitionConfig {onSurfaceChange?: (surface: Surface) => void;onFromOpacityChange?: (surface: Surface,- value: TimeTween,- relativeValue: TimeTween,+ value: number,+ relativeValue: number,) => boolean | void;onToOpacityChange?: (surface: Surface,- value: TimeTween,- relativeValue: TimeTween,+ value: number,+ relativeValue: number,) => boolean | void;transitionTime?: number;}@@ -39,7 +45,7 @@ export function surfaceTransition(fromSurfaceOriginal: Surface) {const toPos = target.getPosition();const fromPos = fromSurface.getPosition();- const relativeValue = new TimeTween(0);+ let relativeValue = 0;const fromDelta = fromSurface.getOriginDelta(target.getOrigin());const fromNewPos = {x: fromPos.x + fromDelta.x,@@ -57,14 +63,8 @@ export function surfaceTransition(fromSurfaceOriginal: Surface) {let check = true;yield* tween(0.6, value => {- if (value.value > transitionTime) {- relativeValue.value = TimeTween.clampRemap(- transitionTime,- 1,- 0,- 1,- value.value,- );+ if (value > transitionTime) {+ relativeValue = clampRemap(transitionTime, 1, 0, 1, value);if (check) {target.show();fromSurface.destroy();@@ -72,17 +72,24 @@ export function surfaceTransition(fromSurfaceOriginal: Surface) {target.setMask({...from,- ...value.rectArc(from, to, config.reverse),- radius: value.easeInOutCubic(from.radius, target.radius()),- color: value.color(+ ...rectArcTween(from, to, easeInOutQuint(value), config.reverse),+ radius: easeInOutCubic(value, from.radius, target.radius()),+ color: colorTween(from.color,target.background(),- value.easeInOutQuint(),+ easeInOutQuint(value),),});- target.setPosition(value.rectArc(fromNewPos, toPos, config.reverse));+ target.setPosition(+ rectArcTween(+ fromNewPos,+ toPos,+ easeInOutQuint(value),+ config.reverse,+ ),+ );if (!config.onToOpacityChange?.(target, value, relativeValue)) {- target.getChild().opacity(relativeValue.value);+ target.getChild().opacity(relativeValue);}if (check) {@@ -90,29 +97,28 @@ export function surfaceTransition(fromSurfaceOriginal: Surface) {check = false;}} else {- relativeValue.value = TimeTween.clampRemap(- 0,- transitionTime,- 1,- 0,- value.value,- );+ relativeValue = clampRemap(0, transitionTime, 1, 0, value);fromSurface.setMask({...from,- ...value.rectArc(from, to, config.reverse),- radius: value.easeInOutCubic(from.radius, target.radius()),- color: value.color(+ ...rectArcTween(from, to, easeInOutQuint(value), config.reverse),+ radius: easeInOutCubic(value, from.radius, target.radius()),+ color: colorTween(from.color,target.background(),- value.easeInOutQuint(),+ easeInOutQuint(value),),});fromSurface.setPosition(- value.rectArc(fromPos, toNewPos, config.reverse),+ rectArcTween(+ fromPos,+ toNewPos,+ easeInOutQuint(value),+ config.reverse,+ ),);if (!config.onFromOpacityChange?.(target, value, relativeValue)) {- fromSurface.getChild().opacity(relativeValue.value);+ fromSurface.getChild().opacity(relativeValue);}}});diff --git a/src/animations/tween.ts b/src/animations/tween.tsdeleted file mode 100644index cf95dc91..00000000--- a/src/animations/tween.ts+++ /dev/null@@ -1,24 +0,0 @@-import {TimeTween} from './TimeTween';-import {PROJECT, Project} from '../Project';-import {decorate, threadable} from "../decorators";--decorate(tween, threadable());-export function* tween(- duration: number,- onProgress: (value: TimeTween, time: number) => void,- onEnd?: (value: TimeTween, time: number) => void,-): Generator {- const project = (yield PROJECT) as Project;- const frames = project.secondsToFrames(duration);- let startFrame = project.frame;- const timeTween = new TimeTween(0);- while (project.frame - startFrame < frames) {- const time = project.framesToSeconds(project.frame - startFrame);- timeTween.value = (project.frame - startFrame) / frames;- onProgress(timeTween, time);- yield;- }- timeTween.value = 1;- onProgress(timeTween, project.framesToSeconds(frames));- onEnd?.(timeTween, project.framesToSeconds(frames));-}diff --git a/src/components/Arrow.ts b/src/components/Arrow.tsindex 054dc0bc..fa4f3cf5 100644--- a/src/components/Arrow.ts+++ b/src/components/Arrow.ts@@ -242,7 +242,8 @@ export class Arrow extends Shape<ArrowConfig> {if (this.attrs.startArrow && firstPoint && arrowScale > 0.0001) {this.drawArrow(context, firstPoint, firstTangent, arrowScale);}-+ context.closePath();+ this.fill(this.stroke());context.fillShape(this);}@@ -361,17 +362,8 @@ export class Arrow extends Shape<ArrowConfig> {this.dirty = true;}- getWidth() {- const points = (<number[]>this.points()).filter(- (value, index) => index % 2 === 1,- );- return Math.max(...points) - Math.min(...points);- }- getHeight() {- const points = (<number[]>this.points()).filter(- (value, index) => index % 2 === 0,- );- return Math.max(...points) - Math.min(...points);+ public getArrowSize(): number {+ return this.attrs.arrowSize ?? this.strokeWidth() * 2;}radius: GetSet<number, this>;diff --git a/src/components/ColorPicker.tsx b/src/components/ColorPicker.tsxindex d1a22c3f..2addbaa8 100644--- a/src/components/ColorPicker.tsx+++ b/src/components/ColorPicker.tsx@@ -1,13 +1,13 @@import {LinearLayout, LinearLayoutConfig} from './LinearLayout';import {Rect} from 'konva/lib/shapes/Rect';import {Range, RangeConfig} from './Range';-import {AnimatedGetSet, getset, KonvaNode} from '../decorators';+import {getset, KonvaNode} from '../decorators';import {parseColor} from 'mix-color';-import {TimeTween} from '../animations';import {Surface} from './Surface';import {Origin} from '../types';import {Style} from '../styles';import {GetSet} from 'konva/lib/types';+import {clampRemap} from '../tweening';export interface ColorPickerConfig extends LinearLayoutConfig {previewColor?: string;@@ -29,9 +29,9 @@ export class ColorPicker extends Surface {@getset(null)public style: GetSet<ColorPickerConfig['style'], this>;@getset('#000000', ColorPicker.prototype.updateColor)- public previewColor: AnimatedGetSet<ColorPickerConfig['previewColor'], this>;+ public previewColor: GetSet<ColorPickerConfig['previewColor'], this>;@getset(0, ColorPicker.prototype.updateDissolve)- public dissolve: AnimatedGetSet<ColorPickerConfig['dissolve'], this>;+ public dissolve: GetSet<ColorPickerConfig['dissolve'], this>;public readonly preview: Rect;public readonly r: Range;@@ -99,7 +99,7 @@ export class ColorPicker extends Surface {private updateDissolve() {if (!this.r) return;- const opacity = TimeTween.clampRemap(0, 0.5, 1, 0, this.dissolve());+ const opacity = clampRemap(0, 0.5, 1, 0, this.dissolve());this.r.opacity(opacity);this.g.opacity(opacity);this.b.opacity(opacity);diff --git a/src/components/Connection.ts b/src/components/Connection.tsindex b05efa58..7073bcba 100644--- a/src/components/Connection.ts+++ b/src/components/Connection.ts@@ -1,25 +1,17 @@-import {Arrow, ArrowConfig} from './Arrow';import {Node} from 'konva/lib/Node';-import {_registerNode} from 'konva/lib/Global';-import {Factory} from 'konva/lib/Factory';-import {GetSet, Vector2d} from 'konva/lib/types';-import {Direction} from '../types';-import {Context} from 'konva/lib/Context';-import {TimeTween} from '../animations';-import {Project} from '../Project';-import {LAYOUT_CHANGE_EVENT} from "./ILayoutNode";--export interface ConnectionPoint {- node: Node;- direction: Direction;- offset: number;- vertical?: boolean;-}--export interface ConnectionConfig extends ArrowConfig {- from: ConnectionPoint;- to: ConnectionPoint;- crossing: Vector2d;+import {Center} from '../types';+import {KonvaNode} from '../decorators';+import {Pin, PIN_CHANGE_EVENT} from './Pin';+import {Group} from 'konva/lib/Group';+import {ContainerConfig} from 'konva/lib/Container';+import {Arrow} from './Arrow';+import {map} from '../tweening';++export interface ConnectionConfig extends ContainerConfig {+ start?: Pin;+ end?: Pin;+ crossing?: Node;+ arrow?: Arrow;}interface Measurement {@@ -28,6 +20,7 @@ interface Measurement {rangeOffset: [number, number];from: number;to: number;+ preferNegative: boolean;}function clamp(value: number, min: number, max: number): number {@@ -35,16 +28,37 @@ function clamp(value: number, min: number, max: number): number {return value < min ? min : value > max ? max : value;}-export class Connection extends Arrow {- private nodeCache: Record<string, Node> = {};- private markAsDirtyCallback: () => void;-- public get project(): Project {- return <Project>this.getStage();- }+@KonvaNode()+export class Connection extends Group {+ public readonly start: Pin;+ public readonly end: Pin;+ public readonly crossing: Node = null;+ public readonly arrow: Arrow;constructor(config?: ConnectionConfig) {super(config);++ this.start = config?.start ?? new Pin();+ this.start.on(PIN_CHANGE_EVENT, () => this.recalculate());+ if (!this.start.getParent()) {+ this.add(this.start);+ }++ this.end = config?.end ?? new Pin();+ this.end.on(PIN_CHANGE_EVENT, () => this.recalculate());+ if (!this.end.getParent()) {+ this.add(this.end);+ }++ if (config?.crossing) {+ this.crossing = config.crossing;+ this.crossing.on('absoluteTransformChange', () => this.recalculate());+ }++ this.arrow = config?.arrow ?? new Arrow();+ if (!this.arrow.getParent()) {+ this.add(this.arrow);+ }}private static measurePosition(@@ -53,25 +67,48 @@ export class Connection extends Arrow {positionB: number,sizeB: number,): Measurement {+ // FIXME use layout margin+ const padding = 20;+ const length = 20;+ const offset = (padding + length) * 2;++ let preferNegative = false;let direction: -1 | 0 | 1;let range: [number, number];let rangeOffset: [number, number];- if (positionA - sizeA - 80 > positionB + sizeB) {+ if (positionA - sizeA - offset > positionB + sizeB) {direction = -1;- range = [positionA - sizeA - 20, positionB + sizeB + 20];- rangeOffset = [range[0] - 20, range[1] + 20];- } else if (positionA + sizeA + 80 < positionB - sizeB) {+ range = [positionA - sizeA - padding, positionB + sizeB + padding];+ rangeOffset = [range[0] - length, range[1] + length];+ } else if (positionA + sizeA + offset < positionB - sizeB) {direction = 1;- range = [positionA + sizeA + 20, positionB - sizeB - 20];- rangeOffset = [range[0] + 20, range[1] - 20];+ range = [positionA + sizeA + padding, positionB - sizeB - padding];+ rangeOffset = [range[0] + length, range[1] - length];} else {direction = 0;- range = [positionA - sizeA - 20, positionB - sizeB - 20];- rangeOffset = [range[0] - 20, range[1] - 20];++ if (+ Math.abs(positionA + sizeA - positionB - sizeB) >+ Math.abs(positionA - sizeA - positionB + sizeB)+ ) {+ range = [positionA - sizeA - padding, positionB - sizeB - padding];+ rangeOffset = [range[0] - length, range[1] - length];+ } else {+ preferNegative = true;+ range = [positionA + sizeA + padding, positionB + sizeB + padding];+ rangeOffset = [range[0] + length, range[1] + length];+ }}- return {direction, range, rangeOffset, from: positionA, to: positionB};+ return {+ direction,+ range,+ rangeOffset,+ from: positionA,+ to: positionB,+ preferNegative,+ };}private static calculateCrossing(@@ -88,45 +125,41 @@ export class Connection extends Arrow {);}- return measurement.direction === 0- ? Math.min(- measurement.rangeOffset[0],- measurement.rangeOffset[1],- clampedCrossing,- )- : fractionX- ? TimeTween.map(- measurement.rangeOffset[0],- measurement.rangeOffset[1],- crossing,- )- : clampedCrossing;- }-- _sceneFunc(context: Context) {- if (this.dirty) {- this.recalculate();+ if (measurement.direction === 0) {+ return measurement.preferNegative+ ? Math.max(+ measurement.rangeOffset[0],+ measurement.rangeOffset[1],+ clampedCrossing,+ )+ : Math.min(+ measurement.rangeOffset[0],+ measurement.rangeOffset[1],+ clampedCrossing,+ );}- super._sceneFunc(context);+ return fractionX+ ? map(measurement.rangeOffset[0], measurement.rangeOffset[1], crossing)+ : clampedCrossing;}private recalculate() {- const from: ConnectionPoint = this.from();- const to: ConnectionPoint = this.to();- const crossing = this.crossing();-- if (!from.node || !to.node) {- this.points([]);+ if (!this.start || !this.end || !this.arrow) {+ this.arrow?.points([]);return;}- const fromRect = from.node.getClientRect({relativeTo: this.getLayer()});+ const crossing = this.crossing+ ? this.crossing.getAbsolutePosition(this.getLayer())+ : {x: 0.5, y: 0.5};++ const fromRect = this.start.getClientRect({relativeTo: this.getLayer()});fromRect.width /= 2;fromRect.height /= 2;fromRect.x += fromRect.width;fromRect.y += fromRect.height;- const toRect = to.node.getClientRect({relativeTo: this.getLayer()});+ const toRect = this.end.getClientRect({relativeTo: this.getLayer()});toRect.width /= 2;toRect.height /= 2;@@ -147,23 +180,27 @@ export class Connection extends Arrow {toRect.height,);- if (from.vertical) {+ if (this.start.direction() === Center.Vertical) {points.push(fromRect.x, vertical.range[0]);} else {points.push(horizontal.range[0], fromRect.y);}- let toVertical = to.vertical;- if (- from.vertical !== toVertical &&- (horizontal.direction === 0 || vertical.direction === 0)- ) {- toVertical = from.vertical;+ let endDirection = this.end.direction();+ if (this.start.direction() !== endDirection) {+ if (endDirection === Center.Vertical && vertical.direction === 0) {+ endDirection = this.start.direction();+ } else if (+ endDirection === Center.Horizontal &&+ horizontal.direction === 0+ ) {+ endDirection = this.start.direction();+ }}let distance = 100;- if (from.vertical === toVertical) {- if (from.vertical) {+ if (this.start.direction() === endDirection) {+ if (endDirection === Center.Vertical) {distance = Math.abs(toRect.x - fromRect.x);if (distance >= 1) {const y = Connection.calculateCrossing(crossing.y, vertical);@@ -179,80 +216,20 @@ export class Connection extends Arrow {}}} else {- if (from.vertical) {- points.push(fromRect.x, toRect.y);- } else {+ if (endDirection === Center.Vertical) {points.push(toRect.x, fromRect.y);+ } else {+ points.push(fromRect.x, toRect.y);}}- if (toVertical) {+ if (endDirection === Center.Vertical) {points.push(toRect.x, vertical.range[1]);} else {points.push(horizontal.range[1], toRect.y);}- this.radius(Math.min(8, distance / 2));- this.points(points);+ this.arrow.radius(Math.min(8, distance / 2));+ this.arrow.points(points);}-- public nodeChanged(name: string, node: Node) {- this.nodeCache ??= {};- this.markAsDirtyCallback ??= () => this.markAsDirty();-- if (this.nodeCache[name] === node) return;-- this.nodeCache[name]- ?.off('absoluteTransformChange', this.markAsDirtyCallback)- .off(LAYOUT_CHANGE_EVENT, this.markAsDirtyCallback);- this.nodeCache[name] = node;- this.nodeCache[name]- ?.on('absoluteTransformChange', this.markAsDirtyCallback)- .on(LAYOUT_CHANGE_EVENT, this.markAsDirtyCallback);- this.markAsDirty();- }-- from: GetSet<ConnectionPoint, this>;- to: GetSet<ConnectionPoint, this>;- crossing: GetSet<Vector2d, this>;}--Connection.prototype.className = 'Connection';-Connection.prototype._attrsAffectingSize = ['from', 'to'];--_registerNode(Arrow);--Factory.addGetterSetter(- Connection,- 'from',- {- node: null,- direction: Direction.Right,- offset: 0,- },- undefined,- function (this: Connection) {- this.nodeChanged('from', this.from().node);- },-);--Factory.addGetterSetter(- Connection,- 'to',- {- node: null,- direction: Direction.Right,- offset: 0,- },- undefined,- function (this: Connection) {- this.nodeChanged('to', this.to().node);- },-);-Factory.addGetterSetter(- Connection,- 'crossing',- {x: 0, y: 0},- undefined,- Connection.prototype.markAsDirty,-);diff --git a/src/components/LayoutGroup.ts b/src/components/LayoutGroup.tsindex f376f524..7806f299 100644--- a/src/components/LayoutGroup.ts+++ b/src/components/LayoutGroup.ts@@ -9,7 +9,7 @@ import {isInsideLayout,LAYOUT_CHANGE_EVENT,LayoutAttrs,-} from '../components/ILayoutNode';+} from './ILayoutNode';import {Node} from 'konva/lib/Node';export type LayoutGroupConfig = Partial<LayoutAttrs> & ContainerConfig;diff --git a/src/components/LayoutText.ts b/src/components/LayoutText.tsindex f556414b..d842fd7c 100644--- a/src/components/LayoutText.ts+++ b/src/components/LayoutText.ts@@ -10,7 +10,7 @@ import {LayoutAttrs,} from './ILayoutNode';import {Origin, Size, PossibleSpacing, Spacing} from '../types';-import {tween} from "../animations";+import {easeInOutCubic, tween, textTween} from '../tweening';export interface LayoutTextConfig extends Partial<LayoutAttrs>, TextConfig {minWidth?: number;@@ -43,7 +43,7 @@ export class LayoutText extends Text implements ILayoutNode {return {width: Math.max(custom?.minWidth ?? this.getMinWidth(),- this.overrideWidth ?? (size.width + padding.x),+ this.overrideWidth ?? size.width + padding.x,),height: (this.isConstructed ? this.getHeight() : 0) + padding.y,};@@ -126,8 +126,8 @@ export class LayoutText extends Text implements ILayoutNode {this.overrideWidth = fromWidth;yield* tween(0.3, value => {- this.overrideWidth = value.easeInOutCubic(fromWidth, toWidth);- this.setText(value.text(fromText, text, value.easeInOutCubic()));+ this.overrideWidth = easeInOutCubic(value, fromWidth, toWidth);+ this.setText(textTween(fromText, text, easeInOutCubic(value)));});this.overrideWidth = null;diff --git a/src/components/Pin.ts b/src/components/Pin.tsnew file mode 100644index 00000000..b30b4bcd--- /dev/null+++ b/src/components/Pin.ts@@ -0,0 +1,80 @@+import {Group} from 'konva/lib/Group';+import {Container, ContainerConfig} from 'konva/lib/Container';+import {Center, flipOrigin, Origin} from '../types';+import {GetSet, IRect} from 'konva/lib/types';+import {getset, KonvaNode} from '../decorators';+import {getOriginDelta, LAYOUT_CHANGE_EVENT, LayoutNode} from './ILayoutNode';+import {Node} from 'konva/lib/Node';+import {bind} from '../decorators/bind';++export interface PinConfig extends ContainerConfig {+ target?: Node;+ attach?: LayoutNode;+ direction?: Center;+}++export const PIN_CHANGE_EVENT = 'pinChange';++@KonvaNode()+export class Pin extends Group {+ @getset(null, Pin.prototype.firePinChangeEvent)+ public target: GetSet<PinConfig['target'], this>;+ @getset(null)+ public attach: GetSet<PinConfig['attach'], this>;+ @getset()+ public direction: GetSet<PinConfig['direction'], this>;++ public constructor(config?: PinConfig) {+ super(config);+ this.on('absoluteTransformChange', this.firePinChangeEvent);+ }++ public getDirection(): Center {+ return (+ this.attrs.direction ??+ (this.attach() ? Center.Vertical : Center.Horizontal)+ );+ }++ public destroy(): this {+ this.attrs.target?.off('absoluteTransformChange', this.firePinChangeEvent);+ this.attrs.target?.off(LAYOUT_CHANGE_EVENT, this.firePinChangeEvent);+ return super.destroy();+ }++ public setTarget(value: Node): this {+ this.attrs.target?.off('absoluteTransformChange', this.firePinChangeEvent);+ this.attrs.target?.off(LAYOUT_CHANGE_EVENT, this.firePinChangeEvent);+ this.attrs.target = value;+ this.attrs.target?.on('absoluteTransformChange', this.firePinChangeEvent);+ this.attrs.target?.on(LAYOUT_CHANGE_EVENT, this.firePinChangeEvent);+ this.firePinChangeEvent();++ return this;+ }++ @bind()+ private firePinChangeEvent() {+ const attach = this.attach();+ if (attach) {+ const attachDirection = flipOrigin(attach.getOrigin(), this.direction());+ const rect = this.getClientRect({relativeTo: attach.getLayer()});+ const offset = getOriginDelta(rect, Origin.TopLeft, attachDirection);+ attach.position({+ x: rect.x + offset.x,+ y: rect.y + offset.y,+ });+ }++ this.fire(PIN_CHANGE_EVENT, undefined, true);+ }++ public getClientRect(config?: {+ skipTransform?: boolean;+ skipShadow?: boolean;+ skipStroke?: boolean;+ relativeTo?: Container;+ }): IRect {+ return this.target()?.getClientRect(config) ?? super.getClientRect(config);+ }+}diff --git a/src/components/Range.ts b/src/components/Range.tsindex 9d5bf111..4e2d64e2 100644--- a/src/components/Range.ts+++ b/src/components/Range.ts@@ -1,10 +1,10 @@import {LayoutShape, LayoutShapeConfig} from './LayoutShape';import {Context} from 'konva/lib/Context';-import {AnimatedGetSet, getset, KonvaNode} from '../decorators';+import {getset, KonvaNode} from '../decorators';import {CanvasHelper} from '../helpers';-import {TimeTween} from '../animations';-import {GetSet} from "konva/lib/types";-import {getFontColor, getStyle, Style} from "../styles";+import {GetSet} from 'konva/lib/types';+import {getFontColor, getStyle, Style} from '../styles';+import {remap} from '../tweening';export interface RangeConfig extends LayoutShapeConfig {range?: [number, number];@@ -19,13 +19,13 @@ export class Range extends LayoutShape {@getset(null)public style: GetSet<RangeConfig['style'], this>;@getset([0, 1])- public range: AnimatedGetSet<RangeConfig['range'], this>;+ public range: GetSet<RangeConfig['range'], this>;@getset(0.5)- public value: AnimatedGetSet<RangeConfig['value'], this>;+ public value: GetSet<RangeConfig['value'], this>;@getset(0)- public precision: AnimatedGetSet<RangeConfig['precision'], this>;+ public precision: GetSet<RangeConfig['precision'], this>;@getset(null)- public label: AnimatedGetSet<RangeConfig['label'], this>;+ public label: GetSet<RangeConfig['label'], this>;public constructor(config?: RangeConfig) {super(config);@@ -52,7 +52,7 @@ export class Range extends LayoutShape {const position = {x: size.width / -2,y: size.height / -2,- }+ };if (label) {position.x += 60;@@ -73,16 +73,15 @@ export class Range extends LayoutShape {ctx.font = style.bodyFont;const textSize = ctx.measureText(minText);- const width = TimeTween.remap(range[0], range[1], textSize.width + 40, size.width, value);- ctx.fillStyle = style.foreground;- CanvasHelper.roundRect(- ctx,- position.x,- position.y,- width,- size.height,- 8,+ const width = remap(+ range[0],+ range[1],+ textSize.width + 40,+ size.width,+ value,);+ ctx.fillStyle = style.foreground;+ CanvasHelper.roundRect(ctx, position.x, position.y, width, size.height, 8);ctx.fill();ctx.font = style.bodyFont;diff --git a/src/components/Sprite.ts b/src/components/Sprite.tsindex ca4c12b1..a49f173a 100644--- a/src/components/Sprite.ts+++ b/src/components/Sprite.ts@@ -2,9 +2,10 @@ 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, TimeTween, waitFor} from '../animations';-import {AnimatedGetSet, getset, KonvaNode, threadable} from '../decorators';+import {cancel, waitFor} from '../animations';+import {getset, KonvaNode, threadable} from '../decorators';import {GeneratorHelper} from '../helpers';+import {map} from '../tweening';export interface SpriteData {fileName: string;@@ -37,9 +38,9 @@ export class Sprite extends LayoutShape {@getset(false)public playing: GetSet<SpriteConfig['playing'], this>;@getset(10)- public fps: AnimatedGetSet<SpriteConfig['fps'], this>;+ public fps: GetSet<SpriteConfig['fps'], this>;@getset(0, Sprite.prototype.recalculate)- public maskBlend: AnimatedGetSet<SpriteConfig['maskBlend'], this>;+ public maskBlend: GetSet<SpriteConfig['maskBlend'], this>;private frame: SpriteData = {height: 0,@@ -116,11 +117,7 @@ export class Sprite extends LayoutShape {);if (mask) {- this.imageData.data[id + 3] *= TimeTween.map(- 1,- mask.data[id] / 255,- blend,- );+ this.imageData.data[id + 3] *= map(1, mask.data[id] / 255, blend);}}}diff --git a/src/components/Surface.ts b/src/components/Surface.tsindex bc634629..7e4eb518 100644--- a/src/components/Surface.ts+++ b/src/components/Surface.ts@@ -11,7 +11,7 @@ import {} from './ILayoutNode';import {CanvasHelper} from '../helpers';import {Context} from 'konva/lib/Context';-import {tween} from '../animations';+import {easeOutExpo, linear, tween} from '../tweening';import {GetSet, IRect} from 'konva/lib/types';import {getset, threadable} from '../decorators';import {Node} from 'konva/lib/Node';@@ -38,9 +38,9 @@ export interface SurfaceConfig extends LayoutGroupConfig {}export class Surface extends LayoutGroup {- @getset(0, Surface.prototype.handleLayoutChange)+ @getset(0, Surface.prototype.updateBackground)public radius: GetSet<SurfaceConfig['radius'], this>;- @getset('#FF00FF', Surface.prototype.handleLayoutChange)+ @getset('#FF00FF', Surface.prototype.updateBackground)public background: GetSet<SurfaceConfig['background'], this>;@getset(null)public child: GetSet<SurfaceConfig['child'], this>;@@ -74,7 +74,9 @@ export class Surface extends LayoutGroup {public setChild(value: LayoutNode): this {this.attrs.child?.remove();this.attrs.child = value;- this.add(value);+ if (value) {+ this.add(value);+ }this.handleLayoutChange();return this;@@ -94,8 +96,10 @@ export class Surface extends LayoutGroup {}public clone(obj?: any): this {- const clone: this = Node.prototype.clone.call(this, obj);const child = this.child();+ this.child(null);+ const clone: this = Node.prototype.clone.call(this, obj);+ this.child(child);if (child) {clone.setChild(child.clone());}@@ -129,9 +133,9 @@ export class Surface extends LayoutGroup {.fill(`rgba(${opaque.r}, ${opaque.g}, ${opaque.b}, ${0.5})`);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.radius() + value.easeOutExpo(0, 50);+ const width = this.layoutData.width + easeOutExpo(value, 0, 100);+ const height = this.layoutData.height + easeOutExpo(value, 0, 100);+ const radius = this.radius() + easeOutExpo(value, 0, 50);this.ripple.offsetX(width / 2)@@ -140,7 +144,8 @@ export class Surface extends LayoutGroup {.height(height).cornerRadius(radius).fill(- `rgba(${opaque.r}, ${opaque.g}, ${opaque.b}, ${value.linear(+ `rgba(${opaque.r}, ${opaque.g}, ${opaque.b}, ${linear(+ value,0.5,0,)})`,@@ -217,21 +222,25 @@ export class Surface extends LayoutGroup {});}+ this.updateBox();this.updateBackground();this.setOrigin(this.getOrigin());this.fireLayoutChange();}- private updateBackground() {+ private updateBox() {if (!this.box) return;const size = this.getLayoutSize();this.box.offsetX(size.width / 2).offsetY(size.height / 2).width(size.width)- .height(size.height)- .cornerRadius(this.radius())- .fill(this.background());+ .height(size.height);+ }++ private updateBackground() {+ if (this.surfaceMask || !this.box) return;+ this.box.cornerRadius(this.radius()).fill(this.background());}private drawMask(ctx: Context) {diff --git a/src/decorators/bind.ts b/src/decorators/bind.tsnew file mode 100644index 00000000..2c76d0d4--- /dev/null+++ b/src/decorators/bind.ts@@ -0,0 +1,17 @@+export function bind(): MethodDecorator {+ return <T>(+ target: Object,+ propertyKey: string | symbol,+ descriptor: TypedPropertyDescriptor<T>,+ ): TypedPropertyDescriptor<T> | void => {+ const name = `__binded${propertyKey.toString()}`;+ const fn = <Function>(<unknown>descriptor.value);++ return {+ get() {+ this[name] ??= fn.bind(this);+ return this[name];+ },+ };+ };+}diff --git a/src/decorators/getset.ts b/src/decorators/getset.tsindex 0cae5df0..d2d77336 100644--- a/src/decorators/getset.ts+++ b/src/decorators/getset.ts@@ -1,83 +1,10 @@import {Factory} from 'konva/lib/Factory';-import {Util} from 'konva/lib/Util';-import {tween} from '../animations';-import {Spacing} from '../types';--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.addGetter(target.constructor, propertyKey, defaultValue);- addSetter(target.constructor, <string>propertyKey, after);- addOverloadedGetterSetter(target.constructor, <string>propertyKey);+ Factory.addGetterSetter(target.constructor, propertyKey, defaultValue, undefined, after);};-}--export interface AnimatedGetSet<Type, This> {- (): Type;- (value: Type): This;- (value: Type, time: number): Generator;-}+}\ No newline at end of filediff --git a/src/global.d.ts b/src/global.d.tsindex f246c44f..300b3af7 100644--- a/src/global.d.ts+++ b/src/global.d.ts@@ -1,19 +1,19 @@-declare module "*.png" {+declare module '*.png' {const value: import('./components/Sprite').SpriteData;export = value;}-declare module "*.glsl" {+declare module '*.glsl' {const value: string;export = value;}-declare module "*.label" {+declare module '*.label' {const value: Record<string, number>;export = value;}-declare module "*.anim" {+declare module '*.anim' {const value: import('./components/Sprite').SpriteData[];export = value;-}\ No newline at end of file+}diff --git a/src/patches/Factory.ts b/src/patches/Factory.tsnew file mode 100644index 00000000..5a97d478--- /dev/null+++ b/src/patches/Factory.ts@@ -0,0 +1,50 @@+import {Factory} from 'konva/lib/Factory';+import {ANIMATE} from '../symbols';+import type {Node} from 'konva/lib/Node';+import {Animator} from '../tweening/Animator';++declare module 'konva/lib/types' {+ export interface GetSet<Type, This extends Node> {+ (): Type;+ (value: Type): This;+ (value: typeof ANIMATE): Animator<Type, This>;+ (value: Type, time: number): Generator;+ }+}++Factory.overWriteSetter = function overWriteSetter(+ constructor: Function,+ attr: string,+ validator?: any,+ after?: () => void,+) {+ const name = attr.charAt(0).toUpperCase() + attr.slice(1);+ const setter = `set${name}`;+ constructor.prototype[setter] = function (val: any, time?: any) {+ if (val === ANIMATE) {+ return new Animator(this, attr);+ }++ if (time !== undefined) {+ return new Animator(this, attr).key(val, time).run();+ }++ this._setAttr(attr, val);+ after?.call(this);++ return this;+ };+};++Factory.addOverloadedGetterSetter = function addOverloadedGetterSetter(+ constructor: Function,+ attr: string,+) {+ const capitalizedAttr = attr.charAt(0).toUpperCase() + attr.slice(1);+ const setter = 'set' + capitalizedAttr;+ const getter = 'get' + capitalizedAttr;++ constructor.prototype[attr] = function (...args: any[]) {+ return args.length ? this[setter](...args) : this[getter]();+ };+};diff --git a/src/patches/Node.ts b/src/patches/Node.tsnew file mode 100644index 00000000..7a675a7b--- /dev/null+++ b/src/patches/Node.ts@@ -0,0 +1,25 @@+import {Node} from 'konva/lib/Node';+import {Vector2d} from 'konva/lib/types';+import {Animator} from '../tweening/Animator';+import {ANIMATE} from '../symbols';++const oldPosition = Node.prototype.position;+function patchedPosition(): Vector2d;+function patchedPosition(value: Vector2d): Node;+function patchedPosition(value: typeof ANIMATE): Animator<Vector2d, Node>;+function patchedPosition(value: Vector2d, time: number): Generator;+function patchedPosition(+ value?: Vector2d | typeof ANIMATE,+ time?: number,+): Node | Vector2d | Animator<Vector2d, Node> | Generator {+ if (value === ANIMATE) {+ return new Animator<Vector2d, Node>(this, 'position');+ }+ if (time !== undefined) {+ return new Animator<Vector2d, Node>(this, 'position')+ .key(value, time)+ .run();+ }+ return oldPosition.call(this, value);+}+Node.prototype.position = patchedPosition;diff --git a/src/patches/index.ts b/src/patches/index.tsnew file mode 100644index 00000000..83e15cb3--- /dev/null+++ b/src/patches/index.ts@@ -0,0 +1,2 @@+import './Factory';+import './Node';\ No newline at end of filediff --git a/src/symbols.ts b/src/symbols.tsnew file mode 100644index 00000000..d8121eee--- /dev/null+++ b/src/symbols.ts@@ -0,0 +1,2 @@+export const ANIMATE = Symbol('ANIMATE');+export const PROJECT = Symbol('PROJECT');diff --git a/src/tweening/Animator.ts b/src/tweening/Animator.tsnew file mode 100644index 00000000..66648b0c--- /dev/null+++ b/src/tweening/Animator.ts@@ -0,0 +1,135 @@+import type {Node} from 'konva/lib/Node';+import {+ colorTween,+ easeInOutCubic,+ InterpolationFunction,+ map,+ rectArcTween,+ spacingTween,+ textTween,+ tween,+ TweenFunction,+ vector2dTween,+} from './index';+import {threadable} from '../decorators';+import {waitFor, waitUntil} from '../animations';++export class Animator<Type, This extends Node> {+ private valueFrom: Type = null;+ private keys: (() => Generator)[] = [];+ private mapper: TweenFunction<any> = map;+ private loops: number = 1;+ private readonly setter: string;+ private readonly getter: string;++ public constructor(+ private readonly object: This,+ private readonly prop: string,+ ) {+ const name = this.prop.charAt(0).toUpperCase() + this.prop.slice(1);+ this.getter = `get${name}`;+ this.setter = `set${name}`;+ }++ public from(value: Type): this {+ this.valueFrom = value;+ return this;+ }++ public key<Rest extends any[]>(+ value: Type,+ time: number,+ interpolation: InterpolationFunction = easeInOutCubic,+ mapper?: TweenFunction<Type, Rest>,+ ...args: Rest+ ): this {+ this.keys.push(() =>+ tween(+ time,+ v => {+ // @ts-ignore+ this.object[this.setter](+ mapper === undefined+ ? this.mapper(this.valueFrom, value, interpolation(v))+ : mapper(this.valueFrom, value, interpolation(v), ...args),+ );+ },+ () => {+ this.valueFrom = value;+ },+ ),+ );++ return this;+ }++ public back<Rest extends any[]>(+ time: number,+ interpolation: InterpolationFunction = easeInOutCubic,+ mapper?: TweenFunction<Type, Rest>,+ ...args: Rest+ ): this {+ return this.key(this.getValueFrom(), time, interpolation, mapper, ...args);+ }++ public waitFor(time: number): this {+ this.keys.push(() => waitFor(time));+ return this;+ }++ public waitUntil(time: number): this {+ this.keys.push(() => waitUntil(time));+ return this;+ }++ public run(loops = 1): Generator {+ this.loops = loops;+ if (this.valueFrom !== null) {+ //@ts-ignore+ this.object[this.setter](this.valueFrom);+ }+ this.inferProperties();+ return this.runner();+ }++ @threadable('animatorRunner')+ private *runner() {+ for (let loop = 0; loop < this.loops; loop++) {+ for (let i = 0; i < this.keys.length; i++) {+ yield* this.keys[i]();+ }+ }+ }++ private getValueFrom(): Type {+ if (this.valueFrom !== null) {+ return this.valueFrom;+ }++ if (this.getter in this.object) {+ //@ts-ignore+ return this.object[this.getter]();+ }+ }++ private inferProperties() {+ this.valueFrom ??= this.getValueFrom();++ if (typeof this.valueFrom === 'string') {+ if (this.valueFrom.startsWith('#') || this.valueFrom.startsWith('rgb')) {+ this.mapper = colorTween;+ } else {+ this.mapper = textTween;+ }+ } else if (typeof this.valueFrom === 'object') {+ if ('x' in this.valueFrom) {+ if ('width' in this.valueFrom) {+ this.mapper = rectArcTween;+ }+ this.mapper = vector2dTween;+ } else if ('left' in this.valueFrom) {+ this.mapper = spacingTween;+ }+ }+ }+}diff --git a/src/tweening/index.ts b/src/tweening/index.tsnew file mode 100644index 00000000..05bf8f71--- /dev/null+++ b/src/tweening/index.ts@@ -0,0 +1,3 @@+export * from './tween';+export * from './tweenFunctions';+export * from './interpolationFunctions';diff --git a/src/tweening/interpolationFunctions.ts b/src/tweening/interpolationFunctions.tsnew file mode 100644index 00000000..5126da16--- /dev/null+++ b/src/tweening/interpolationFunctions.ts@@ -0,0 +1,51 @@+import {map, remap} from './tweenFunctions';++export interface InterpolationFunction {+ (value: number, from?: number, to?: number): number;+}++export function easeInOutCirc(value: number, from = 0, to = 1) {+ value =+ value < 0.5+ ? (1 - Math.sqrt(1 - Math.pow(2 * value, 2))) / 2+ : (Math.sqrt(1 - Math.pow(-2 * value + 2, 2)) + 1) / 2;+ return map(from, to, value);+}++export function easeOutExpo(value: number, from = 0, to = 1) {+ value = value === 1 ? 1 : 1 - Math.pow(2, -10 * value);+ return map(from, to, value);+}++export function easeInExpo(value: number, from = 0, to = 1) {+ value = value === 0 ? 0 : Math.pow(2, 10 * value - 10);+ return map(from, to, value);+}++export function linear(value: number, from = 0, to = 1) {+ return map(from, to, value);+}++export function sin(value: number, from = 0, to = 1) {+ return remap(-1, 1, from, to, Math.sin(value));+}++export function cos(value: number, from = 0, to = 1) {+ return remap(-1, 1, from, to, Math.cos(value));+}++export function easeInOutCubic(value: number, from = 0, to = 1) {+ value =+ value < 0.5+ ? 4 * value * value * value+ : 1 - Math.pow(-2 * value + 2, 3) / 2;+ return map(from, to, value);+}++export function easeInOutQuint(value: number, from = 0, to = 1) {+ value =+ value < 0.5+ ? 16 * value * value * value * value * value+ : 1 - Math.pow(-2 * value + 2, 5) / 2;+ return map(from, to, value);+}diff --git a/src/tweening/tween.ts b/src/tweening/tween.tsnew file mode 100644index 00000000..7c0adf43--- /dev/null+++ b/src/tweening/tween.ts@@ -0,0 +1,24 @@+import {decorate, threadable} from '../decorators';+import type {Project} from '../Project';+import {PROJECT} from '../symbols';++decorate(tween, threadable());+export function* tween(+ duration: number,+ onProgress: (value: number, time: number) => void,+ onEnd?: (value: number, time: number) => void,+): Generator {+ const project = (yield PROJECT) as Project;+ const frames = project.secondsToFrames(duration);+ let startFrame = project.frame;+ let value = 0;+ while (project.frame - startFrame < frames) {+ const time = project.framesToSeconds(project.frame - startFrame);+ value = (project.frame - startFrame) / frames;+ onProgress(value, time);+ yield;+ }+ value = 1;+ onProgress(value, project.framesToSeconds(frames));+ onEnd?.(value, project.framesToSeconds(frames));+}diff --git a/src/tweening/tweenFunctions.ts b/src/tweening/tweenFunctions.tsnew file mode 100644index 00000000..f6baf421--- /dev/null+++ b/src/tweening/tweenFunctions.ts@@ -0,0 +1,116 @@+import mixColor from 'mix-color';+import {IRect, Vector2d} from 'konva/lib/types';+import {PossibleSpacing, Spacing} from '../types';++export interface TweenFunction<T, Rest extends any[] = any[]> {+ (from: T, to: T, value: number, ...args: Rest): T;+}++export function textTween(from: string, to: string, value: number) {+ // left to right+ if (to.length > from.length) {+ const current = Math.floor(to.length * value);+ const currentLength = Math.floor(map(from.length - 1, to.length, value));+ let text = '';+ for (let i = 0; i < to.length; i++) {+ if (i < current) {+ text += to[i];+ } else if (from[i] || i <= currentLength) {+ text += from[i] ?? to[i];+ }+ }++ return text;+ }+ // right to left+ else {+ const current = Math.round(from.length * (1 - value));+ const currentLength = Math.floor(map(from.length + 1, to.length, value));+ let text = [];+ for (let i = from.length - 1; i >= 0; i--) {+ if (i < current) {+ text.unshift(from[i]);+ } else if (to[i] || i < currentLength) {+ text.unshift(to[i] ?? from[i]);+ }+ }++ return text.join('');+ }+}++export function colorTween(from: string, to: string, value: number) {+ return mixColor(from, to, value);+}++export function vector2dTween(from: Vector2d, to: Vector2d, value: number) {+ return {+ x: map(from.x, to.x, value),+ y: map(from.y, to.y, value),+ };+}++export function spacingTween(+ from: Spacing,+ to: Spacing,+ value: number,+): PossibleSpacing {+ return [+ map(from.top, to.top, value),+ map(from.right, to.right, value),+ map(from.bottom, to.bottom, value),+ map(from.left, to.left, value),+ ];+}++export function rectArcTween(+ from: Partial<IRect>,+ to: Partial<IRect>,+ value: number,+ reverse?: boolean,+) {+ value = map(0, Math.PI / 2, value);+ let xValue = Math.sin(value);+ let yValue = 1 - Math.cos(value);+ if (reverse) {+ [xValue, yValue] = [yValue, xValue];+ }++ return {+ x: map(from.x ?? 0, to.x ?? 0, xValue),+ y: map(from.y ?? 0, to.y ?? 0, yValue),+ width: map(from.width ?? 0, to.width ?? 0, xValue),+ height: map(from.height ?? 0, to.height ?? 0, yValue),+ };+}++export function map(from: number, to: number, value: number) {+ return from + (to - from) * value;+}++export function remap(+ fromIn: number,+ toIn: number,+ fromOut: number,+ toOut: number,+ value: number,+) {+ return fromOut + ((value - fromIn) * (toOut - fromOut)) / (toIn - fromIn);+}++export function clampRemap(+ fromIn: number,+ toIn: number,+ fromOut: number,+ toOut: number,+ value: number,+) {+ const remappedValue = remap(fromIn, toIn, fromOut, toOut, value);+ if (fromOut > toOut) [fromOut, toOut] = [toOut, fromOut];++ return remappedValue < fromOut+ ? fromOut+ : remappedValue > toOut+ ? toOut+ : remappedValue;+}diff --git a/src/utils/follow.ts b/src/utils/follow.tsdeleted file mode 100644index 0d93a9b2..00000000--- a/src/utils/follow.ts+++ /dev/null@@ -1,40 +0,0 @@-import {Node} from 'konva/lib/Node';-import {Center, flipOrigin, Origin} from '../types';-import {getOriginDelta, isLayoutNode} from '../components/ILayoutNode';--export interface FollowSubscription {- dispose(): void;- target(newTarget: Node): void;-}--export function follow(- source: Node,- target: Node,- direction?: Origin,-): FollowSubscription {- direction ??= isLayoutNode(source)- ? flipOrigin(source.getOrigin(), Center.Vertical)- : Origin.TopLeft;-- const update = () => {- const rect = target.getClientRect({relativeTo: target.getLayer()});- const offset = getOriginDelta(rect, Origin.TopLeft, direction);- source.position({- x: rect.x + offset.x,- y: rect.y + offset.y,- });- };-- target.on('absoluteTransformChange', update);- update();-- return {- dispose: () => target.off('absoluteTransformChange', update),- target: (newTarget: Node) => {- target.off('absoluteTransformChange', update);- target = newTarget;- target.on('absoluteTransformChange', update);- update();- },- };-}diff --git a/src/utils/index.ts b/src/utils/index.tsindex 2cdf10d3..2d090d0c 100644--- a/src/utils/index.ts+++ b/src/utils/index.ts@@ -1,2 +1 @@-export * from './pop';-export * from './follow';\ No newline at end of file+export * from './pop';\ No newline at end of filediff --git a/tools/loaders/animation-loader.js b/tools/loaders/animation-loader.jsindex 969cd8e4..4f751b5f 100644--- a/tools/loaders/animation-loader.js+++ b/tools/loaders/animation-loader.js@@ -3,7 +3,7 @@ const {readdirSync} = require('fs');const loadImage = require('../utils/load-image');const nameRegex = /([^\d]*)\d+\.png$/;-module.exports = function () {+function loader () {const callback = this.async();const directoryPath = path.dirname(this.resourcePath);const files = readdirSync(directoryPath)@@ -15,7 +15,7 @@ module.exports = function () {loadAnimation(files).then(result => callback(null, result)).catch(error => callback(error));-};+}async function loadAnimation(files) {const frames = [];@@ -26,4 +26,4 @@ async function loadAnimation(files) {return `export default ${JSON.stringify(frames)};`;}-+module.exports = loader;diff --git a/tools/loaders/label-loader.js b/tools/loaders/label-loader.jsindex 7a686279..28a127ec 100644--- a/tools/loaders/label-loader.js+++ b/tools/loaders/label-loader.js@@ -1,4 +1,4 @@-module.exports = function (source) {+function loader(source) {const json = {};source.split(/\r?\n/).forEach(line => {if (!line) return;@@ -21,4 +21,6 @@ const proxy = new Proxy(json, {export default proxy;`;-};+}++module.exports = loader;\ No newline at end of filediff --git a/tools/loaders/sprite-loader.js b/tools/loaders/sprite-loader.jsindex 6ffab9da..153136ea 100644--- a/tools/loaders/sprite-loader.js+++ b/tools/loaders/sprite-loader.js@@ -1,8 +1,10 @@const loadImage = require('../utils/load-image');-module.exports = function () {+function loader() {const callback = this.async();loadImage(this.resourcePath).then(sprite => callback(null, `export default ${JSON.stringify(sprite)}`)).catch(error => callback(error));-};+}++module.exports = loader;