@gridui/text-morph 1.1.2 → 2.1.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.
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
+ // src/text-morph/use-text-morph.ts
2
+ import { useMotionPolicy } from "@gridui/motion/policy";
3
+
1
4
  // src/text-morph/options.ts
2
5
  var validateOptions = (options) => {
3
6
  if (options.duration !== void 0 && (!Number.isFinite(options.duration) || options.duration < 0)) {
@@ -21,6 +24,67 @@ var validateOptions = (options) => {
21
24
  }
22
25
  };
23
26
 
27
+ // src/text-morph/observe-layout.ts
28
+ var observeTextLayout = (layer, refresh) => {
29
+ const document = layer.ownerDocument;
30
+ const view = document.defaultView;
31
+ const signature = () => {
32
+ const style = view.getComputedStyle(layer);
33
+ return [
34
+ style.font,
35
+ style.fontKerning,
36
+ style.fontFeatureSettings,
37
+ style.fontVariationSettings,
38
+ style.fontOpticalSizing,
39
+ style.fontVariantLigatures,
40
+ style.letterSpacing,
41
+ style.wordSpacing,
42
+ style.direction,
43
+ style.unicodeBidi,
44
+ style.writingMode,
45
+ style.textTransform,
46
+ layer.closest("[lang]")?.getAttribute("lang")
47
+ ].join("|");
48
+ };
49
+ let previous = signature();
50
+ let frame = 0;
51
+ let force = false;
52
+ const schedule = (fontChanged = false) => {
53
+ force ||= fontChanged;
54
+ if (frame) {
55
+ return;
56
+ }
57
+ frame = view.requestAnimationFrame(() => {
58
+ frame = 0;
59
+ const next = signature();
60
+ if (force || next !== previous) {
61
+ previous = next;
62
+ refresh();
63
+ }
64
+ force = false;
65
+ });
66
+ };
67
+ const observer = new MutationObserver(() => void schedule());
68
+ for (let ancestor = layer.parentElement; ancestor; ancestor = ancestor.parentElement) {
69
+ observer.observe(ancestor, { attributes: true, attributeFilter: ["class", "style", "lang", "dir", "data-font-profile"] });
70
+ }
71
+ const resize = () => void schedule();
72
+ const fonts = () => void schedule(true);
73
+ view.addEventListener("resize", resize);
74
+ document.fonts.addEventListener("loadingdone", fonts);
75
+ document.fonts.addEventListener("loadingerror", fonts);
76
+ return () => {
77
+ observer.disconnect();
78
+ view.removeEventListener("resize", resize);
79
+ document.fonts.removeEventListener("loadingdone", fonts);
80
+ document.fonts.removeEventListener("loadingerror", fonts);
81
+ view.cancelAnimationFrame(frame);
82
+ };
83
+ };
84
+
85
+ // src/text-morph/transition.ts
86
+ import { readMotionDuration } from "@gridui/motion/policy";
87
+
24
88
  // src/text-morph/segments.ts
25
89
  var MAX_SEGMENTS = 256;
26
90
  var segmentText = (text, locale, numbers = true) => {
@@ -127,6 +191,71 @@ var segmentText = (text, locale, numbers = true) => {
127
191
  return parts;
128
192
  };
129
193
 
194
+ // src/text-morph/exits.ts
195
+ var createMorphExits = (release) => {
196
+ const exits = /* @__PURE__ */ new Set();
197
+ const remove = (element) => {
198
+ for (const child of element.querySelectorAll("*")) {
199
+ exits.delete(child);
200
+ release(child);
201
+ }
202
+ exits.delete(element);
203
+ release(element);
204
+ element.remove();
205
+ };
206
+ return {
207
+ add: (element) => {
208
+ exits.add(element);
209
+ },
210
+ has: (element) => exits.has(element),
211
+ remove,
212
+ trim: (segments) => {
213
+ const budget = Math.min(MAX_SEGMENTS, Math.max(8, segments * 2));
214
+ while (exits.size > budget) {
215
+ remove(exits.values().next().value);
216
+ }
217
+ },
218
+ clear: () => {
219
+ while (exits.size) {
220
+ remove(exits.values().next().value);
221
+ }
222
+ }
223
+ };
224
+ };
225
+
226
+ // src/text-morph/measurement.ts
227
+ var borderBox = (style, axis) => {
228
+ const size = Number.parseFloat(style[axis]);
229
+ if (style.boxSizing === "border-box") {
230
+ return size;
231
+ }
232
+ const edges = axis === "width" ? [style.paddingLeft, style.paddingRight, style.borderLeftWidth, style.borderRightWidth] : [style.paddingTop, style.paddingBottom, style.borderTopWidth, style.borderBottomWidth];
233
+ return size + edges.reduce((sum, edge) => sum + (Number.parseFloat(edge) || 0), 0);
234
+ };
235
+ var measureMorphLayout = (layer, elements, style) => {
236
+ const origin = layer.getBoundingClientRect();
237
+ const width = borderBox(style, "width");
238
+ const height = borderBox(style, "height");
239
+ const scaleX = width > 0 ? origin.width / width : 1;
240
+ const scaleY = height > 0 ? origin.height / height : 1;
241
+ const before = elements.map((element) => {
242
+ const rect = element.getBoundingClientRect();
243
+ const glyph = element.firstElementChild;
244
+ const glyphRect = glyph?.getBoundingClientRect();
245
+ return {
246
+ rect,
247
+ opacity: Number(getComputedStyle(element).opacity),
248
+ glyph: glyph && glyphRect ? {
249
+ element: glyph,
250
+ x: (glyphRect.left - rect.left) / scaleX,
251
+ y: (glyphRect.top - rect.top) / scaleY,
252
+ opacity: Number(getComputedStyle(glyph).opacity)
253
+ } : void 0
254
+ };
255
+ });
256
+ return { origin, scaleX, scaleY, before, em: Number.parseFloat(style.fontSize) };
257
+ };
258
+
130
259
  // src/text-morph/matching.ts
131
260
  var words = (segments) => {
132
261
  const result = [];
@@ -260,11 +389,189 @@ var matchSegments = (previous, next, cursorIndex) => {
260
389
  return matches;
261
390
  };
262
391
 
263
- // src/text-morph/timing.ts
264
- var milliseconds = (value, fallback = 180) => {
265
- const amount = Number.parseFloat(value);
266
- return Number.isFinite(amount) ? Math.max(0, amount * (value.trim().endsWith("ms") ? 1 : 1e3)) : fallback;
392
+ // src/text-morph/motion-state.ts
393
+ import { createSpringValue } from "@gridui/motion";
394
+ var styleProperty = (property) => property === "x" || property === "y" || property === "scale" ? "transform" : property;
395
+ var createMorphMotionState = () => {
396
+ const entries = /* @__PURE__ */ new Map();
397
+ const dirty = /* @__PURE__ */ new Set();
398
+ let scheduled = false;
399
+ let options = {};
400
+ let tempo = 1;
401
+ const restore = (entry) => {
402
+ for (const [property, original] of entry.original) {
403
+ entry.element.style.setProperty(property, original.value, original.priority);
404
+ }
405
+ };
406
+ const flush = () => {
407
+ scheduled = false;
408
+ for (const entry of dirty) {
409
+ const { channels, element } = entry;
410
+ if (channels.x || channels.y || channels.scale) {
411
+ const x = channels.x?.get() ?? 0;
412
+ const y = channels.y?.get() ?? 0;
413
+ const scale = channels.scale?.get() ?? 1;
414
+ element.style.transform = x === 0 && y === 0 && scale === 1 ? "none" : `translate(${x}px, ${y}px) scale(${scale})`;
415
+ }
416
+ if (channels.opacity) {
417
+ element.style.opacity = String(Math.max(0, Math.min(1, channels.opacity.get())));
418
+ }
419
+ if (channels.width) {
420
+ element.style.width = `${Math.max(0, channels.width.get())}px`;
421
+ }
422
+ if (channels.height) {
423
+ element.style.height = `${Math.max(0, channels.height.get())}px`;
424
+ }
425
+ }
426
+ dirty.clear();
427
+ };
428
+ const mark = (entry) => {
429
+ dirty.add(entry);
430
+ if (!scheduled) {
431
+ scheduled = true;
432
+ queueMicrotask(flush);
433
+ }
434
+ };
435
+ const release = (entry) => {
436
+ entry.revision++;
437
+ for (const channel of Object.values(entry.channels)) {
438
+ channel.dispose();
439
+ }
440
+ dirty.delete(entry);
441
+ restore(entry);
442
+ };
443
+ const remove = (element) => {
444
+ const entry = entries.get(element);
445
+ if (!entry) {
446
+ return;
447
+ }
448
+ release(entry);
449
+ entries.delete(element);
450
+ };
451
+ return {
452
+ configure: (next, nextTempo) => {
453
+ if (tempo === nextTempo && options.stiffness === next.stiffness && options.damping === next.damping && options.mass === next.mass && options.precision === next.precision) {
454
+ return;
455
+ }
456
+ options = next;
457
+ tempo = nextTempo;
458
+ for (const entry of entries.values()) {
459
+ for (const channel of Object.values(entry.channels)) {
460
+ channel.configure(options, { tempo, immediate: false });
461
+ }
462
+ }
463
+ },
464
+ flush,
465
+ /** Release owned styles for one synchronous natural-layout measurement batch. */
466
+ prepare: () => {
467
+ flush();
468
+ for (const entry of entries.values()) {
469
+ restore(entry);
470
+ }
471
+ },
472
+ resume: () => {
473
+ for (const entry of entries.values()) {
474
+ if (entry.pending) {
475
+ dirty.add(entry);
476
+ }
477
+ }
478
+ flush();
479
+ },
480
+ to: (element, from, to) => {
481
+ const previous = entries.get(element);
482
+ const properties = Object.keys(to);
483
+ const moving = (property) => Math.abs((from[property] ?? previous?.channels[property]?.get() ?? to[property]) - to[property]) > 1e-4 || Math.abs(previous?.channels[property]?.getVelocity() ?? 0) > 1e-4;
484
+ if (!previous && !properties.some(moving)) {
485
+ return void 0;
486
+ }
487
+ const entry = previous ?? { element, channels: {}, runs: {}, original: /* @__PURE__ */ new Map(), revision: 0, pending: void 0 };
488
+ entries.set(element, entry);
489
+ const revision = ++entry.revision;
490
+ for (const property of properties) {
491
+ const next = to[property];
492
+ const current = from[property] ?? entry.channels[property]?.get() ?? next;
493
+ let channel = entry.channels[property];
494
+ if (!moving(property)) {
495
+ channel?.jump(next);
496
+ delete entry.runs[property];
497
+ continue;
498
+ }
499
+ const owned = styleProperty(property);
500
+ if (!entry.original.has(owned)) {
501
+ entry.original.set(owned, { value: element.style.getPropertyValue(owned), priority: element.style.getPropertyPriority(owned) });
502
+ }
503
+ const velocity = channel?.getVelocity() ?? 0;
504
+ if (!channel) {
505
+ channel = createSpringValue(current, options, { tempo, immediate: false });
506
+ entry.channels[property] = channel;
507
+ channel.subscribe(() => void mark(entry));
508
+ } else {
509
+ channel.jump(current);
510
+ }
511
+ const run = channel.set(next, velocity);
512
+ entry.runs[property] = run;
513
+ void run.then(() => {
514
+ if (entry.runs[property] === run) {
515
+ delete entry.runs[property];
516
+ }
517
+ });
518
+ }
519
+ const runs = Object.values(entry.runs);
520
+ if (!runs.length) {
521
+ entry.pending = void 0;
522
+ dirty.delete(entry);
523
+ restore(entry);
524
+ return void 0;
525
+ }
526
+ mark(entry);
527
+ const pending = Promise.all(runs).then((results) => {
528
+ if (revision !== entry.revision || results.includes("cancelled")) {
529
+ return "cancelled";
530
+ }
531
+ entry.pending = void 0;
532
+ dirty.delete(entry);
533
+ restore(entry);
534
+ return "finished";
535
+ });
536
+ entry.pending = pending;
537
+ return pending;
538
+ },
539
+ pending: () => [...entries.values()].flatMap((entry) => entry.pending ? [entry.pending] : []),
540
+ remove,
541
+ clear: () => {
542
+ for (const entry of entries.values()) {
543
+ release(entry);
544
+ }
545
+ entries.clear();
546
+ }
547
+ };
267
548
  };
549
+ var morphKeyframe = (frame) => ({
550
+ ...frame.opacity === void 0 ? {} : { opacity: frame.opacity },
551
+ ...frame.width === void 0 ? {} : { width: `${frame.width}px` },
552
+ ...frame.height === void 0 ? {} : { height: `${frame.height}px` },
553
+ ...frame.x === void 0 && frame.y === void 0 && frame.scale === void 0 ? {} : {
554
+ transform: (frame.x ?? 0) === 0 && (frame.y ?? 0) === 0 && (frame.scale ?? 1) === 1 ? "none" : `translate(${frame.x ?? 0}px, ${frame.y ?? 0}px) scale(${frame.scale ?? 1})`
555
+ }
556
+ });
557
+
558
+ // src/text-morph/mode.ts
559
+ var resolveTextMorphMode = (text, mode, direction) => {
560
+ if (mode && mode !== "auto") {
561
+ return mode;
562
+ }
563
+ if (direction === "rtl" || /[\u200e\u200f\u202a-\u202e\u2066-\u2069]/u.test(text)) {
564
+ return "text";
565
+ }
566
+ for (const character of text) {
567
+ if (/\p{Letter}/u.test(character) && !/[\p{Script=Latin}\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u.test(character)) {
568
+ return "text";
569
+ }
570
+ }
571
+ return "characters";
572
+ };
573
+
574
+ // src/text-morph/timing.ts
268
575
  var springTiming = (spring) => {
269
576
  const { stiffness = 170, damping = 26, mass = 1, precision = 1e-3 } = spring;
270
577
  const frequency = Math.sqrt(stiffness / mass);
@@ -310,66 +617,114 @@ var createTextTransition = (layer) => {
310
617
  let active = null;
311
618
  let revision = 0;
312
619
  let lastText;
620
+ let lastSegmentation;
621
+ let lastPhysical = false;
622
+ let tempo = 1;
313
623
  const animations = /* @__PURE__ */ new Set();
314
- const exits = /* @__PURE__ */ new Set();
315
- const motion = layer.ownerDocument.defaultView?.matchMedia("(prefers-reduced-motion: reduce)");
316
- let respectReducedMotion = true;
317
- const settle = () => {
624
+ const motion = createMorphMotionState();
625
+ const exits = createMorphExits(motion.remove);
626
+ const remove = exits.remove;
627
+ const cancelRun = () => {
318
628
  revision++;
319
629
  const previous = active;
320
630
  active = null;
631
+ previous?.cancel?.();
632
+ };
633
+ const settle = () => {
634
+ cancelRun();
321
635
  for (const animation of animations) {
322
636
  animation.cancel();
323
637
  }
324
638
  animations.clear();
325
- for (const element of exits) {
326
- element.remove();
327
- }
639
+ motion.clear();
328
640
  exits.clear();
329
- previous?.cancel?.();
330
641
  };
331
- const onMotionChange = () => {
332
- if (respectReducedMotion && motion?.matches) {
642
+ let currentOptions = {};
643
+ const update = (text, options) => {
644
+ currentOptions = options;
645
+ const style = getComputedStyle(layer);
646
+ const mode = resolveTextMorphMode(text, options.mode, style.direction);
647
+ const nextTempo = options.tempo ?? 1;
648
+ if (nextTempo !== tempo) {
649
+ tempo = nextTempo;
650
+ for (const animation of animations) {
651
+ animation.updatePlaybackRate(1 / tempo);
652
+ }
653
+ }
654
+ const springOptions = typeof options.ease === "object" ? options.ease : void 0;
655
+ const physical = springOptions !== void 0 && options.duration === void 0;
656
+ if (physical !== lastPhysical) {
333
657
  settle();
658
+ lastPhysical = physical;
659
+ }
660
+ if (physical) {
661
+ motion.configure({
662
+ stiffness: springOptions.stiffness ?? 170,
663
+ damping: springOptions.damping ?? 26,
664
+ mass: springOptions.mass ?? 1,
665
+ precision: springOptions.precision ?? 1e-3
666
+ }, tempo);
667
+ }
668
+ const numbers = options.cursorIndex === void 0 && options.numbers !== false;
669
+ const segmentationChanged = lastSegmentation !== void 0 && (lastSegmentation.locale !== options.locale || lastSegmentation.numbers !== numbers || lastSegmentation.mode !== mode);
670
+ lastSegmentation = { locale: options.locale, numbers, mode };
671
+ if (segmentationChanged) {
672
+ settle();
673
+ layer.replaceChildren();
674
+ items = [];
675
+ initialized = false;
334
676
  }
335
- };
336
- motion?.addEventListener("change", onMotionChange);
337
- const update = (text, options) => {
338
- respectReducedMotion = options.respectReducedMotion !== false;
339
- const reduced = respectReducedMotion && motion?.matches;
340
- if (text === lastText) {
341
- if (options.disabled || reduced || options.duration === 0) {
677
+ if (text === lastText && !segmentationChanged) {
678
+ if (options.disabled || options.duration === 0) {
342
679
  settle();
343
680
  }
344
681
  return;
345
682
  }
346
683
  lastText = text;
347
- const segments = segmentText(text, options.locale, options.cursorIndex === void 0 && options.numbers !== false);
348
- const style = getComputedStyle(layer);
349
- const spring = typeof options.ease === "object" ? springTiming(options.ease) : void 0;
350
- const duration = options.duration ?? spring?.duration ?? milliseconds(style.getPropertyValue("--gridui-motion-duration-normal"));
351
- const animate = initialized && !options.disabled && !reduced && duration > 0 && typeof layer.animate === "function" && segments.length <= MAX_SEGMENTS && items.length <= MAX_SEGMENTS;
352
- const origin = layer.getBoundingClientRect();
353
- const scaleX = layer.offsetWidth ? origin.width / layer.offsetWidth : 1;
354
- const scaleY = layer.offsetHeight ? origin.height / layer.offsetHeight : 1;
355
- const before = animate ? items.map(({ element }) => {
356
- return {
357
- rect: element.getBoundingClientRect(),
358
- opacity: getComputedStyle(element).opacity
359
- };
360
- }) : [];
361
- settle();
362
- const requestedEase = typeof options.ease === "string" ? options.ease : spring?.easing;
684
+ const segments = mode === "text" ? [{ text }] : segmentText(text, options.locale, numbers);
685
+ layer.dataset.mode = mode;
686
+ const sampled = !physical && springOptions ? springTiming(springOptions) : void 0;
687
+ const duration = options.duration ?? sampled?.duration ?? readMotionDuration(layer);
688
+ const animate = initialized && !options.disabled && (physical || duration > 0) && typeof layer.animate === "function" && segments.length <= MAX_SEGMENTS && items.length <= MAX_SEGMENTS;
689
+ motion.flush();
690
+ const { origin, scaleX, scaleY, em, before } = measureMorphLayout(
691
+ layer,
692
+ animate ? items.map((item) => item.element) : [],
693
+ style
694
+ );
695
+ if (physical && animate) {
696
+ cancelRun();
697
+ motion.prepare();
698
+ } else {
699
+ settle();
700
+ }
701
+ if (segments.length > MAX_SEGMENTS) {
702
+ layer.textContent = text;
703
+ items = [];
704
+ initialized = false;
705
+ return;
706
+ }
707
+ const requestedEase = typeof options.ease === "string" ? options.ease : sampled?.easing;
363
708
  const fallbackEase = style.getPropertyValue("--gridui-motion-ease-out").trim() || "ease-out";
364
709
  const easing = requestedEase && CSS.supports("animation-timing-function", requestedEase) ? requestedEase : fallbackEase;
365
- const timing = {
366
- duration,
367
- easing
368
- };
369
710
  const currentRevision = revision;
370
711
  const pending = [];
371
- const play = (element, frames, done) => {
372
- const animation = element.animate(frames, timing);
712
+ const play = (element, from, to, done) => {
713
+ if (physical) {
714
+ const run = motion.to(element, from, to);
715
+ if (run) {
716
+ void run.then((result) => {
717
+ if (result === "finished") {
718
+ done?.();
719
+ }
720
+ });
721
+ } else {
722
+ done?.();
723
+ }
724
+ return;
725
+ }
726
+ const animation = element.animate([morphKeyframe(from), morphKeyframe(to)], { duration, easing });
727
+ animation.playbackRate = 1 / tempo;
373
728
  animations.add(animation);
374
729
  pending.push(animation.finished);
375
730
  void animation.finished.then(() => {
@@ -379,15 +734,7 @@ var createTextTransition = (layer) => {
379
734
  animations.delete(animation);
380
735
  });
381
736
  };
382
- if (segments.length > MAX_SEGMENTS) {
383
- layer.textContent = text;
384
- items = [];
385
- initialized = false;
386
- return;
387
- }
388
- const matches = matchSegments(items.map((item) => {
389
- return item.segment;
390
- }), segments, options.cursorIndex);
737
+ const matches = matchSegments(items.map((item) => item.segment), segments, options.cursorIndex);
391
738
  const retained = new Set(matches.values());
392
739
  items.forEach((item, index) => {
393
740
  if (retained.has(index)) {
@@ -395,7 +742,7 @@ var createTextTransition = (layer) => {
395
742
  }
396
743
  const box = before[index];
397
744
  if (!animate || !box || item.segment.text === "\n") {
398
- item.element.remove();
745
+ remove(item.element);
399
746
  return;
400
747
  }
401
748
  item.element.style.position = "absolute";
@@ -404,6 +751,7 @@ var createTextTransition = (layer) => {
404
751
  exits.add(item.element);
405
752
  });
406
753
  if (!items.length) {
754
+ exits.clear();
407
755
  layer.replaceChildren();
408
756
  }
409
757
  const next = segments.map((segment, index) => {
@@ -416,17 +764,15 @@ var createTextTransition = (layer) => {
416
764
  const glyph = layer.ownerDocument.createElement("span");
417
765
  glyph.className = "gridui-text-morph-glyph";
418
766
  glyph.textContent = segment.text;
419
- element.replaceChildren(glyph);
767
+ const outgoing = physical ? Array.from(element.children).filter((child) => exits.has(child)) : [];
768
+ element.replaceChildren(glyph, ...outgoing);
420
769
  } else {
421
770
  element.textContent = segment.text === "\n" ? "" : segment.text;
422
771
  }
423
772
  }
424
773
  element.dataset.digit = String(segment.kind === "digit");
425
774
  element.dataset.kind = segment.kind ?? "text";
426
- return {
427
- segment,
428
- element
429
- };
775
+ return { segment, element };
430
776
  });
431
777
  let cursor = layer.firstChild;
432
778
  for (const { element } of next) {
@@ -437,21 +783,14 @@ var createTextTransition = (layer) => {
437
783
  }
438
784
  }
439
785
  if (animate) {
440
- const after = next.map(({ element }) => {
441
- return element.getBoundingClientRect();
442
- });
786
+ const after = next.map(({ element }) => element.getBoundingClientRect());
443
787
  const destination = layer.getBoundingClientRect();
444
- if (Math.abs(destination.width - origin.width) > 0.1 || Math.abs(destination.height - origin.height) > 0.1) {
445
- play(layer, [
446
- {
447
- width: `${origin.width / scaleX}px`,
448
- height: `${origin.height / scaleY}px`
449
- },
450
- {
451
- width: `${destination.width / scaleX}px`,
452
- height: `${destination.height / scaleY}px`
453
- }
454
- ]);
788
+ if (physical || Math.abs(destination.width - origin.width) > 0.1 || Math.abs(destination.height - origin.height) > 0.1) {
789
+ play(
790
+ layer,
791
+ { width: origin.width / scaleX, height: origin.height / scaleY },
792
+ { width: destination.width / scaleX, height: destination.height / scaleY }
793
+ );
455
794
  }
456
795
  next.forEach((item, index) => {
457
796
  if (item.segment.text === "\n") {
@@ -464,7 +803,7 @@ var createTextTransition = (layer) => {
464
803
  const x = (box.rect.left - after[index].left) / scaleX;
465
804
  const y = (box.rect.top - after[index].top) / scaleY;
466
805
  if (previous.segment.text !== item.segment.text && item.segment.place !== void 0) {
467
- const outgoing = layer.ownerDocument.createElement("span");
806
+ const outgoing = physical && box.glyph ? box.glyph.element : layer.ownerDocument.createElement("span");
468
807
  outgoing.className = "gridui-text-morph-glyph";
469
808
  outgoing.textContent = previous.segment.text;
470
809
  outgoing.style.position = "absolute";
@@ -472,76 +811,49 @@ var createTextTransition = (layer) => {
472
811
  outgoing.style.top = "0";
473
812
  const incoming = item.element.firstElementChild;
474
813
  item.element.append(outgoing);
475
- if (Math.abs(x) > 0.1 || Math.abs(y) > 0.1) {
476
- play(item.element, [
477
- { transform: `translate(${x}px, ${y}px)` },
478
- { transform: "none" }
479
- ]);
814
+ if (physical || Math.abs(x) > 0.1 || Math.abs(y) > 0.1) {
815
+ play(item.element, { x, y }, { x: 0, y: 0 });
480
816
  }
481
817
  exits.add(outgoing);
482
- play(outgoing, [
483
- {
484
- opacity: box.opacity,
485
- transform: "translateY(0)"
486
- },
487
- {
488
- opacity: 0,
489
- transform: "translateY(-0.6em)"
490
- }
491
- ], () => {
492
- outgoing.remove();
493
- exits.delete(outgoing);
494
- });
495
- play(incoming, [
496
- {
497
- opacity: 0,
498
- transform: "translateY(0.6em)"
499
- },
500
- {
501
- opacity: 1,
502
- transform: "none"
503
- }
504
- ]);
505
- } else if (Math.abs(x) > 0.1 || Math.abs(y) > 0.1 || Number(box.opacity) < 1) {
506
- play(item.element, [
507
- {
508
- transform: `translate(${x}px, ${y}px)`,
509
- opacity: box.opacity
510
- },
511
- {
512
- transform: "none",
513
- opacity: 1
514
- }
515
- ]);
818
+ play(
819
+ outgoing,
820
+ { opacity: box.glyph?.opacity ?? box.opacity, x: box.glyph?.x ?? 0, y: box.glyph?.y ?? 0 },
821
+ { opacity: 0, x: 0, y: -0.6 * em },
822
+ () => void remove(outgoing)
823
+ );
824
+ play(incoming, { opacity: 0, y: 0.6 * em }, { opacity: 1, y: 0 });
825
+ } else {
826
+ if (box.glyph && item.element.firstElementChild && (physical || Math.abs(box.glyph.x) > 0.1 || Math.abs(box.glyph.y) > 0.1 || box.glyph.opacity < 1)) {
827
+ play(
828
+ item.element.firstElementChild,
829
+ { opacity: box.glyph.opacity, x: box.glyph.x, y: box.glyph.y },
830
+ { opacity: 1, x: 0, y: 0 }
831
+ );
832
+ }
833
+ if (physical || Math.abs(x) > 0.1 || Math.abs(y) > 0.1 || box.opacity < 1) {
834
+ play(item.element, { x, y, opacity: box.opacity }, { x: 0, y: 0, opacity: 1 });
835
+ }
516
836
  }
517
837
  } else {
518
- play(item.element, [
519
- {
520
- opacity: 0,
521
- transform: "translateY(0.3em)"
522
- },
523
- {
524
- opacity: 1,
525
- transform: "none"
526
- }
527
- ]);
838
+ play(item.element, { opacity: 0, y: mode === "text" ? 0 : 0.3 * em }, { opacity: 1, y: 0 });
528
839
  }
529
840
  });
530
841
  items.forEach((item, index) => {
531
842
  if (exits.has(item.element)) {
532
- play(item.element, [
533
- { opacity: before[index].opacity },
534
- {
535
- opacity: 0,
536
- transform: options.scale ? "scale(0.7)" : "none"
537
- }
538
- ], () => {
539
- item.element.remove();
540
- exits.delete(item.element);
541
- });
843
+ play(
844
+ item.element,
845
+ { opacity: before[index].opacity, x: 0, y: 0, scale: 1 },
846
+ { opacity: 0, x: 0, y: 0, scale: options.scale ? 0.7 : 1 },
847
+ () => void remove(item.element)
848
+ );
542
849
  }
543
850
  });
544
851
  }
852
+ if (physical) {
853
+ exits.trim(segments.length);
854
+ motion.resume();
855
+ pending.push(...motion.pending());
856
+ }
545
857
  items = next;
546
858
  initialized = true;
547
859
  if (pending.length) {
@@ -557,9 +869,20 @@ var createTextTransition = (layer) => {
557
869
  };
558
870
  return {
559
871
  update,
872
+ refresh: () => {
873
+ const text = lastText;
874
+ if (text === void 0) {
875
+ return;
876
+ }
877
+ settle();
878
+ layer.replaceChildren();
879
+ items = [];
880
+ initialized = false;
881
+ lastText = void 0;
882
+ update(text, currentOptions);
883
+ },
560
884
  destroy: () => {
561
885
  settle();
562
- motion?.removeEventListener("change", onMotionChange);
563
886
  layer.replaceChildren();
564
887
  }
565
888
  };
@@ -568,21 +891,27 @@ var createTextTransition = (layer) => {
568
891
  // src/text-morph/use-text-morph.ts
569
892
  import { useCallback, useLayoutEffect, useRef } from "react";
570
893
  var useTextMorph = (value, options = {}) => {
894
+ const policy = useMotionPolicy();
571
895
  validateOptions(options);
572
896
  const text = typeof value === "number" ? new Intl.NumberFormat(options.locale, options.formatOptions).format(value) : value;
573
897
  const latest = useRef(options);
574
898
  const transition = useRef(null);
575
899
  const element = useRef(null);
900
+ const stopObserving = useRef(null);
576
901
  const layerRef = useCallback((layer) => {
902
+ stopObserving.current?.();
577
903
  transition.current?.destroy();
578
904
  element.current?.parentElement?.removeAttribute("data-enhanced");
579
905
  element.current = layer;
580
906
  transition.current = layer ? createTextTransition(layer) : null;
907
+ stopObserving.current = layer ? observeTextLayout(layer, () => transition.current?.refresh()) : null;
581
908
  }, []);
582
909
  useLayoutEffect(() => {
583
910
  latest.current = options;
584
911
  transition.current?.update(text, {
585
912
  ...options,
913
+ disabled: options.disabled || policy.immediate,
914
+ tempo: policy.tempo,
586
915
  onAnimationStart: () => {
587
916
  latest.current.onAnimationStart?.();
588
917
  },
@@ -621,6 +950,7 @@ var TextMorph = (props) => {
621
950
  locale,
622
951
  formatOptions,
623
952
  numbers,
953
+ mode,
624
954
  cursorIndex,
625
955
  disabled,
626
956
  respectReducedMotion,
@@ -638,6 +968,7 @@ var TextMorph = (props) => {
638
968
  locale,
639
969
  formatOptions,
640
970
  numbers,
971
+ mode,
641
972
  cursorIndex,
642
973
  disabled,
643
974
  respectReducedMotion,