@brightlocal/ui-components 1.3.0 → 1.4.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.
@@ -27,6 +27,21 @@ export interface InputListProps {
27
27
  * Called when the list of items changes.
28
28
  */
29
29
  onValueChange: (value: string[]) => void;
30
+ /**
31
+ * Called before items are added to the list.
32
+ * Return `true` to allow the addition, or a `string` to block it
33
+ * and display that string as an error message.
34
+ * The input value is preserved when addition is blocked.
35
+ * @example
36
+ * ```tsx
37
+ * onBeforeAdd={(newItems, current) => {
38
+ * const existing = new Set(current.map((k) => k.toLowerCase()));
39
+ * const hasDupe = newItems.some((item) => existing.has(item.toLowerCase()));
40
+ * return hasDupe ? "Keyword already added" : true;
41
+ * }}
42
+ * ```
43
+ */
44
+ onBeforeAdd?: (newItems: string[], currentValue: string[]) => true | string;
30
45
  /**
31
46
  * Placeholder text for the text input.
32
47
  * @default "Add item"
@@ -98,6 +113,7 @@ export interface InputListProps {
98
113
  function InputList({
99
114
  value,
100
115
  onValueChange,
116
+ onBeforeAdd,
101
117
  placeholder = "Add item",
102
118
  addButtonLabel = "Add",
103
119
  skeletonCount = 3,
@@ -112,6 +128,9 @@ function InputList({
112
128
  className,
113
129
  }: InputListProps) {
114
130
  const [inputValue, setInputValue] = React.useState("");
131
+ const [validationError, setValidationError] = React.useState<string | null>(
132
+ null
133
+ );
115
134
 
116
135
  // Stable keys so AnimatePresence can track items across additions/removals
117
136
  const nextIdRef = React.useRef(value.length);
@@ -147,6 +166,16 @@ function InputList({
147
166
  (items: string[]) => {
148
167
  const toAdd = items.map((s) => s.trim()).filter(Boolean);
149
168
  if (!toAdd.length) return;
169
+
170
+ if (onBeforeAdd) {
171
+ const result = onBeforeAdd(toAdd, value);
172
+ if (result !== true) {
173
+ setValidationError(result);
174
+ return;
175
+ }
176
+ }
177
+
178
+ setValidationError(null);
150
179
  setStableKeys((prev) => [
151
180
  ...prev,
152
181
  ...toAdd.map(() => nextIdRef.current++),
@@ -154,7 +183,7 @@ function InputList({
154
183
  onValueChange([...value, ...toAdd]);
155
184
  setInputValue("");
156
185
  },
157
- [value, onValueChange]
186
+ [value, onValueChange, onBeforeAdd]
158
187
  );
159
188
 
160
189
  const removeItem = React.useCallback(
@@ -265,10 +294,13 @@ function InputList({
265
294
  className="flex-1"
266
295
  dataHook={`${dataHook}-input`}
267
296
  disabled={inputDisabled}
268
- error={error}
297
+ error={error || !!validationError}
269
298
  placeholder={placeholder}
270
299
  value={inputValue}
271
- onChange={(e) => setInputValue(e.target.value)}
300
+ onChange={(e) => {
301
+ setInputValue(e.target.value);
302
+ if (validationError) setValidationError(null);
303
+ }}
272
304
  onKeyDown={handleKeyDown}
273
305
  onPaste={handlePaste}
274
306
  />
@@ -282,13 +314,13 @@ function InputList({
282
314
  </div>
283
315
 
284
316
  {/* Error message replaces description */}
285
- {error && errorMessage ? (
317
+ {(error && errorMessage) || validationError ? (
286
318
  <FieldError
287
319
  className="text-left"
288
320
  data-slot="input-list-error"
289
321
  dataHook={`${dataHook}-error`}
290
322
  >
291
- {errorMessage}
323
+ {validationError ?? errorMessage}
292
324
  </FieldError>
293
325
  ) : (
294
326
  description && (
@@ -1,9 +1,15 @@
1
1
  "use client";
2
2
 
3
3
  import * as React from "react";
4
- import { useCallback, useEffect, useId, useRef, useState } from "react";
4
+ import {
5
+ useCallback,
6
+ useEffect,
7
+ useId,
8
+ useMemo,
9
+ useRef,
10
+ useState,
11
+ } from "react";
5
12
  import { animate } from "framer-motion";
6
- import { interpolate } from "flubber";
7
13
 
8
14
  import { cn } from "@brightlocal/ui-components/lib/utils";
9
15
  import { usePrefersReducedMotion } from "../hooks/use-prefers-reduced-motion";
@@ -34,6 +40,93 @@ const DEFAULT_SHAPES: string[] = [
34
40
  STAR_PATH,
35
41
  ];
36
42
 
43
+ /** Number of pre-sampled frames for flubber morphs */
44
+ const MORPH_SAMPLES = 30;
45
+
46
+ /** Fewer samples on low-end devices to reduce pre-computation + memory */
47
+ const MORPH_SAMPLES_LOW = 15;
48
+
49
+ /**
50
+ * Detect low-performance devices via hardware concurrency.
51
+ * Falls back to false on SSR or when the API is unavailable.
52
+ */
53
+ const isLowPerfDevice =
54
+ typeof navigator !== "undefined" &&
55
+ typeof navigator.hardwareConcurrency === "number" &&
56
+ navigator.hardwareConcurrency <= 4;
57
+
58
+ // ---------------------------------------------------------------------------
59
+ // rAF-batched DOM write scheduler
60
+ // ---------------------------------------------------------------------------
61
+
62
+ interface FrameState {
63
+ ballX: number;
64
+ clipRight: number;
65
+ rotate: number;
66
+ pathD: string;
67
+ }
68
+
69
+ function createFrameScheduler(
70
+ ball: HTMLDivElement,
71
+ group: SVGGElement,
72
+ path: SVGPathElement
73
+ ) {
74
+ let pending = false;
75
+ let activeItemEl: HTMLSpanElement | null = null;
76
+ const state: FrameState = { ballX: 0, clipRight: 100, rotate: 0, pathD: "" };
77
+
78
+ function flush() {
79
+ pending = false;
80
+ ball.style.transform = `translateX(${state.ballX}px)`;
81
+ if (activeItemEl) {
82
+ activeItemEl.style.clipPath = `inset(0 ${state.clipRight}% 0 0)`;
83
+ }
84
+ group.style.transform = `rotate(${state.rotate}deg)`;
85
+ path.setAttribute("d", state.pathD);
86
+ }
87
+
88
+ function schedule(
89
+ ballX: number,
90
+ clipRight: number,
91
+ rotate: number,
92
+ pathD: string
93
+ ) {
94
+ state.ballX = ballX;
95
+ state.clipRight = clipRight;
96
+ state.rotate = rotate;
97
+ state.pathD = pathD;
98
+ if (!pending) {
99
+ pending = true;
100
+ requestAnimationFrame(flush);
101
+ }
102
+ }
103
+
104
+ /** Update which item element receives clip-path writes */
105
+ schedule.setItem = (el: HTMLSpanElement) => {
106
+ activeItemEl = el;
107
+ };
108
+
109
+ return schedule;
110
+ }
111
+
112
+ // ---------------------------------------------------------------------------
113
+ // rAF-based delay (replaces setTimeout for frame-aligned timing)
114
+ // ---------------------------------------------------------------------------
115
+
116
+ function rafDelay(ms: number, signal: { cancelled: boolean }): Promise<void> {
117
+ return new Promise((resolve) => {
118
+ const start = performance.now();
119
+ function check() {
120
+ if (signal.cancelled || performance.now() - start >= ms) {
121
+ resolve();
122
+ } else {
123
+ requestAnimationFrame(check);
124
+ }
125
+ }
126
+ requestAnimationFrame(check);
127
+ });
128
+ }
129
+
37
130
  // ---------------------------------------------------------------------------
38
131
  // Props
39
132
  // ---------------------------------------------------------------------------
@@ -143,7 +236,10 @@ const TextRevealMotion = React.forwardRef<
143
236
 
144
237
  const reducedMotion = usePrefersReducedMotion();
145
238
  const rawId = useId();
146
- const gradientId = `text-reveal-gradient-${rawId.replace(/:/g, "")}`;
239
+ const gradientId = useMemo(
240
+ () => `text-reveal-gradient-${rawId.replace(/:/g, "")}`,
241
+ [rawId]
242
+ );
147
243
 
148
244
  // Refs for imperative animation
149
245
  const ballRef = useRef<HTMLDivElement>(null);
@@ -151,7 +247,9 @@ const TextRevealMotion = React.forwardRef<
151
247
  const pathRef = useRef<SVGPathElement>(null);
152
248
  const groupRef = useRef<SVGGElement>(null);
153
249
  const gradientElRef = useRef<SVGLinearGradientElement>(null);
154
- const itemRefsMap = useRef<Map<number, HTMLSpanElement>>(new Map());
250
+ const containerRef = useRef<HTMLDivElement>(null);
251
+ const textWrapRef = useRef<HTMLSpanElement>(null);
252
+ const itemRefs = useRef<(HTMLSpanElement | null)[]>([]);
155
253
 
156
254
  const items = React.Children.toArray(children);
157
255
  const [measurements, setMeasurements] = useState<{
@@ -161,40 +259,47 @@ const TextRevealMotion = React.forwardRef<
161
259
  const { widths, ballSize } = measurements;
162
260
 
163
261
  // -----------------------------------------------------------------------
164
- // Collect refs and measure on last mount
262
+ // Collect refs
165
263
  // -----------------------------------------------------------------------
166
264
  const itemRefCallback = useCallback(
167
265
  (index: number) => (el: HTMLSpanElement | null) => {
168
- if (el) {
169
- itemRefsMap.current.set(index, el);
170
- } else {
171
- itemRefsMap.current.delete(index);
172
- }
266
+ itemRefs.current[index] = el;
173
267
  },
174
268
  []
175
269
  );
176
270
 
177
271
  // Measure children widths and font-size after refs are attached.
178
- // setState is deferred via rAF so it runs outside the synchronous
179
- // effect body, satisfying the react-hooks/set-state-in-effect rule.
272
+ // Waits for document.fonts.ready so measurements use the real web
273
+ // font metrics rather than fallback system font widths.
180
274
  useEffect(() => {
181
- if (itemRefsMap.current.size === 0) return;
182
- const raf = requestAnimationFrame(() => {
275
+ if (itemRefs.current.length === 0 || !itemRefs.current[0]) return;
276
+ let cancelled = false;
277
+
278
+ function measure() {
279
+ if (cancelled) return;
183
280
  const w: number[] = [];
184
281
  let fontSize = 32;
185
- itemRefsMap.current.forEach((node, i) => {
282
+ for (let i = 0; i < items.length; i++) {
283
+ const node = itemRefs.current[i];
284
+ if (!node) continue;
186
285
  w[i] = node.scrollWidth;
187
286
  if (i === 0) {
188
- // Read font-size from the actual Typography element, not the wrapper span.
189
- // Ball size = 1.5× font-size for proportional scaling.
190
287
  const textEl = node.firstElementChild ?? node;
191
288
  const fs = parseFloat(getComputedStyle(textEl).fontSize) || 16;
192
289
  fontSize = Math.round(fs * 1.5);
193
290
  }
194
- });
291
+ }
195
292
  setMeasurements({ widths: w, ballSize: fontSize });
293
+ }
294
+
295
+ document.fonts.ready.then(() => {
296
+ if (cancelled) return;
297
+ requestAnimationFrame(measure);
196
298
  });
197
- return () => cancelAnimationFrame(raf);
299
+
300
+ return () => {
301
+ cancelled = true;
302
+ };
198
303
  }, [items.length]);
199
304
 
200
305
  // -----------------------------------------------------------------------
@@ -204,7 +309,6 @@ const TextRevealMotion = React.forwardRef<
204
309
  if (reducedMotion) return;
205
310
  const grad = gradientElRef.current;
206
311
  if (!grad) return;
207
- // Capture as non-null const for use inside rAF closure
208
312
  const gradEl: SVGLinearGradientElement = grad;
209
313
  let raf: number;
210
314
  let start: number | null = null;
@@ -212,14 +316,12 @@ const TextRevealMotion = React.forwardRef<
212
316
  const sB = 0.08 + Math.random() * 0.04;
213
317
  const oA = Math.random() * Math.PI * 2;
214
318
  const oB = Math.random() * Math.PI * 2;
215
- // Track previous values to skip redundant DOM writes
216
319
  let prevAngle = -Infinity;
217
320
  function tick(now: number) {
218
321
  if (!start) start = now;
219
322
  const t = (now - start) / 1000;
220
323
  const angle =
221
324
  Math.sin(t * sA + oA) * Math.PI + Math.sin(t * sB + oB) * 0.5;
222
- // Skip write when angle change is imperceptible (< 0.01 rad ≈ 0.6°)
223
325
  if (Math.abs(angle - prevAngle) > 0.01) {
224
326
  prevAngle = angle;
225
327
  const cos = Math.cos(angle);
@@ -261,75 +363,105 @@ const TextRevealMotion = React.forwardRef<
261
363
  !groupRef.current ||
262
364
  !ballRef.current ||
263
365
  !shimmerRef.current ||
366
+ !containerRef.current ||
367
+ !textWrapRef.current ||
264
368
  widths.length === 0 ||
265
369
  ballSize === 0
266
370
  )
267
371
  return;
268
372
 
269
- // Capture as non-null locals for use inside async closures
270
373
  const path: SVGPathElement = pathRef.current;
271
374
  const group: SVGGElement = groupRef.current;
272
375
  const ball: HTMLDivElement = ballRef.current;
273
376
  const shimmerEl: HTMLDivElement = shimmerRef.current;
377
+ const container: HTMLDivElement = containerRef.current;
378
+ const textWrap: HTMLSpanElement = textWrapRef.current;
379
+
380
+ function resizeToItem(wordW: number) {
381
+ const w = `${wordW}px`;
382
+ container.style.width = w;
383
+ textWrap.style.width = w;
384
+ }
274
385
 
275
386
  if (reducedMotion) {
276
387
  path.setAttribute("d", shapes[0]!);
277
388
  group.style.opacity = "1";
278
- const firstItem = itemRefsMap.current.get(0);
389
+ const firstItem = itemRefs.current[0];
279
390
  if (firstItem) {
280
- firstItem.style.visibility = "visible";
391
+ firstItem.style.opacity = "1";
281
392
  firstItem.style.clipPath = "none";
282
393
  }
283
- const gap0 = ballSize * 0.5;
394
+ resizeToItem(widths[0] ?? 0);
395
+ const gap0 = ballSize * 0.25;
284
396
  const endX0 = (widths[0] ?? 0) + gap0 + ballSize / 2;
285
397
  ball.style.transform = `translateX(${endX0}px)`;
286
398
  return;
287
399
  }
288
400
 
289
- let cancelled = false;
290
- // Equal visual gap between ball edge and text edge on both sides
291
- const gap = ballSize * 0.5;
292
-
293
- // Precompute all flubber interpolators — avoids expensive SVG path
294
- // parsing inside the animation loop.
295
- const interpCache: ((t: number) => string)[] = [];
296
- for (let i = 0; i < shapes.length; i++) {
297
- interpCache.push(
298
- interpolate(shapes[i]!, shapes[(i + 1) % shapes.length]!)
299
- );
300
- }
401
+ const signal = { cancelled: false };
402
+ const gap = ballSize * 0.25;
301
403
 
302
404
  async function loop() {
405
+ // Lazy-load flubber so it doesn't block first paint
406
+ const { interpolate } = await import("flubber");
407
+ if (signal.cancelled) return;
408
+
409
+ // Pre-sample all morph transitions into lookup tables.
410
+ // Eliminates per-frame flubber string generation (~50% CPU savings).
411
+ // On low-end devices, halve the sample count to reduce memory + init cost.
412
+ const sampleCount = isLowPerfDevice ? MORPH_SAMPLES_LOW : MORPH_SAMPLES;
413
+ const sampledFrames: string[][] = [];
414
+ for (let i = 0; i < shapes.length; i++) {
415
+ const interp = interpolate(
416
+ shapes[i]!,
417
+ shapes[(i + 1) % shapes.length]!
418
+ );
419
+ const frames: string[] = [];
420
+ for (let j = 0; j <= sampleCount; j++) {
421
+ frames.push(interp(j / sampleCount));
422
+ }
423
+ sampledFrames.push(frames);
424
+ }
425
+
426
+ // Create scheduler once — reuse across all phases and items
427
+ const schedule = createFrameScheduler(ball, group, path);
428
+
303
429
  group.style.opacity = "1";
304
430
  let wordIndex = 0;
305
431
  let shapeStep = 0;
306
432
  let totalRotation = 0;
307
433
 
308
- while (!cancelled) {
434
+ while (!signal.cancelled) {
309
435
  const idx = wordIndex % items.length;
310
436
  const wordW = widths[idx] ?? 0;
311
437
 
312
- // Ball center positions for equal visual gap on both sides
438
+ resizeToItem(wordW);
439
+
313
440
  const startX = -(gap + ballSize / 2);
314
441
  const endX = wordW + gap + ballSize / 2;
315
442
  const travel = endX - startX;
316
443
 
317
- const container = itemRefsMap.current.get(idx);
318
- if (!container) break;
444
+ const itemEl = itemRefs.current[idx];
445
+ if (!itemEl) break;
446
+
447
+ // Point scheduler at the active item for clip-path writes
448
+ schedule.setItem(itemEl);
319
449
 
320
- // Show this item (clipped), hide all others
321
- itemRefsMap.current.forEach((el, i) => {
322
- el.style.visibility = i === idx ? "visible" : "hidden";
450
+ // Show this item (clipped), hide all others via opacity (no layout cost)
451
+ for (let i = 0; i < items.length; i++) {
452
+ const el = itemRefs.current[i];
453
+ if (!el) continue;
454
+ el.style.opacity = i === idx ? "1" : "0";
323
455
  el.style.clipPath = "inset(0 100% 0 0)";
324
- });
456
+ }
325
457
 
326
458
  // Phase 1: Roll right → reveal
327
- const interp1 = interpCache[shapeStep % shapes.length]!;
459
+ const morphFrames1 = sampledFrames[shapeStep % shapes.length]!;
328
460
  const rollDeg = 360;
329
461
  const startRot1 = totalRotation;
330
462
 
331
463
  await new Promise<void>((resolve) => {
332
- if (cancelled) {
464
+ if (signal.cancelled) {
333
465
  resolve();
334
466
  return;
335
467
  }
@@ -339,18 +471,21 @@ const TextRevealMotion = React.forwardRef<
339
471
  damping,
340
472
  mass,
341
473
  onUpdate: (x: number) => {
342
- if (cancelled) {
474
+ if (signal.cancelled) {
343
475
  controls.stop();
344
476
  resolve();
345
477
  return;
346
478
  }
347
- ball.style.transform = `translateX(${x}px)`;
479
+ const t = clamp01((x - startX) / travel);
348
480
  const clipRight =
349
481
  wordW > 0 ? 100 - clamp01(x / wordW) * 100 : 100;
350
- container.style.clipPath = `inset(0 ${clipRight}% 0 0)`;
351
- const t = (x - startX) / travel;
352
- group.style.transform = `rotate(${startRot1 + t * rollDeg}deg)`;
353
- path.setAttribute("d", interp1(clamp01(t)));
482
+ const frameIdx = Math.round(t * sampleCount);
483
+ schedule(
484
+ x,
485
+ clipRight,
486
+ startRot1 + t * rollDeg,
487
+ morphFrames1[frameIdx]!
488
+ );
354
489
  },
355
490
  onComplete: () => {
356
491
  totalRotation = startRot1 + rollDeg;
@@ -360,34 +495,44 @@ const TextRevealMotion = React.forwardRef<
360
495
  });
361
496
  });
362
497
 
363
- if (cancelled) break;
498
+ if (signal.cancelled) break;
364
499
 
365
500
  // Shimmer
366
501
  if (shimmer) {
367
502
  runShimmerEffect(shimmerEl);
368
503
  }
369
504
 
370
- // Hold — identical loop to Default: pause → spring (await full settle)
505
+ // Hold — ball morphs during the pause (batched through scheduler)
371
506
  if (holdTime > 0) {
372
507
  const holdStart = performance.now();
373
- while (!cancelled && performance.now() - holdStart < holdTime) {
374
- await new Promise<void>((r) => setTimeout(r, 300));
375
- if (cancelled || performance.now() - holdStart >= holdTime) break;
508
+ // Capture ball position at end of reveal for hold phase
509
+ const holdBallX = endX;
510
+ while (
511
+ !signal.cancelled &&
512
+ performance.now() - holdStart < holdTime
513
+ ) {
514
+ await rafDelay(300, signal);
515
+ if (signal.cancelled || performance.now() - holdStart >= holdTime)
516
+ break;
376
517
 
377
518
  const nextStep = (shapeStep + 1) % shapes.length;
378
- const interpH = interpCache[shapeStep % shapes.length]!;
519
+ const holdFrames = sampledFrames[shapeStep % shapes.length]!;
379
520
  const startRotH = totalRotation;
380
521
  const targetRotH = totalRotation + 360;
381
522
 
382
- // Await full spring settle — no early stop, same as Default
383
523
  await animate(0, 1, {
384
524
  type: "spring",
385
525
  stiffness: 30,
386
526
  damping: 9,
387
527
  mass: 0.5,
388
528
  onUpdate: (v: number) => {
389
- path.setAttribute("d", interpH(clamp01(v)));
390
- group.style.transform = `rotate(${startRotH + v * (targetRotH - startRotH)}deg)`;
529
+ const frameIdx = Math.round(clamp01(v) * sampleCount);
530
+ schedule(
531
+ holdBallX,
532
+ 0,
533
+ startRotH + v * (targetRotH - startRotH),
534
+ holdFrames[frameIdx]!
535
+ );
391
536
  },
392
537
  });
393
538
 
@@ -395,14 +540,14 @@ const TextRevealMotion = React.forwardRef<
395
540
  shapeStep = nextStep;
396
541
  }
397
542
  }
398
- if (cancelled) break;
543
+ if (signal.cancelled) break;
399
544
 
400
545
  // Phase 2: Roll back left → hide
401
- const interp2 = interpCache[shapeStep % shapes.length]!;
546
+ const morphFrames2 = sampledFrames[shapeStep % shapes.length]!;
402
547
  const startRot2 = totalRotation;
403
548
 
404
549
  await new Promise<void>((resolve) => {
405
- if (cancelled) {
550
+ if (signal.cancelled) {
406
551
  resolve();
407
552
  return;
408
553
  }
@@ -412,18 +557,21 @@ const TextRevealMotion = React.forwardRef<
412
557
  damping,
413
558
  mass,
414
559
  onUpdate: (x: number) => {
415
- if (cancelled) {
560
+ if (signal.cancelled) {
416
561
  controls.stop();
417
562
  resolve();
418
563
  return;
419
564
  }
420
- ball.style.transform = `translateX(${x}px)`;
565
+ const t = clamp01(1 - (x - startX) / travel);
421
566
  const clipRight =
422
567
  wordW > 0 ? 100 - clamp01(x / wordW) * 100 : 100;
423
- container.style.clipPath = `inset(0 ${clipRight}% 0 0)`;
424
- const t = 1 - (x - startX) / travel;
425
- group.style.transform = `rotate(${startRot2 - t * rollDeg}deg)`;
426
- path.setAttribute("d", interp2(clamp01(t)));
568
+ const frameIdx = Math.round(t * sampleCount);
569
+ schedule(
570
+ x,
571
+ clipRight,
572
+ startRot2 - t * rollDeg,
573
+ morphFrames2[frameIdx]!
574
+ );
427
575
  },
428
576
  onComplete: () => {
429
577
  totalRotation = startRot2 - rollDeg;
@@ -433,17 +581,17 @@ const TextRevealMotion = React.forwardRef<
433
581
  });
434
582
  });
435
583
 
436
- if (cancelled) break;
584
+ if (signal.cancelled) break;
437
585
 
438
- // Brief pause between items
439
- await new Promise<void>((r) => setTimeout(r, 300));
586
+ // Brief pause between items (frame-aligned)
587
+ await rafDelay(300, signal);
440
588
  wordIndex++;
441
589
  }
442
590
  }
443
591
 
444
592
  loop();
445
593
  return () => {
446
- cancelled = true;
594
+ signal.cancelled = true;
447
595
  };
448
596
  }, [
449
597
  widths,
@@ -459,7 +607,11 @@ const TextRevealMotion = React.forwardRef<
459
607
  shapes,
460
608
  ]);
461
609
 
462
- const maxWidth = widths.length > 0 ? Math.max(...widths) : 0;
610
+ const maxWidth = useMemo(
611
+ () => (widths.length > 0 ? Math.max(...widths) : 0),
612
+ [widths]
613
+ );
614
+ const ready = widths.length > 0 && ballSize > 0;
463
615
 
464
616
  return (
465
617
  <div
@@ -469,15 +621,27 @@ const TextRevealMotion = React.forwardRef<
469
621
  data-slot="text-reveal"
470
622
  data-tracking-el={trackingEl}
471
623
  data-tracking-label={trackingLabel}
624
+ style={{
625
+ opacity: ready ? 1 : 0,
626
+ transition: "opacity 0.4s ease-out",
627
+ }}
472
628
  {...props}
473
629
  >
474
630
  <div
631
+ ref={containerRef}
475
632
  className="relative flex items-center"
476
- style={{ width: maxWidth || undefined }}
633
+ style={{
634
+ width: maxWidth || undefined,
635
+ transition: "width 0.3s ease-out",
636
+ }}
477
637
  >
478
638
  <span
639
+ ref={textWrapRef}
479
640
  className="relative inline-block overflow-hidden"
480
- style={{ width: maxWidth || undefined }}
641
+ style={{
642
+ width: maxWidth || undefined,
643
+ transition: "width 0.3s ease-out",
644
+ }}
481
645
  >
482
646
  {items.map((child, i) => (
483
647
  <span
@@ -486,9 +650,9 @@ const TextRevealMotion = React.forwardRef<
486
650
  style={{
487
651
  display: "block",
488
652
  whiteSpace: "nowrap",
489
- visibility: "hidden",
653
+ opacity: 0,
490
654
  clipPath: "inset(0 100% 0 0)",
491
- willChange: "clip-path, visibility",
655
+ willChange: "clip-path",
492
656
  ...(i > 0 ? { position: "absolute", top: 0, left: 0 } : {}),
493
657
  }}
494
658
  >
@@ -503,7 +667,7 @@ const TextRevealMotion = React.forwardRef<
503
667
  style={{
504
668
  opacity: 0,
505
669
  transform: "translateX(-100%)",
506
- willChange: "transform, opacity",
670
+ willChange: "transform",
507
671
  background:
508
672
  "linear-gradient(90deg, transparent 0%, color-mix(in srgb, var(--background) 40%, transparent) 40%, color-mix(in srgb, var(--background) 70%, transparent) 50%, color-mix(in srgb, var(--background) 40%, transparent) 60%, transparent 100%)",
509
673
  }}