morphico 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +147 -63
  2. package/dist/esm/all.js +50 -0
  3. package/dist/esm/clip.js +285 -0
  4. package/dist/esm/engine.js +25 -0
  5. package/dist/esm/face.js +152 -0
  6. package/dist/esm/geometry.js +459 -0
  7. package/dist/esm/icon.js +41 -0
  8. package/dist/esm/index.js +51 -0
  9. package/dist/esm/morph.js +107 -0
  10. package/dist/esm/roundness.js +37 -0
  11. package/dist/esm/sets/battery.js +87 -0
  12. package/dist/esm/sets/bell.js +101 -0
  13. package/dist/esm/sets/characters.js +64 -0
  14. package/dist/esm/sets/check-mark.js +74 -0
  15. package/dist/esm/sets/checkbox.js +91 -0
  16. package/dist/esm/sets/chevron.js +70 -0
  17. package/dist/esm/sets/condensed.js +138 -0
  18. package/dist/esm/sets/copy.js +87 -0
  19. package/dist/esm/sets/eye.js +105 -0
  20. package/dist/esm/sets/faces.js +482 -0
  21. package/dist/esm/sets/folder.js +112 -0
  22. package/dist/esm/sets/handwritten.js +137 -0
  23. package/dist/esm/sets/lock.js +75 -0
  24. package/dist/esm/sets/lucide.js +66 -0
  25. package/dist/esm/sets/media.js +109 -0
  26. package/dist/esm/sets/menu.js +84 -0
  27. package/dist/esm/sets/mic.js +102 -0
  28. package/dist/esm/sets/radio.js +84 -0
  29. package/dist/esm/sets/round.js +245 -0
  30. package/dist/esm/sets/shapes.js +461 -0
  31. package/dist/esm/sets/slim.js +149 -0
  32. package/dist/esm/sets/square.js +150 -0
  33. package/dist/esm/sets/symbols.js +154 -0
  34. package/dist/esm/sets/theme.js +107 -0
  35. package/dist/esm/sets/toggle.js +73 -0
  36. package/dist/esm/sets/volume.js +89 -0
  37. package/dist/esm/sets/weather.js +691 -0
  38. package/dist/esm/sets/wifi.js +68 -0
  39. package/dist/esm/svg.js +31 -0
  40. package/dist/esm/text.js +89 -0
  41. package/dist/esm/types.js +3 -0
  42. package/dist/morphico.js +3991 -3787
  43. package/dist/types/{iconSets.d.ts → all.d.ts} +0 -2
  44. package/dist/types/clip.d.ts +8 -18
  45. package/dist/types/face.d.ts +2 -6
  46. package/dist/types/icon.d.ts +6 -11
  47. package/dist/types/index.d.ts +4 -5
  48. package/dist/types/morph.d.ts +3 -3
  49. package/dist/types/roundness.d.ts +8 -0
  50. package/dist/types/sets/battery.d.ts +1 -1
  51. package/dist/types/sets/bell.d.ts +1 -1
  52. package/dist/types/sets/characters.d.ts +3 -2
  53. package/dist/types/sets/checkbox.d.ts +1 -1
  54. package/dist/types/sets/chevron.d.ts +1 -1
  55. package/dist/types/sets/condensed.d.ts +1 -1
  56. package/dist/types/sets/copy.d.ts +1 -1
  57. package/dist/types/sets/eye.d.ts +1 -1
  58. package/dist/types/sets/folder.d.ts +1 -1
  59. package/dist/types/sets/handwritten.d.ts +1 -1
  60. package/dist/types/sets/lock.d.ts +1 -1
  61. package/dist/types/sets/media.d.ts +1 -1
  62. package/dist/types/sets/menu.d.ts +1 -1
  63. package/dist/types/sets/mic.d.ts +1 -1
  64. package/dist/types/sets/radio.d.ts +1 -1
  65. package/dist/types/sets/round.d.ts +1 -1
  66. package/dist/types/sets/shapes.d.ts +4 -1
  67. package/dist/types/sets/slim.d.ts +1 -1
  68. package/dist/types/sets/square.d.ts +1 -1
  69. package/dist/types/sets/symbols.d.ts +38 -0
  70. package/dist/types/sets/theme.d.ts +1 -1
  71. package/dist/types/sets/toggle.d.ts +1 -1
  72. package/dist/types/sets/volume.d.ts +1 -1
  73. package/dist/types/sets/weather.d.ts +1 -1
  74. package/dist/types/sets/wifi.d.ts +1 -1
  75. package/dist/types/text.d.ts +9 -20
  76. package/package.json +95 -3
  77. package/dist/morphico.mjs +0 -4642
@@ -0,0 +1,285 @@
1
+ /*! morphico v0.6.0 | MIT License, Copyright (c) 2026 Raycho Ivanov (see LICENSE) */
2
+ // Layer 3: an element cut out by a morphing shape (a star, a heart, a speech bubble …), e.g. a photo or a card.
3
+ // The shape is square (1:1), placed by its centre (x, y) and size in % or px of the element, can be turned and
4
+ // outlined (only a band along its edge shows). Filled → CSS `clip-path: url(#id)`; outlined → `mask: url(#id)`
5
+ // (clip-path ignores line width). The <clipPath> / <mask> live in one hidden <svg> per clip.
6
+ import { animate, easings } from './engine.js';
7
+ import { interpolate, pieceLengthOf, shapeForPair, toPathData } from './geometry.js';
8
+ import { checkedInit, resolveIconSet } from './roundness.js';
9
+ import { clampToUnit, DEFAULT_DURATION, prefersReducedMotion, shapesOf } from './morph.js';
10
+ import { clipShapes } from './sets/shapes.js';
11
+ import { createSvgElement } from './svg.js';
12
+ const GRID_SIZE = 24;
13
+ /** Default size: this share of the element's shorter side (a square that fits, with room around it). */
14
+ const DEFAULT_SIZE_SHARE = 0.7;
15
+ const GRID_CENTER = 12;
16
+ const DEGREE = Math.PI / 180;
17
+ /** Masks and their clip regions reach far past the element, so bands and turned shapes are never cut by them. */
18
+ const FAR = 100000;
19
+ /** In objectBoundingBox units (1 = the element's width / height): far around the element. */
20
+ const INVERTED_SURROUNDING = 'M-1000 -1000H1001V1001H-1000Z';
21
+ let clipCount = 0;
22
+ const lengthToPixels = (length, reference, name) => {
23
+ if (typeof length === 'number' && Number.isFinite(length))
24
+ return (length / 100) * reference;
25
+ const match = typeof length === 'string' ? /^\s*(-?[\d.]+(?:e[-+]?\d+)?)\s*(px|%)\s*$/i.exec(length) : null;
26
+ if (!match)
27
+ throw new Error(`morphico: ${name} "${length}" is not a length — use a number (= %), '40%' or '120px'`);
28
+ const value = Number(match[1]);
29
+ return match[2] === 'px' ? value : (value / 100) * reference;
30
+ };
31
+ const checkedOutline = (outline) => {
32
+ if (!outline)
33
+ return false;
34
+ if (!(outline.width > 0))
35
+ throw new Error('morphico: outline.width must be a number of px above 0');
36
+ if (outline.band && !['inside', 'centre', 'outside'].includes(outline.band)) {
37
+ throw new Error(`morphico: outline.band "${outline.band}" — use 'inside', 'centre' or 'outside'`);
38
+ }
39
+ return outline;
40
+ };
41
+ /** Cuts `element` out by a morphing shape, `init` first. */
42
+ export const clip = (element, init, options = {}) => {
43
+ const { x = 50, y = 50, size, rotation = 0, roundness = 1, outline = false, inverted = false, ...defaultMorphOptions } = options;
44
+ const checkedState = (shapeSet, state) => {
45
+ if (!(state in shapeSet.strokes)) {
46
+ throw new Error(`morphico: unknown shape "${state}" (known: ${Object.keys(shapeSet.strokes).join(', ')})`);
47
+ }
48
+ return state;
49
+ };
50
+ for (const [name, length] of [['x', x], ['y', y], ['size', size]]) {
51
+ if (length !== undefined)
52
+ lengthToPixels(length, 1, name);
53
+ }
54
+ /** Where the change goes (or what shows when nothing moves). */
55
+ const target = {
56
+ state: checkedState(clipShapes, checkedInit(init, 'clip')), set: resolveIconSet(clipShapes, roundness), roundness,
57
+ x, y, size, rotation, outline: checkedOutline(outline), inverted,
58
+ };
59
+ const pieceLength = pieceLengthOf(clipShapes);
60
+ let frame = null; // null = resting at the target
61
+ let running = null;
62
+ let elementWidth = 0, elementHeight = 0;
63
+ // ---- the hidden <svg> with the <clipPath> (filled) and the <mask> (outlined) ----
64
+ const id = `morphico-clip-${++clipCount}`;
65
+ const svg = createSvgElement('svg', { width: 0, height: 0, 'aria-hidden': 'true', focusable: 'false' });
66
+ svg.style.position = 'absolute';
67
+ svg.style.pointerEvents = 'none';
68
+ const clipPathElement = svg.appendChild(createSvgElement('clipPath', { id: `${id}-shape`, clipPathUnits: 'objectBoundingBox' }));
69
+ const clipShape = clipPathElement.appendChild(createSvgElement('path'));
70
+ const farRegion = { maskUnits: 'userSpaceOnUse', x: -FAR, y: -FAR, width: 2 * FAR, height: 2 * FAR };
71
+ const maskElement = svg.appendChild(createSvgElement('mask', { id: `${id}-band`, ...farRegion }));
72
+ /** Every path drawn in element pixels for the outlined band (the band itself and its helpers). */
73
+ let bandPaths = [];
74
+ const buildBand = () => {
75
+ for (const helper of svg.querySelectorAll('.morphico-band-helper'))
76
+ helper.remove();
77
+ maskElement.replaceChildren();
78
+ bandPaths = [];
79
+ clipShape.setAttribute('clip-rule', target.inverted ? 'evenodd' : 'nonzero');
80
+ if (!target.outline)
81
+ return;
82
+ const { width, band = 'inside' } = target.outline;
83
+ // inverted: everything shows (white), the band is the hole (black)
84
+ const bandColor = target.inverted ? 'black' : 'white';
85
+ if (target.inverted) {
86
+ maskElement.append(createSvgElement('rect', { x: -FAR, y: -FAR, width: 2 * FAR, height: 2 * FAR, fill: 'white' }));
87
+ }
88
+ const pixelPath = (attributes) => {
89
+ const path = createSvgElement('path', attributes);
90
+ bandPaths.push(path);
91
+ return path;
92
+ };
93
+ // inside = a line twice as wide, clipped to the shape; outside = a line twice as wide, the shape cut out of it
94
+ const edgeLine = (lineWidth) => pixelPath({ fill: 'none', stroke: bandColor, 'stroke-width': lineWidth, 'stroke-linejoin': 'miter' });
95
+ if (band === 'centre') {
96
+ maskElement.append(edgeLine(width));
97
+ }
98
+ else if (band === 'inside') {
99
+ const insideClip = createSvgElement('clipPath', { id: `${id}-inside`, class: 'morphico-band-helper' });
100
+ insideClip.append(pixelPath({}));
101
+ svg.append(insideClip);
102
+ const line = edgeLine(2 * width);
103
+ line.setAttribute('clip-path', `url(#${id}-inside)`);
104
+ maskElement.append(line);
105
+ }
106
+ else {
107
+ // painting black over the inside would only work for luminance masks; a mask cut out of the line works for both
108
+ const outsideMask = createSvgElement('mask', { id: `${id}-outside`, class: 'morphico-band-helper', ...farRegion });
109
+ outsideMask.append(createSvgElement('rect', { x: -FAR, y: -FAR, width: 2 * FAR, height: 2 * FAR, fill: 'white' }), pixelPath({ fill: 'black' }));
110
+ svg.append(outsideMask);
111
+ const line = edgeLine(2 * width);
112
+ line.setAttribute('mask', `url(#${id}-outside)`);
113
+ maskElement.append(line);
114
+ }
115
+ };
116
+ const ownClipPath = element.style.clipPath;
117
+ const ownMask = element.style.mask;
118
+ const applyStyle = () => {
119
+ const mask = target.outline ? `url(#${id}-band)` : ownMask;
120
+ element.style.clipPath = target.outline ? ownClipPath : `url(#${id}-shape)`;
121
+ element.style.mask = mask;
122
+ element.style.setProperty('-webkit-mask', mask);
123
+ };
124
+ // ---- placement and drawing ----
125
+ const restingPlacement = () => ({
126
+ centerX: lengthToPixels(target.x, elementWidth, 'x'),
127
+ centerY: lengthToPixels(target.y, elementHeight, 'y'),
128
+ side: target.size === undefined ? DEFAULT_SIZE_SHARE * Math.min(elementWidth, elementHeight) : lengthToPixels(target.size, elementWidth, 'size'),
129
+ });
130
+ const restingFrame = () => ({ shape: shapesOf(target.set)[target.state], rotation: target.rotation, placement: restingPlacement() });
131
+ /** The shape in element pixels: scaled to its square, turned around the square's centre, moved into place. */
132
+ const toElementPixels = ({ shape, rotation: angle, placement: { centerX, centerY, side } }) => {
133
+ const scale = side / GRID_SIZE;
134
+ const cos = Math.cos(angle * DEGREE), sin = Math.sin(angle * DEGREE);
135
+ const pixels = [];
136
+ for (let index = 0; index < shape.length; index += 2) {
137
+ const offsetX = (shape[index] - GRID_CENTER) * scale, offsetY = (shape[index + 1] - GRID_CENTER) * scale;
138
+ pixels.push(centerX + offsetX * cos - offsetY * sin, centerY + offsetX * sin + offsetY * cos);
139
+ }
140
+ return pixels;
141
+ };
142
+ const render = () => {
143
+ if (!elementWidth || !elementHeight)
144
+ return;
145
+ const pixels = toElementPixels(frame ?? restingFrame());
146
+ if (target.outline) {
147
+ const pathData = toPathData(pixels, pieceLength);
148
+ for (const path of bandPaths)
149
+ path.setAttribute('d', pathData);
150
+ }
151
+ else {
152
+ // objectBoundingBox: 0…1 of the element's width / height
153
+ const boxUnits = pixels.map((value, index) => value / (index % 2 ? elementHeight : elementWidth));
154
+ // inverted: a rectangle far around the element with the shape as a hole in it (clip-rule evenodd)
155
+ const surrounding = target.inverted ? INVERTED_SURROUNDING : '';
156
+ clipShape.setAttribute('d', surrounding + toPathData(boxUnits, pieceLength));
157
+ }
158
+ };
159
+ const measure = (width, height) => {
160
+ elementWidth = width;
161
+ elementHeight = height;
162
+ render();
163
+ };
164
+ // ---- changes ----
165
+ /** Ends the running change and resolves everyone waiting for it. */
166
+ const finish = (interrupted) => {
167
+ if (!running)
168
+ return;
169
+ const { stopAnimation, resolvers } = running;
170
+ running = null;
171
+ stopAnimation();
172
+ for (const resolve of resolvers)
173
+ resolve({ state: target.state, interrupted });
174
+ };
175
+ /** Updates the target (checked first, so a wrong value throws right away, not in an animation frame). */
176
+ const applyChanges = (changes) => {
177
+ for (const name of ['x', 'y', 'size']) {
178
+ if (changes[name] !== undefined)
179
+ lengthToPixels(changes[name], 1, name);
180
+ }
181
+ if (changes.state !== undefined)
182
+ target.state = checkedState(target.set, changes.state);
183
+ if (changes.roundness !== undefined && changes.roundness !== target.roundness) {
184
+ target.roundness = changes.roundness;
185
+ target.set = resolveIconSet(clipShapes, changes.roundness);
186
+ }
187
+ if (changes.x !== undefined)
188
+ target.x = changes.x;
189
+ if (changes.y !== undefined)
190
+ target.y = changes.y;
191
+ if (changes.size !== undefined)
192
+ target.size = changes.size;
193
+ if (changes.rotation !== undefined)
194
+ target.rotation = changes.rotation;
195
+ if (changes.outline !== undefined || changes.inverted !== undefined) {
196
+ if (changes.outline !== undefined)
197
+ target.outline = checkedOutline(changes.outline);
198
+ if (changes.inverted !== undefined)
199
+ target.inverted = changes.inverted;
200
+ buildBand();
201
+ applyStyle();
202
+ }
203
+ };
204
+ const change = (changes, morphOptions) => {
205
+ const settled = !running;
206
+ finish(true);
207
+ const previous = { state: target.state, set: target.set };
208
+ const from = frame ?? restingFrame();
209
+ applyChanges(changes);
210
+ const { duration = DEFAULT_DURATION, easing = 'easeInOutCubic' } = morphOptions;
211
+ if (duration <= 0 || prefersReducedMotion() || !elementWidth || !elementHeight) {
212
+ frame = null;
213
+ render();
214
+ return Promise.resolve({ state: target.state, interrupted: false });
215
+ }
216
+ // settled: both sides use the pair's layouts; interrupted: start from the shape on screen
217
+ const fromShape = settled
218
+ ? shapeForPair(previous.set, shapesOf(previous.set), previous.state, target.state) : from.shape;
219
+ const toShape = shapeForPair(target.set, shapesOf(target.set), target.state, previous.state);
220
+ const to = restingPlacement();
221
+ const ease = typeof easing === 'function' ? easing : easings[easing];
222
+ const startTime = performance.now();
223
+ return new Promise((resolve) => {
224
+ const stopAnimation = animate((frameTime) => {
225
+ const progress = clampToUnit((frameTime - startTime) / duration);
226
+ if (progress >= 1) {
227
+ frame = null;
228
+ render();
229
+ finish(false);
230
+ return false;
231
+ }
232
+ const easedProgress = ease(progress);
233
+ const between = (start, end) => start + (end - start) * easedProgress;
234
+ frame = {
235
+ shape: interpolate(fromShape, toShape, easedProgress),
236
+ rotation: between(from.rotation, target.rotation),
237
+ placement: {
238
+ centerX: between(from.placement.centerX, to.centerX),
239
+ centerY: between(from.placement.centerY, to.centerY),
240
+ side: between(from.placement.side, to.side),
241
+ },
242
+ };
243
+ render();
244
+ return true;
245
+ });
246
+ running = { stopAnimation, resolvers: [resolve] };
247
+ });
248
+ };
249
+ // ---- start ----
250
+ const root = element.getRootNode();
251
+ // inside a shadow root, url(#id) only finds ids of that root
252
+ (root instanceof ShadowRoot ? root : document.body).append(svg);
253
+ buildBand();
254
+ applyStyle();
255
+ const box = element.getBoundingClientRect();
256
+ measure(box.width, box.height);
257
+ const resizeObserver = typeof ResizeObserver === 'function'
258
+ ? new ResizeObserver(([entry]) => {
259
+ const borderBox = entry.borderBoxSize?.[0];
260
+ if (borderBox)
261
+ measure(borderBox.inlineSize, borderBox.blockSize);
262
+ else
263
+ measure(entry.contentRect.width, entry.contentRect.height);
264
+ })
265
+ : null;
266
+ resizeObserver?.observe(element);
267
+ return {
268
+ to(stateOrChanges, options = {}) {
269
+ const { onEnd, duration, easing, ...changes } = typeof stateOrChanges === 'string'
270
+ ? { ...options, state: stateOrChanges } : stateOrChanges;
271
+ const result = change(changes, { ...defaultMorphOptions, ...(duration !== undefined && { duration }), ...(easing && { easing }) });
272
+ if (onEnd)
273
+ result.then(onEnd);
274
+ return result;
275
+ },
276
+ destroy() {
277
+ finish(true);
278
+ resizeObserver?.disconnect();
279
+ svg.remove();
280
+ element.style.clipPath = ownClipPath;
281
+ element.style.mask = ownMask;
282
+ element.style.setProperty('-webkit-mask', ownMask);
283
+ },
284
+ };
285
+ };
@@ -0,0 +1,25 @@
1
+ /*! morphico v0.6.0 | MIT License, Copyright (c) 2026 Raycho Ivanov (see LICENSE) */
2
+ // Animation engine: easings and one shared requestAnimationFrame loop for every running morph.
3
+ // The loop only runs while something moves; nothing touches the DOM at import time (SSR-safe).
4
+ export const easings = {
5
+ linear: (progress) => progress,
6
+ easeInOutCubic: (progress) => (progress < 0.5 ? 4 * progress ** 3 : 1 - (-2 * progress + 2) ** 3 / 2),
7
+ easeOutBack: (progress) => 1 + 2.70158 * (progress - 1) ** 3 + 1.70158 * (progress - 1) ** 2,
8
+ easeOutElastic: (progress) => (progress === 0 || progress === 1
9
+ ? progress
10
+ : 2 ** (-10 * progress) * Math.sin((progress * 10 - 0.75) * ((2 * Math.PI) / 3)) + 1),
11
+ };
12
+ const frameCallbacks = new Set();
13
+ let animationFrameId = 0;
14
+ const runFrame = (frameTime) => {
15
+ for (const callback of frameCallbacks)
16
+ if (!callback(frameTime))
17
+ frameCallbacks.delete(callback);
18
+ animationFrameId = frameCallbacks.size ? requestAnimationFrame(runFrame) : 0;
19
+ };
20
+ /** Adds a callback to the shared loop. Returns a function that removes it again. */
21
+ export const animate = (onFrame) => {
22
+ frameCallbacks.add(onFrame);
23
+ animationFrameId ||= requestAnimationFrame(runFrame);
24
+ return () => { frameCallbacks.delete(onFrame); };
25
+ };
@@ -0,0 +1,152 @@
1
+ /*! morphico v0.6.0 | MIT License, Copyright (c) 2026 Raycho Ivanov (see LICENSE) */
2
+ // Layer 4: a face that morphs between feelings. 7 soft filled pieces (sets/faces.ts) — brows, eyes and mouth in the
3
+ // CSS color, the pupils in their own color and clipped to the eyes. Blinking runs on top of any expression, by itself
4
+ // every few seconds (option) or on blink().
5
+ import { animate, easings } from './engine.js';
6
+ import { DEFAULT_DURATION, prefersReducedMotion } from './morph.js';
7
+ import { blinked, faceExpressionNames, faceExpressionPieces, facePaths, interpolateFace } from './sets/faces.js';
8
+ import { checkedInit } from './roundness.js';
9
+ import { createSvgElement } from './svg.js';
10
+ const BLINK_CLOSING = 90;
11
+ const BLINK_SHUT = 50;
12
+ const BLINK_OPENING = 150;
13
+ const AUTO_BLINK_MIN_PAUSE = 2500;
14
+ const AUTO_BLINK_EXTRA_PAUSE = 3500;
15
+ /** Expressions whose eyes are already shut: blinking does nothing. */
16
+ const EYES_SHUT = ['asleep', 'laughing'];
17
+ let faceCount = 0;
18
+ const checkedExpression = (state) => {
19
+ if (!faceExpressionNames.includes(state))
20
+ throw new Error(`morphico: face() has no expression "${state}"`);
21
+ return state;
22
+ };
23
+ const resolveEasing = (easing) => (typeof easing === 'function' ? easing : easings[easing ?? 'easeInOutCubic']);
24
+ /** Adds a morphing face (an <svg>) to `element`, showing the expression `init` first. */
25
+ export const face = (element, init, options = {}) => {
26
+ const { pupilColor = 'white', blink: blinksByItself = true, size = '100%', ...defaultMorphOptions } = options;
27
+ const expressions = faceExpressionPieces();
28
+ let state = checkedExpression(checkedInit(init, 'face'));
29
+ let shownPieces = expressions[state];
30
+ let openness = 1;
31
+ const clipId = `morphico-face-${++faceCount}`;
32
+ const svg = createSvgElement('svg', { viewBox: '0 0 24 24', fill: 'currentColor', role: 'img' });
33
+ svg.style.width = size;
34
+ svg.style.height = size;
35
+ svg.style.overflow = 'visible';
36
+ const clipPath = svg.appendChild(createSvgElement('clipPath', { id: clipId }));
37
+ const eyesPath = clipPath.appendChild(createSvgElement('path'));
38
+ const featuresPath = svg.appendChild(createSvgElement('path'));
39
+ const pupilsPath = svg.appendChild(createSvgElement('path', { fill: pupilColor, 'clip-path': `url(#${clipId})` }));
40
+ const render = () => {
41
+ const paths = facePaths(blinked(shownPieces, openness));
42
+ featuresPath.setAttribute('d', paths.features);
43
+ eyesPath.setAttribute('d', paths.eyes);
44
+ pupilsPath.setAttribute('d', paths.pupils);
45
+ };
46
+ const updateLabel = () => svg.setAttribute('aria-label', state);
47
+ render();
48
+ updateLabel();
49
+ element.appendChild(svg);
50
+ // ---- morphing ----
51
+ let morph = null;
52
+ const endMorph = (interrupted) => {
53
+ if (!morph)
54
+ return;
55
+ const { stopAnimation, resolve, state: morphState } = morph;
56
+ morph = null;
57
+ stopAnimation();
58
+ resolve({ state: morphState, interrupted });
59
+ };
60
+ const morphTo = (nextState, morphOptions) => {
61
+ endMorph(true);
62
+ state = nextState;
63
+ updateLabel();
64
+ const fromPieces = shownPieces;
65
+ const toPieces = expressions[nextState];
66
+ const duration = morphOptions.duration ?? DEFAULT_DURATION;
67
+ if (prefersReducedMotion() || duration <= 0) {
68
+ shownPieces = toPieces;
69
+ render();
70
+ return Promise.resolve({ state: nextState, interrupted: false });
71
+ }
72
+ const easing = resolveEasing(morphOptions.easing);
73
+ let startTime = null;
74
+ return new Promise((resolve) => {
75
+ const stopAnimation = animate((frameTime) => {
76
+ startTime ??= frameTime;
77
+ const progress = Math.min((frameTime - startTime) / duration, 1);
78
+ shownPieces = interpolateFace(fromPieces, toPieces, easing(progress));
79
+ render();
80
+ if (progress < 1)
81
+ return true;
82
+ endMorph(false);
83
+ return false;
84
+ });
85
+ morph = { stopAnimation, resolve, state: nextState };
86
+ });
87
+ };
88
+ // ---- blinking ----
89
+ let stopBlink = null;
90
+ let finishBlink = null;
91
+ const endBlink = () => {
92
+ stopBlink?.();
93
+ stopBlink = null;
94
+ if (openness < 1) {
95
+ openness = 1;
96
+ render();
97
+ }
98
+ finishBlink?.();
99
+ finishBlink = null;
100
+ };
101
+ const blink = () => {
102
+ if (EYES_SHUT.includes(state) || prefersReducedMotion())
103
+ return Promise.resolve();
104
+ endBlink();
105
+ let startTime = null;
106
+ return new Promise((resolve) => {
107
+ finishBlink = resolve;
108
+ stopBlink = animate((frameTime) => {
109
+ startTime ??= frameTime;
110
+ const elapsed = frameTime - startTime;
111
+ if (elapsed < BLINK_CLOSING)
112
+ openness = 1 - elapsed / BLINK_CLOSING;
113
+ else if (elapsed < BLINK_CLOSING + BLINK_SHUT)
114
+ openness = 0;
115
+ else
116
+ openness = Math.min((elapsed - BLINK_CLOSING - BLINK_SHUT) / BLINK_OPENING, 1);
117
+ render();
118
+ if (openness < 1 || elapsed < BLINK_CLOSING)
119
+ return true;
120
+ stopBlink = null;
121
+ finishBlink = null;
122
+ resolve();
123
+ return false;
124
+ });
125
+ });
126
+ };
127
+ let autoBlinkTimer;
128
+ const scheduleAutoBlink = () => {
129
+ autoBlinkTimer = setTimeout(() => {
130
+ if (typeof document === 'undefined' || !document.hidden)
131
+ void blink();
132
+ scheduleAutoBlink();
133
+ }, AUTO_BLINK_MIN_PAUSE + Math.random() * AUTO_BLINK_EXTRA_PAUSE);
134
+ };
135
+ if (blinksByItself && !prefersReducedMotion())
136
+ scheduleAutoBlink();
137
+ return {
138
+ to(nextState, { onEnd, ...morphOptions } = {}) {
139
+ const result = morphTo(checkedExpression(nextState), { ...defaultMorphOptions, ...morphOptions });
140
+ if (onEnd)
141
+ result.then(onEnd);
142
+ return result;
143
+ },
144
+ blink,
145
+ destroy() {
146
+ clearTimeout(autoBlinkTimer);
147
+ endMorph(true);
148
+ endBlink();
149
+ svg.remove();
150
+ },
151
+ };
152
+ };