Visualize Your Ideas With Code
feat: better naming conventions (#62)
Jacoba9d764fbceb6
diff --git a/packages/core/src/transitions/slideTransition.ts b/packages/core/src/transitions/slideTransition.tsindex a698c04d..7c794beb 100644--- a/packages/core/src/transitions/slideTransition.ts+++ b/packages/core/src/transitions/slideTransition.ts@@ -1,5 +1,5 @@import {Direction, originPosition} from '../types';-import {easeInOutCubic, tween, deepTween} from '../tweening';+import {easeInOutCubic, tween, deepLerp} from '../tweening';import {useScene} from '../utils';import {useTransition} from './';@@ -15,13 +15,13 @@ export function slideTransition(direction: Direction = Direction.Top) {return tween(0.6,value => {- ppos = deepTween(+ ppos = deepLerp({x: 0, y: 0},{x: -position.x, y: -position.y},easeInOutCubic(value),);- cpos = deepTween(position, {x: 0, y: 0}, easeInOutCubic(value));+ cpos = deepLerp(position, {x: 0, y: 0}, easeInOutCubic(value));},endTransition,);diff --git a/packages/core/src/tweening/Animator.ts b/packages/core/src/tweening/Animator.tsindex 1ad0b521..156f44fa 100644--- a/packages/core/src/tweening/Animator.ts+++ b/packages/core/src/tweening/Animator.ts@@ -1,12 +1,12 @@import {- colorTween,+ colorLerp,easeInOutCubic,- InterpolationFunction,+ TimingFunction,map,- textTween,+ textLerp,tween,- TweenFunction,- deepTween,+ InterpolationFunction,+ deepLerp,} from './index';import {threadable} from '../decorators';import {waitFor, waitUntil} from '../flow';@@ -18,7 +18,7 @@ export interface TweenProvider<T> {from: T,to: T,time: number,- interpolation: InterpolationFunction,+ timingFunction: TimingFunction,onEnd: Callback,): ThreadGenerator;}@@ -27,7 +27,7 @@ export class Animator<Type, This> {private valueFrom: Type = null;private lastValue: Type;private keys: (() => ThreadGenerator)[] = [];- private tweenFunction: TweenFunction<any> = map;+ private interpolationFunction: InterpolationFunction<any> = map;private loops = 1;private readonly setter: string;private readonly getter: string;@@ -50,8 +50,8 @@ export class Animator<Type, This> {public key<Rest extends unknown[]>(value: Type,time: number,- interpolation: InterpolationFunction = easeInOutCubic,- mapper?: TweenFunction<Type, Rest>,+ timingFunction: TimingFunction = easeInOutCubic,+ interpolationFunction?: InterpolationFunction<Type, Rest>,...args: Rest): this {this.lastValue = value;@@ -62,7 +62,7 @@ export class Animator<Type, This> {this.valueFrom,value,time,- interpolation,+ timingFunction,() => (this.valueFrom = value),): tween(@@ -70,9 +70,18 @@ export class Animator<Type, This> {v => {// @ts-ignorethis.object[this.setter](- mapper === undefined- ? this.tweenFunction(this.valueFrom, value, interpolation(v))- : mapper(this.valueFrom, value, interpolation(v), ...args),+ interpolationFunction === undefined+ ? this.interpolationFunction(+ this.valueFrom,+ value,+ timingFunction(v),+ )+ : interpolationFunction(+ this.valueFrom,+ value,+ timingFunction(v),+ ...args,+ ),);},() => {@@ -95,8 +104,8 @@ export class Animator<Type, This> {public diff<Rest extends unknown[]>(value: Type,time: number,- interpolation: InterpolationFunction = easeInOutCubic,- mapper?: TweenFunction<Type, Rest>,+ timingFunction: TimingFunction = easeInOutCubic,+ interpolationFunction?: InterpolationFunction<Type, Rest>,...args: Rest): this {let next: any = value;@@ -112,16 +121,22 @@ export class Animator<Type, This> {next += last;}- return this.key(next, time, interpolation, mapper, ...args);+ return this.key(next, time, timingFunction, interpolationFunction, ...args);}public back<Rest extends unknown[]>(time: number,- interpolation: InterpolationFunction = easeInOutCubic,- mapper?: TweenFunction<Type, Rest>,+ timingFunction: TimingFunction = easeInOutCubic,+ interpolationFunction?: InterpolationFunction<Type, Rest>,...args: Rest): this {- return this.key(this.getValueFrom(), time, interpolation, mapper, ...args);+ return this.key(+ this.getValueFrom(),+ time,+ timingFunction,+ interpolationFunction,+ ...args,+ );}public waitFor(time: number): this {@@ -168,22 +183,26 @@ export class Animator<Type, This> {private inferProperties() {this.valueFrom ??= this.getValueFrom();- this.tweenFunction = Animator.inferTweenFunction(this.valueFrom);+ this.interpolationFunction = Animator.inferInterpolationFunction(+ this.valueFrom,+ );}- public static inferTweenFunction<T>(value: T): TweenFunction<T> {- let tween: TweenFunction<unknown> = map;+ public static inferInterpolationFunction<T>(+ value: T,+ ): InterpolationFunction<T> {+ let interpolationFunction: InterpolationFunction<unknown> = map;if (typeof value === 'string') {if (value.startsWith('#') || value.startsWith('rgb')) {- tween = colorTween;+ interpolationFunction = colorLerp;} else {- tween = textTween;+ interpolationFunction = textLerp;}} else if (value && typeof value === 'object') {- tween = deepTween;+ interpolationFunction = deepLerp;}- return tween as TweenFunction<T>;+ return interpolationFunction as InterpolationFunction<T>;}}diff --git a/packages/core/src/tweening/index.ts b/packages/core/src/tweening/index.tsindex 9e1c8c96..81ecf3bf 100644--- a/packages/core/src/tweening/index.ts+++ b/packages/core/src/tweening/index.ts@@ -1,4 +1,4 @@export * from './Animator';export * from './interpolationFunctions';+export * from './timingFunctions';export * from './tween';-export * from './tweenFunctions';diff --git a/packages/core/src/tweening/interpolationFunctions.test.ts b/packages/core/src/tweening/interpolationFunctions.test.tsnew file mode 100644index 00000000..98f014f2--- /dev/null+++ b/packages/core/src/tweening/interpolationFunctions.test.ts@@ -0,0 +1,122 @@+import {deepLerp, colorLerp, vector2dLerp} from './interpolationFunctions';+import type {Vector2} from '../types';++describe('deepLerp', () => {+ test('falls back to primitive tween for numbers', () => {+ expect(deepLerp(5, 10, 3 / 5)).toEqual(8);+ });++ test('falls back to primitive tween for strings', () => {+ expect(deepLerp('foo', 'foobar', 2 / 3)).toEqual('fooba');+ });++ test('interpolates between colors', () => {+ expect(deepLerp('hsl(0, 0%, 0%)', 'hsl(0, 0%, 100%)', 0)).toEqual(+ 'hsl(0, 0%, 0%)',+ );+ expect(+ deepLerp('hsl(0, 0%, 0%)', 'hsl(0, 0%, 100%)', 1 / 2),+ ).toMatchInlineSnapshot(`"rgb(50% 50% 50%)"`);+ expect(deepLerp('hsl(0, 0%, 0%)', 'hsl(0, 0%, 100%)', 1)).toEqual(+ 'hsl(0, 0%, 100%)',+ );+ });++ test('interpolates between values in an array', () => {+ expect(deepLerp([0, 2], [1, 3], 1 / 2)).toEqual([0.5, 2.5]);+ });++ test('jumps to new array if values vary in length', () => {+ expect(deepLerp([0, 2], [1, 3, 5], 0)).toEqual([0, 2]);+ expect(deepLerp([0, 2], [1, 3, 5], 1 / 2)).toEqual([1, 3, 5]);+ expect(deepLerp([0, 2], [1, 3, 5], 1)).toEqual([1, 3, 5]);+ });++ test('interpolates between values in a map', () => {+ expect(+ deepLerp(new Map([['foo', 0]]), new Map([['foo', 5]]), 3 / 5),+ ).toEqual(new Map([['foo', 3]]));+ });++ test('deletes values in a map after a value of 0', () => {+ expect(deepLerp(new Map([['foo', 5]]), new Map(), 3 / 5)).toEqual(+ new Map(),+ );+ expect(deepLerp(new Map([['foo', 5]]), new Map(), 1)).toEqual(new Map());+ });++ test('retains missing values in a map at a value of 0', () => {+ expect(deepLerp(new Map([['foo', 5]]), new Map(), 0)).toEqual(+ new Map([['foo', 5]]),+ );+ });++ test('waits to add new values to a map until a value of 1', () => {+ expect(deepLerp(new Map(), new Map([['foo', 5]]), 3 / 5)).toEqual(+ new Map(),+ );+ expect(deepLerp(new Map(), new Map([['foo', 5]]), 0)).toEqual(new Map());+ });++ test('adds new values to a map at a value of 1', () => {+ expect(deepLerp(new Map(), new Map([['foo', 5]]), 1)).toEqual(+ new Map([['foo', 5]]),+ );+ });++ test('interpolates between values in an object', () => {+ expect(deepLerp({foo: 0}, {foo: 5}, 3 / 5)).toEqual({foo: 3});+ });++ test('deletes values in a map after a value of 0', () => {+ expect(deepLerp({foo: 5}, {}, 3 / 5)).toEqual({});+ expect(deepLerp({foo: 5}, {}, 1)).toEqual({});+ });++ test('retains missing values in a map at a value of 0', () => {+ expect(deepLerp({foo: 5}, {}, 0)).toEqual({foo: 5});+ });++ test('retains properties with falsy values', () => {+ expect(deepLerp({x: 0, y: 10}, {x: 0, y: 20}, 0.5)).toEqual({x: 0, y: 15});+ });++ test('waits to add new values to a map until a value of 1', () => {+ expect(deepLerp({}, {foo: 5}, 3 / 5)).toEqual({});+ expect(deepLerp({}, {foo: 5}, 0)).toEqual({});+ });++ test('adds new values to a map at a value of 1', () => {+ expect(deepLerp({}, {foo: 5}, 1)).toEqual({foo: 5});+ });++ test('replaces vector2dLerp', () => {+ const args: [Vector2, Vector2, number] = [+ {x: 50, y: 65},+ {x: 10, y: 100},+ 1 / 2,+ ];+ expect(deepLerp(...args)).toEqual(vector2dLerp(...args));+ });+});++describe('colorLerp', () => {+ test('interpolates between colors', () => {+ expect(+ colorLerp('rgb(0, 0, 0)', 'rgb(255, 255, 255)', 1 / 2),+ ).toMatchInlineSnapshot(`"rgb(50% 50% 50%)"`);+ expect(+ colorLerp('hsl(0, 0%, 0%)', 'hsl(0, 0%, 100%)', 1 / 2),+ ).toMatchInlineSnapshot(`"rgb(50% 50% 50%)"`);+ });+ test('returns starting value at 0', () => {+ expect(colorLerp('hsl(0, 0%, 0%)', 'hsl(0, 0%, 100%)', 0)).toEqual(+ 'hsl(0, 0%, 0%)',+ );+ });+ test('returns final value at 1', () => {+ expect(colorLerp('hsl(0, 0%, 0%)', 'hsl(0, 0%, 100%)', 1)).toEqual(+ 'hsl(0, 0%, 100%)',+ );+ });+});diff --git a/packages/core/src/tweening/interpolationFunctions.ts b/packages/core/src/tweening/interpolationFunctions.tsindex c3449088..9e138796 100644--- a/packages/core/src/tweening/interpolationFunctions.ts+++ b/packages/core/src/tweening/interpolationFunctions.ts@@ -1,96 +1,259 @@-import {map, remap} from './tweenFunctions';+import Color from 'colorjs.io';+import type {Rect, Vector2, PossibleSpacing, Spacing} from '../types';-export interface InterpolationFunction {- (value: number, from?: number, to?: number): number;+export interface InterpolationFunction<T, Rest extends unknown[] = unknown[]> {+ (from: T, to: T, value: number, ...args: Rest): T;}-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 textLerp(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];+ }+ }-export function easeOutExpo(value: number, from = 0, to = 1) {- value = value === 1 ? 1 : 1 - Math.pow(2, -10 * value);- return map(from, to, value);-}+ 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));+ const 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]);+ }+ }-export function easeInExpo(value: number, from = 0, to = 1) {- value = value === 0 ? 0 : Math.pow(2, 10 * value - 10);- return map(from, to, value);+ return text.join('');+ }}-export function linear(value: number, from = 0, to = 1) {- return map(from, to, value);+/**+ * Interpolate between any two Records, including objects and Maps, even with+ * mismatched keys.+ *+ * @remarks+ * Any old key that is missing in `to` will be removed immediately once value is+ * not 0. Any new key that is missing in `from` will be added once value reaches+ * 1.+ *+ * @param from - The input to favor when value is 0.+ * @param to - The input to favor when value is 1.+ * @param value - On a scale between 0 and 1, how closely to favor from vs to.+ *+ * @returns A value matching the structure of from and to.+ */+export function deepLerp<+ TFrom extends Record<any, unknown>,+ TTo extends Record<any, unknown>,+>(from: TFrom, to: TTo, value: number): TFrom | TTo;+/**+ * Interpolate between any two values, including objects, arrays, and Maps.+ *+ * @param from - The input to favor when value is 0.+ * @param to - The input to favor when value is 1.+ * @param value - On a scale between 0 and 1, how closely to favor from vs to.+ *+ * @returns A value matching the structure of from and to.+ */+export function deepLerp<T>(from: T, to: T, value: number): T;+export function deepLerp(from: any, to: any, value: number): any {+ if (value === 0) return from;+ if (value === 1) return to;++ if (typeof from === 'undefined' || typeof to === 'undefined') {+ return undefined;+ }++ if (typeof from === 'number' && typeof to === 'number') {+ return map(from, to, value);+ }++ if (typeof from === 'string' && typeof to === 'string') {+ try {+ Color.parse(from);+ Color.parse(to);+ return colorLerp(from, to, value);+ } catch (err) {+ // inputs are not colors+ }++ return textLerp(from, to, value);+ }++ if (from && to && typeof from === 'object' && typeof to === 'object') {+ if (Array.isArray(from) && Array.isArray(to)) {+ if (from.length === to.length) {+ return from.map((f, i) => deepLerp(f, to[i], value));+ }+ } else {+ let toObject = false;+ if (!(from instanceof Map) && !(to instanceof Map)) {+ toObject = true;+ from = new Map(Object.entries(from));+ to = new Map(Object.entries(to));+ }++ if (from instanceof Map && to instanceof Map) {+ const result = new Map();+ for (const key of new Set([...from.keys(), ...to.keys()])) {+ const inter = deepLerp(from.get(key), to.get(key), value);+ if (inter !== undefined) result.set(key, inter);+ }+ return toObject ? Object.fromEntries(result) : result;+ }+ }+ }++ // fallback with an immediate jump to the new value+ return to;}-export function sin(value: number, from = 0, to = 1) {- return remap(-1, 1, from, to, Math.sin(value));+interface ColorLerpOptions {+ /**+ * The space to use during interpolation, affecting the intermediate colors+ */+ space?: string;+ /**+ * The format in which to return values+ */+ outputSpace?: string;}-export function cos(value: number, from = 0, to = 1) {- return remap(-1, 1, from, to, Math.cos(value));+/**+ * Mix two colors together.+ *+ * @param from - The value to use at 0.+ * @param to - The value to use at 1.+ * @param value - How much of each color to use, on a scale of 0 to 1.+ * @param options - Additional configuration.+ *+ * @returns An srgb string, or one of the input values if value is 0 or 1.+ */+export function colorLerp(+ from: string | typeof Color,+ to: string | typeof Color,+ value: number,+ options?: ColorLerpOptions,+): string {+ if (value === 0) return from;+ if (value === 1) return to;+ const range = new Color(from).range(to, {+ space: options?.space ?? 'srgb',+ outputSpace: options?.outputSpace ?? 'srgb',+ });+ return range(value).toString();}-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 vector2dLerp(from: Vector2, to: Vector2, value: number) {+ return {+ x: map(from.x, to.x, value),+ y: map(from.y, to.y, value),+ };}-export function easeOutCubic(value: number, from = 0, to = 1): number {- value = 1 - Math.pow(1 - value, 3);- return map(from, to, value);+export function spacingLerp(+ 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 easeInCubic(value: number, from = 0, to = 1): number {- value = value * value * value;- return map(from, to, value);+export function rectArcLerp(+ from: Partial<Rect>,+ to: Partial<Rect>,+ value: number,+ reverse?: boolean,+ ratio?: number,+) {+ ratio ??= calculateRatio(from, to);++ let flip = reverse;+ if (ratio > 1) {+ ratio = 1 / ratio;+ } else {+ flip = !flip;+ }++ const normalized = flip ? Math.acos(1 - value) : Math.asin(value);+ const radians = map(normalized, map(0, Math.PI / 2, value), ratio);++ let xValue = Math.sin(radians);+ let yValue = 1 - Math.cos(radians);+ 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 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);+export function calculateRatio(from: Partial<Rect>, to: Partial<Rect>): number {+ let numberOfValues = 0;+ let ratio = 0;+ if (from.x) {+ ratio += Math.abs((from.x - to.x) / (from.y - to.y));+ numberOfValues++;+ }+ if (from.width) {+ ratio += Math.abs((from.width - to.width) / (from.height - to.height));+ numberOfValues++;+ }++ if (numberOfValues) {+ ratio /= numberOfValues;+ }++ return isNaN(ratio) ? 1 : ratio;}-export function createEaseInBack(s = 1.70158): InterpolationFunction {- return (value: number, from = 0, to = 1) => {- return map(from, to, value * value * ((s + 1) * value - s));- };+export function map(from: number, to: number, value: number) {+ return from + (to - from) * value;}-export function createEaseOutBack(s = 1.70158): InterpolationFunction {- return (value: number, from = 0, to = 1) => {- return map(- from,- to,- 1 + (value - 1) * (value - 1) * ((s + 1) * (value - 1) + s),- );- };+export function remap(+ fromIn: number,+ toIn: number,+ fromOut: number,+ toOut: number,+ value: number,+) {+ return fromOut + ((value - fromIn) * (toOut - fromOut)) / (toIn - fromIn);}-export function createEaseInOutBack(s = 1.70158): InterpolationFunction {- return (value: number, from = 0, to = 1) => {- value = value * 2;- if (value < 1) {- return map(from, to, (value * value * ((s + 1) * value - s)) / 2);- }- value -= 1;- return map(- from,- to,- (1 + (value - 1) * (value - 1) * ((s + 1) * (value - 1) + s)) / 2 + 0.5,- );- };+export function clamp(min: number, max: number, value: number) {+ return value < min ? min : value > max ? max : value;}-export const easeInBack: InterpolationFunction = createEaseInBack();-export const easeOutBack: InterpolationFunction = createEaseOutBack();-export const easeInOutBack: InterpolationFunction = createEaseInOutBack();+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 clamp(fromOut, toOut, remappedValue);+}diff --git a/packages/core/src/tweening/timingFunctions.ts b/packages/core/src/tweening/timingFunctions.tsnew file mode 100644index 00000000..f77458e8--- /dev/null+++ b/packages/core/src/tweening/timingFunctions.ts@@ -0,0 +1,96 @@+import {map, remap} from './interpolationFunctions';++export interface TimingFunction {+ (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 easeOutCubic(value: number, from = 0, to = 1): number {+ value = 1 - Math.pow(1 - value, 3);+ return map(from, to, value);+}++export function easeInCubic(value: number, from = 0, to = 1): number {+ value = value * value * value;+ 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);+}++export function createEaseInBack(s = 1.70158): TimingFunction {+ return (value: number, from = 0, to = 1) => {+ return map(from, to, value * value * ((s + 1) * value - s));+ };+}++export function createEaseOutBack(s = 1.70158): TimingFunction {+ return (value: number, from = 0, to = 1) => {+ return map(+ from,+ to,+ 1 + (value - 1) * (value - 1) * ((s + 1) * (value - 1) + s),+ );+ };+}++export function createEaseInOutBack(s = 1.70158): TimingFunction {+ return (value: number, from = 0, to = 1) => {+ value = value * 2;+ if (value < 1) {+ return map(from, to, (value * value * ((s + 1) * value - s)) / 2);+ }+ value -= 1;+ return map(+ from,+ to,+ (1 + (value - 1) * (value - 1) * ((s + 1) * (value - 1) + s)) / 2 + 0.5,+ );+ };+}++export const easeInBack: TimingFunction = createEaseInBack();+export const easeOutBack: TimingFunction = createEaseOutBack();+export const easeInOutBack: TimingFunction = createEaseInOutBack();diff --git a/packages/core/src/tweening/tweenFunctions.test.ts b/packages/core/src/tweening/tweenFunctions.test.tsdeleted file mode 100644index a84e9fd3..00000000--- a/packages/core/src/tweening/tweenFunctions.test.ts+++ /dev/null@@ -1,122 +0,0 @@-import {deepTween, colorTween, vector2dTween} from './tweenFunctions';-import type {Vector2} from '../types';--describe('deepTween', () => {- test('falls back to primitive tween for numbers', () => {- expect(deepTween(5, 10, 3 / 5)).toEqual(8);- });-- test('falls back to primitive tween for strings', () => {- expect(deepTween('foo', 'foobar', 2 / 3)).toEqual('fooba');- });-- test('interpolates between colors', () => {- expect(deepTween('hsl(0, 0%, 0%)', 'hsl(0, 0%, 100%)', 0)).toEqual(- 'hsl(0, 0%, 0%)',- );- expect(- deepTween('hsl(0, 0%, 0%)', 'hsl(0, 0%, 100%)', 1 / 2),- ).toMatchInlineSnapshot(`"rgb(50% 50% 50%)"`);- expect(deepTween('hsl(0, 0%, 0%)', 'hsl(0, 0%, 100%)', 1)).toEqual(- 'hsl(0, 0%, 100%)',- );- });-- test('interpolates between values in an array', () => {- expect(deepTween([0, 2], [1, 3], 1 / 2)).toEqual([0.5, 2.5]);- });-- test('jumps to new array if values vary in length', () => {- expect(deepTween([0, 2], [1, 3, 5], 0)).toEqual([0, 2]);- expect(deepTween([0, 2], [1, 3, 5], 1 / 2)).toEqual([1, 3, 5]);- expect(deepTween([0, 2], [1, 3, 5], 1)).toEqual([1, 3, 5]);- });-- test('interpolates between values in a map', () => {- expect(- deepTween(new Map([['foo', 0]]), new Map([['foo', 5]]), 3 / 5),- ).toEqual(new Map([['foo', 3]]));- });-- test('deletes values in a map after a value of 0', () => {- expect(deepTween(new Map([['foo', 5]]), new Map(), 3 / 5)).toEqual(- new Map(),- );- expect(deepTween(new Map([['foo', 5]]), new Map(), 1)).toEqual(new Map());- });-- test('retains missing values in a map at a value of 0', () => {- expect(deepTween(new Map([['foo', 5]]), new Map(), 0)).toEqual(- new Map([['foo', 5]]),- );- });-- test('waits to add new values to a map until a value of 1', () => {- expect(deepTween(new Map(), new Map([['foo', 5]]), 3 / 5)).toEqual(- new Map(),- );- expect(deepTween(new Map(), new Map([['foo', 5]]), 0)).toEqual(new Map());- });-- test('adds new values to a map at a value of 1', () => {- expect(deepTween(new Map(), new Map([['foo', 5]]), 1)).toEqual(- new Map([['foo', 5]]),- );- });-- test('interpolates between values in an object', () => {- expect(deepTween({foo: 0}, {foo: 5}, 3 / 5)).toEqual({foo: 3});- });-- test('deletes values in a map after a value of 0', () => {- expect(deepTween({foo: 5}, {}, 3 / 5)).toEqual({});- expect(deepTween({foo: 5}, {}, 1)).toEqual({});- });-- test('retains missing values in a map at a value of 0', () => {- expect(deepTween({foo: 5}, {}, 0)).toEqual({foo: 5});- });-- test('retains properties with falsy values', () => {- expect(deepTween({x: 0, y: 10}, {x: 0, y: 20}, 0.5)).toEqual({x: 0, y: 15});- });-- test('waits to add new values to a map until a value of 1', () => {- expect(deepTween({}, {foo: 5}, 3 / 5)).toEqual({});- expect(deepTween({}, {foo: 5}, 0)).toEqual({});- });-- test('adds new values to a map at a value of 1', () => {- expect(deepTween({}, {foo: 5}, 1)).toEqual({foo: 5});- });-- test('replaces vector2dTween', () => {- const args: [Vector2, Vector2, number] = [- {x: 50, y: 65},- {x: 10, y: 100},- 1 / 2,- ];- expect(deepTween(...args)).toEqual(vector2dTween(...args));- });-});--describe('colorTween', () => {- test('interpolates between colors', () => {- expect(- colorTween('rgb(0, 0, 0)', 'rgb(255, 255, 255)', 1 / 2),- ).toMatchInlineSnapshot(`"rgb(50% 50% 50%)"`);- expect(- colorTween('hsl(0, 0%, 0%)', 'hsl(0, 0%, 100%)', 1 / 2),- ).toMatchInlineSnapshot(`"rgb(50% 50% 50%)"`);- });- test('returns starting value at 0', () => {- expect(colorTween('hsl(0, 0%, 0%)', 'hsl(0, 0%, 100%)', 0)).toEqual(- 'hsl(0, 0%, 0%)',- );- });- test('returns final value at 1', () => {- expect(colorTween('hsl(0, 0%, 0%)', 'hsl(0, 0%, 100%)', 1)).toEqual(- 'hsl(0, 0%, 100%)',- );- });-});diff --git a/packages/core/src/tweening/tweenFunctions.ts b/packages/core/src/tweening/tweenFunctions.tsdeleted file mode 100644index e5c15a89..00000000--- a/packages/core/src/tweening/tweenFunctions.ts+++ /dev/null@@ -1,262 +0,0 @@-import Color from 'colorjs.io';-import type {Rect, Vector2, PossibleSpacing, Spacing} from '../types';--export interface TweenFunction<T, Rest extends unknown[] = unknown[]> {- (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));- const 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('');- }-}--/**- * Interpolate between any two Records, including objects and Maps, even with- * mismatched keys.- *- * @remarks- * Any old key that is missing in `to` will be removed immediately once value is- * not 0. Any new key that is missing in `from` will be added once value reaches- * 1.- *- * @param from - The input to favor when value is 0.- * @param to - The input to favor when value is 1.- * @param value - On a scale between 0 and 1, how closely to favor from vs to.- *- * @returns A value matching the structure of from and to.- */-export function deepTween<- TFrom extends Record<any, unknown>,- TTo extends Record<any, unknown>,->(from: TFrom, to: TTo, value: number): TFrom | TTo;-/**- * Interpolate between any two values, including objects, arrays, and Maps.- *- * @param from - The input to favor when value is 0.- * @param to - The input to favor when value is 1.- * @param value - On a scale between 0 and 1, how closely to favor from vs to.- *- * @returns A value matching the structure of from and to.- */-export function deepTween<T>(from: T, to: T, value: number): T;-export function deepTween(from: any, to: any, value: number): any {- if (value === 0) return from;- if (value === 1) return to;-- if (typeof from === 'undefined' || typeof to === 'undefined') {- return undefined;- }-- if (typeof from === 'number' && typeof to === 'number') {- return map(from, to, value);- }-- if (typeof from === 'string' && typeof to === 'string') {- try {- Color.parse(from);- Color.parse(to);- return colorTween(from, to, value);- } catch (err) {- // inputs are not colors- }-- return textTween(from, to, value);- }-- if (from && to && typeof from === 'object' && typeof to === 'object') {- if (Array.isArray(from) && Array.isArray(to)) {- if (from.length === to.length) {- return from.map((f, i) => deepTween(f, to[i], value));- }- } else {- let toObject = false;- if (!(from instanceof Map) && !(to instanceof Map)) {- toObject = true;- from = new Map(Object.entries(from));- to = new Map(Object.entries(to));- }-- if (from instanceof Map && to instanceof Map) {- const result = new Map();- for (const key of new Set([...from.keys(), ...to.keys()])) {- const inter = deepTween(from.get(key), to.get(key), value);- if (inter !== undefined) result.set(key, inter);- }- return toObject ? Object.fromEntries(result) : result;- }- }- }-- // fallback with an immediate jump to the new value- return to;-}--interface ColorTweenOptions {- /**- * The space to use during interpolation, affecting the intermediate colors- */- space?: string;- /**- * The format in which to return values- */- outputSpace?: string;-}--/**- * Mix two colors together.- *- * @param from - The value to use at 0.- * @param to - The value to use at 1.- * @param value - How much of each color to use, on a scale of 0 to 1.- * @param options - Additional configuration.- *- * @returns An srgb string, or one of the input values if value is 0 or 1.- */-export function colorTween(- from: string | typeof Color,- to: string | typeof Color,- value: number,- options?: ColorTweenOptions,-): string {- if (value === 0) return from;- if (value === 1) return to;- const range = new Color(from).range(to, {- space: options?.space ?? 'srgb',- outputSpace: options?.outputSpace ?? 'srgb',- });- return range(value).toString();-}--/**- * @deprecated Use {@link deepTween} instead.- */-export function vector2dTween(from: Vector2, to: Vector2, 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<Rect>,- to: Partial<Rect>,- value: number,- reverse?: boolean,- ratio?: number,-) {- ratio ??= calculateRatio(from, to);-- let flip = reverse;- if (ratio > 1) {- ratio = 1 / ratio;- } else {- flip = !flip;- }-- const normalized = flip ? Math.acos(1 - value) : Math.asin(value);- const radians = map(normalized, map(0, Math.PI / 2, value), ratio);-- let xValue = Math.sin(radians);- let yValue = 1 - Math.cos(radians);- 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 calculateRatio(from: Partial<Rect>, to: Partial<Rect>): number {- let numberOfValues = 0;- let ratio = 0;- if (from.x) {- ratio += Math.abs((from.x - to.x) / (from.y - to.y));- numberOfValues++;- }- if (from.width) {- ratio += Math.abs((from.width - to.width) / (from.height - to.height));- numberOfValues++;- }-- if (numberOfValues) {- ratio /= numberOfValues;- }-- return isNaN(ratio) ? 1 : ratio;-}--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 clamp(min: number, max: number, value: number) {- return value < min ? min : value > max ? max : value;-}--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 clamp(fromOut, toOut, remappedValue);-}diff --git a/packages/docs/docs/guides/migration/12.0.0.md b/packages/docs/docs/guides/migration/12.0.0.mdindex c7e91b67..5cc0739b 100644--- a/packages/docs/docs/guides/migration/12.0.0.md+++ b/packages/docs/docs/guides/migration/12.0.0.md@@ -104,3 +104,13 @@ Similarly, change your types reference in `motion-canvas.d.ts`:- /// <reference types="@motion-canvas/core/project" />+ /// <reference types="@motion-canvas/legacy/project" />```++## Update function names++`TweenFunction`s are now called `InterpolationFunction`s.+The naming convention has changed. Instead of `[type]Tween` they now use+`[type]Lerp`. For instance: `colorTween` is now `colorLerp`.++`InterpolationFunction`s are now called `TimingFunction`s.+Their individual names haven't changed (`easeInExpo`, `easeOutCubic`, etc.),+but referring to them as timing functions is better aligned with the CSS spec.diff --git a/packages/legacy/src/animations/surfaceFrom.ts b/packages/legacy/src/animations/surfaceFrom.tsindex 7f6bbc83..b7b9d0a2 100644--- a/packages/legacy/src/animations/surfaceFrom.ts+++ b/packages/legacy/src/animations/surfaceFrom.ts@@ -3,10 +3,10 @@ import type {ThreadGenerator} from '@motion-canvas/core/lib/threading';import type {Surface, SurfaceMask} from '../components';import {calculateRatio,- colorTween,+ colorLerp,easeInOutCubic,easeInOutQuint,- rectArcTween,+ rectArcLerp,tween,} from '@motion-canvas/core/lib/tweening';import {decorate, threadable} from '@motion-canvas/core/lib/decorators';@@ -19,7 +19,7 @@ export interface SurfaceFromConfig {* Whether the transition arc should be reversed.** @remarks- * See {@link rectArcTween} for more detail.+ * See {@link rectArcLerp} for more detail.*/reverse?: boolean;/**@@ -67,7 +67,7 @@ export function* surfaceFrom(yield* tween(config.duration ?? 0.6, value => {surface.setMask({...fromMask,- ...rectArcTween(+ ...rectArcLerp(fromMask,toMask,easeInOutQuint(value),@@ -75,11 +75,11 @@ export function* surfaceFrom(ratio,),radius: easeInOutCubic(value, fromMask.radius, toMask.radius),- color: colorTween(fromMask.color, toMask.color, easeInOutQuint(value)),+ color: colorLerp(fromMask.color, toMask.color, easeInOutQuint(value)),});if (position) {surface.setPosition(- rectArcTween(+ rectArcLerp(position,toPosition,easeInOutQuint(value),diff --git a/packages/legacy/src/animations/surfaceTransition.ts b/packages/legacy/src/animations/surfaceTransition.tsindex 699d56aa..dd8b783d 100644--- a/packages/legacy/src/animations/surfaceTransition.ts+++ b/packages/legacy/src/animations/surfaceTransition.ts@@ -2,10 +2,10 @@ import {Surface} from '../components';import {calculateRatio,clampRemap,- colorTween,+ colorLerp,easeInOutCubic,easeInOutQuint,- rectArcTween,+ rectArcLerp,tween,} from '@motion-canvas/core/lib/tweening';import {decorate, threadable} from '@motion-canvas/core/lib/decorators';@@ -34,7 +34,7 @@ export interface SurfaceTransitionConfig {* Whether the transition arc should be reversed.** @remarks- * See {@link rectArcTween} for more detail.+ * See {@link rectArcLerp} for more detail.*/reverse?: boolean;/**@@ -128,16 +128,16 @@ export function* surfaceTransition(}target.setMask({...from,- ...rectArcTween(from, to, easeInOutQuint(value), config.reverse, ratio),+ ...rectArcLerp(from, to, easeInOutQuint(value), config.reverse, ratio),radius: easeInOutCubic(value, from.radius, target.radius()),- color: colorTween(+ color: colorLerp(from.color,target.background(),easeInOutQuint(value),),});target.setPosition(- rectArcTween(+ rectArcLerp(fromNewPos,toPos,easeInOutQuint(value),@@ -157,16 +157,16 @@ export function* surfaceTransition(relativeValue = clampRemap(0, transitionTime, 1, 0, value);initial.setMask({...from,- ...rectArcTween(from, to, easeInOutQuint(value), config.reverse, ratio),+ ...rectArcLerp(from, to, easeInOutQuint(value), config.reverse, ratio),radius: easeInOutCubic(value, from.radius, target.radius()),- color: colorTween(+ color: colorLerp(from.color,target.background(),easeInOutQuint(value),),});initial.setPosition(- rectArcTween(+ rectArcLerp(fromPos,toNewPos,easeInOutQuint(value),diff --git a/packages/legacy/src/components/LayoutText.ts b/packages/legacy/src/components/LayoutText.tsindex 12d410fc..04d44e47 100644--- a/packages/legacy/src/components/LayoutText.ts+++ b/packages/legacy/src/components/LayoutText.ts@@ -10,8 +10,8 @@ import {import {Animator,tween,- textTween,- InterpolationFunction,+ textLerp,+ TimingFunction,} from '@motion-canvas/core/lib/tweening';import {threadable} from '@motion-canvas/core/lib/decorators';import {getset} from '../decorators';@@ -102,7 +102,7 @@ export class LayoutText extends Text {fromText: string,text: string,time: number,- interpolation: InterpolationFunction,+ timingFunction: TimingFunction,onEnd: Callback,) {const fromWidth = this.getLayoutSize({text: fromText, minWidth: 0}).width;@@ -110,8 +110,8 @@ export class LayoutText extends Text {this.overrideWidth = fromWidth;yield* tween(time, value => {- this.overrideWidth = interpolation(value, fromWidth, toWidth);- this.setText(textTween(fromText, text, interpolation(value)));+ this.overrideWidth = timingFunction(value, fromWidth, toWidth);+ this.setText(textLerp(fromText, text, timingFunction(value)));});this.overrideWidth = null;diff --git a/packages/legacy/src/components/Sprite.ts b/packages/legacy/src/components/Sprite.tsindex a6272f6a..9a993943 100644--- a/packages/legacy/src/components/Sprite.ts+++ b/packages/legacy/src/components/Sprite.ts@@ -4,11 +4,7 @@ import {waitFor} from '@motion-canvas/core/lib/flow';import {threadable} from '@motion-canvas/core/lib/decorators';import {cached, KonvaNode, getset} from '../decorators';import {GeneratorHelper} from '@motion-canvas/core/lib/helpers';-import {- InterpolationFunction,- map,- tween,-} from '@motion-canvas/core/lib/tweening';+import {TimingFunction, map, tween} from '@motion-canvas/core/lib/tweening';import {cancel, ThreadGenerator} from '@motion-canvas/core/lib/threading';import {parseColor} from 'mix-color';import {Shape, ShapeConfig} from 'konva/lib/Shape';@@ -318,7 +314,7 @@ export class Sprite extends Shape {from: ImageDataSource,to: ImageDataSource,time: number,- interpolation: InterpolationFunction,+ timingFunction: TimingFunction,onEnd: () => void,): ThreadGenerator {this.baseMask = from;@@ -328,7 +324,7 @@ export class Sprite extends Shape {this.mask(to);yield* tween(time, value => {- this.baseMaskBlend = interpolation(1 - value);+ this.baseMaskBlend = timingFunction(1 - value);this.updateFrame();});this.baseMask = null;diff --git a/packages/legacy/src/patches/Factory.ts b/packages/legacy/src/patches/Factory.tsindex 22bce70f..2a52a51e 100644--- a/packages/legacy/src/patches/Factory.ts+++ b/packages/legacy/src/patches/Factory.ts@@ -3,8 +3,8 @@ import {Factory} from 'konva/lib/Factory';import {ANIMATE} from '@motion-canvas/core/lib';import {Animator,+ TimingFunction,InterpolationFunction,- TweenFunction,TweenProvider,} from '@motion-canvas/core/lib/tweening';import {ThreadGenerator} from '@motion-canvas/core/lib/threading';@@ -28,8 +28,8 @@ declare module 'konva/lib/types' {<Rest extends unknown[]>(value: Type,time: number,- interpolation?: InterpolationFunction,- mapper?: TweenFunction<Type, Rest>,+ timingFunction?: TimingFunction,+ interpolationFunction?: InterpolationFunction<Type, Rest>,...rest: Rest): ThreadGenerator;}@@ -47,8 +47,8 @@ Factory.addOverloadedGetterSetter = function addOverloadedGetterSetter(constructor.prototype[attr] = function <Rest extends unknown[]>(value?: Vector2d | typeof ANIMATE,time?: number,- interpolation?: InterpolationFunction,- mapper?: TweenFunction<unknown, Rest>,+ timingFunction?: TimingFunction,+ interpolationFunction?: InterpolationFunction<unknown, Rest>,...rest: Rest) {if (value === ANIMATE) {@@ -56,7 +56,7 @@ Factory.addOverloadedGetterSetter = function addOverloadedGetterSetter(}if (time !== undefined) {return new Animator<unknown, Node>(this, attr, tween)- .key(value, time, interpolation, mapper, ...rest)+ .key(value, time, timingFunction, interpolationFunction, ...rest).run();}return value === undefined ? this[getter]() : this[setter](value);