Visualize Your Ideas With Code
feat: added deepTween function and rewrote colorTween to use colorjs.io (#88)
Ross Esmondeb7ca3c8974a
diff --git a/package-lock.json b/package-lock.jsonindex 2125acfa..1fcced8e 100644--- a/package-lock.json+++ b/package-lock.json@@ -12,6 +12,7 @@"@types/prismjs": "^1.26.0","@types/three": "^0.141.0","@types/webpack-env": "^1.17.0",+ "colorjs.io": "^0.3.0","html-webpack-plugin": "^5.5.0","image-size": "^1.0.1","konva": "^8.3.9",@@ -3937,6 +3938,11 @@"resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.17.tgz","integrity": "sha512-hJo+3Bkn0NCHybn9Tu35fIeoOKGOk5OCC32y4Hz2It+qlCO2Q3DeQ1hRn/tDDMQKRYUEzqsl7jbF6dYKjlE60g=="},+ "node_modules/colorjs.io": {+ "version": "0.3.0",+ "resolved": "https://registry.npmjs.org/colorjs.io/-/colorjs.io-0.3.0.tgz",+ "integrity": "sha512-F1FD3/LWZDjd66KUAVErCLDrij/ukHntf5bWtfhrnSV2IT5ZUivuv7KKW3QbZLbjKPTsVPjmxeugQgnNYWMdrA=="+ },"node_modules/combined-stream": {"version": "1.0.8","resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",@@ -18396,6 +18402,11 @@"resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.17.tgz","integrity": "sha512-hJo+3Bkn0NCHybn9Tu35fIeoOKGOk5OCC32y4Hz2It+qlCO2Q3DeQ1hRn/tDDMQKRYUEzqsl7jbF6dYKjlE60g=="},+ "colorjs.io": {+ "version": "0.3.0",+ "resolved": "https://registry.npmjs.org/colorjs.io/-/colorjs.io-0.3.0.tgz",+ "integrity": "sha512-F1FD3/LWZDjd66KUAVErCLDrij/ukHntf5bWtfhrnSV2IT5ZUivuv7KKW3QbZLbjKPTsVPjmxeugQgnNYWMdrA=="+ },"combined-stream": {"version": "1.0.8","resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",diff --git a/package.json b/package.jsonindex 8c3a5a2a..65954b31 100644--- a/package.json+++ b/package.json@@ -37,6 +37,7 @@"@types/prismjs": "^1.26.0","@types/three": "^0.141.0","@types/webpack-env": "^1.17.0",+ "colorjs.io": "^0.3.0","html-webpack-plugin": "^5.5.0","image-size": "^1.0.1","konva": "^8.3.9",diff --git a/src/globals.ts b/src/globals.tsindex 1258550c..c488dcf4 100644--- a/src/globals.ts+++ b/src/globals.ts@@ -99,3 +99,8 @@ declare const PROJECT_FILE_NAME: string;declare const CORE_VERSION: string;declare const META_VERSION: number;++declare module 'colorjs.io' {+ const noTypesYet: any;+ export default noTypesYet;+}diff --git a/src/styles/Style.ts b/src/styles/Style.tsindex f13b0b04..7bd26f59 100644--- a/src/styles/Style.ts+++ b/src/styles/Style.ts@@ -1,5 +1,5 @@import type {Node} from 'konva/lib/Node';-import {parseColor} from 'mix-color';+import Color from 'colorjs.io';export interface Style {labelFont: string;@@ -41,9 +41,6 @@ export function getStyle(node: Node): Style {}export function getFontColor(background: string) {- const color = parseColor(background);- const brightness = Math.round(- (color.r * 299 + color.g * 587 + color.b * 114) / 1000,- );- return brightness > 125 ? 'rgba(0, 0, 0, 0.87)' : 'rgba(255, 255, 255, 0.87)';+ const color = new Color(background);+ return color.lab.l > 50 ? 'rgba(0, 0, 0, 0.87)' : 'rgba(255, 255, 255, 0.87)';}diff --git a/src/transitions/slideTransition.ts b/src/transitions/slideTransition.tsindex 08bbfd90..a698c04d 100644--- a/src/transitions/slideTransition.ts+++ b/src/transitions/slideTransition.ts@@ -1,5 +1,5 @@import {Direction, originPosition} from '../types';-import {easeInOutCubic, tween, vector2dTween} from '../tweening';+import {easeInOutCubic, tween, deepTween} 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 = vector2dTween(+ ppos = deepTween({x: 0, y: 0},{x: -position.x, y: -position.y},easeInOutCubic(value),);- cpos = vector2dTween(position, {x: 0, y: 0}, easeInOutCubic(value));+ cpos = deepTween(position, {x: 0, y: 0}, easeInOutCubic(value));},endTransition,);diff --git a/src/tweening/Animator.ts b/src/tweening/Animator.tsindex 841b9da4..1ad0b521 100644--- a/src/tweening/Animator.ts+++ b/src/tweening/Animator.ts@@ -3,12 +3,10 @@ import {easeInOutCubic,InterpolationFunction,map,- rectArcTween,- spacingTween,textTween,tween,TweenFunction,- vector2dTween,+ deepTween,} from './index';import {threadable} from '../decorators';import {waitFor, waitUntil} from '../flow';@@ -183,15 +181,7 @@ export class Animator<Type, This> {tween = textTween;}} else if (value && typeof value === 'object') {- if ('x' in value) {- if ('width' in value) {- tween = rectArcTween;- } else {- tween = vector2dTween;- }- } else if ('left' in value) {- tween = spacingTween;- }+ tween = deepTween;}return tween as TweenFunction<T>;diff --git a/src/tweening/tweenFunctions.test.ts b/src/tweening/tweenFunctions.test.tsnew file mode 100644index 00000000..b8a7aaec--- /dev/null+++ b/src/tweening/tweenFunctions.test.ts@@ -0,0 +1,118 @@+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('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/src/tweening/tweenFunctions.ts b/src/tweening/tweenFunctions.tsindex b3026eef..cdc57087 100644--- a/src/tweening/tweenFunctions.ts+++ b/src/tweening/tweenFunctions.ts@@ -1,4 +1,4 @@-import mixColor from 'mix-color';+import Color from 'colorjs.io';import type {Rect, Vector2, PossibleSpacing, Spacing} from '../types';export interface TweenFunction<T, Rest extends unknown[] = unknown[]> {@@ -38,10 +38,118 @@ export function textTween(from: string, to: string, value: number) {}}-export function colorTween(from: string, to: string, value: number) {- return mixColor(from, to, value);+/**+ * Interpolate between any two Records, including objects and Maps, even with mismatched keys.+ * 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) 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+ * @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),