use-scroll-animate 4.2.0 → 4.3.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.
@@ -1,6 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  var base = require('../chunks/base-CXx7jZ-o.cjs');
4
+ var core = require('../chunks/core-BRIIoKeS.cjs');
5
+ require('./tokens.cjs');
4
6
 
5
7
  var css$5 = "usa-typewriter{white-space:pre-wrap}usa-typewriter .usa-tw-caret{display:inline-block;width:var(--usa-caret-width,0.08em);height:1.05em;margin-left:0.06em;vertical-align:-0.12em;background:var(--usa-caret-color,currentColor);animation:usa-caret 1.06s steps(1) infinite}usa-typewriter[data-typing] .usa-tw-caret{animation:none}usa-typewriter[data-no-cursor] .usa-tw-caret{display:none}@keyframes usa-caret{50%{opacity:0}}@media (prefers-reduced-motion:reduce){usa-typewriter .usa-tw-caret,usa-shimmer-text{animation:none}}";
6
8
 
@@ -121,12 +123,255 @@ function defineTypewriter(tag = 'usa-typewriter') {
121
123
 
122
124
  var css$4 = "usa-split-text .usa-split-word{display:inline-block;white-space:nowrap}usa-split-text .usa-split-unit{display:inline-block;white-space:pre}usa-split-text[data-state=\"hidden\"] .usa-split-unit{opacity:0}usa-split-text[data-state=\"play\"] .usa-split-unit{animation:usa-split-rise var(--usa-split-duration,620ms) cubic-bezier(0.22,1,0.36,1) both;animation-delay:calc(var(--usa-split-delay,0ms) + var(--i,0) * var(--usa-split-stagger,28ms))}usa-split-text[effect=\"fade\"][data-state=\"play\"] .usa-split-unit{animation-name:usa-split-fade}usa-split-text[effect=\"blur\"][data-state=\"play\"] .usa-split-unit{animation-name:usa-split-blur}usa-split-text[effect=\"flip\"][data-state=\"play\"] .usa-split-unit{animation-name:usa-split-flip;transform-origin:50% 100%}usa-split-text[effect=\"pop\"][data-state=\"play\"] .usa-split-unit{animation-name:usa-split-pop;animation-timing-function:cubic-bezier(0.34,1.56,0.64,1)}@keyframes usa-split-rise{from{opacity:0;transform:translate3d(0,0.6em,0)}to{opacity:1;transform:none}}@keyframes usa-split-fade{from{opacity:0}to{opacity:1}}@keyframes usa-split-blur{from{opacity:0;filter:blur(8px)}to{opacity:1;filter:none}}@keyframes usa-split-flip{from{opacity:0;transform:perspective(500px) rotateX(-80deg)}to{opacity:1;transform:none}}@keyframes usa-split-pop{from{opacity:0;transform:scale(0.3)}to{opacity:1;transform:none}}@media (prefers-reduced-motion:reduce){usa-split-text .usa-split-unit{animation:none !important;opacity:1 !important}}";
123
125
 
126
+ const CJK = /[\u2E80-\u2FFF\u3000-\u303F\u3040-\u30FF\u3100-\u312F\u3130-\u318F\u31A0-\u31FF\u3400-\u4DBF\u4E00-\u9FFF\uAC00-\uD7AF\uF900-\uFAFF\uFF00-\uFFEF]/;
127
+ /** Scripts whose letters join (splitting them would break shaping). */
128
+ const JOINING_SCRIPT = /[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/;
129
+ const RTL = /[\u0590-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFF]/;
130
+ const SR = 'position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;border:0';
131
+ function segmenter(locale, granularity) {
132
+ const S = globalThis.Intl?.Segmenter;
133
+ if (typeof S !== 'function')
134
+ return null;
135
+ try {
136
+ return new S(locale || undefined, { granularity });
137
+ }
138
+ catch {
139
+ return null;
140
+ }
141
+ }
142
+ /** Grapheme clusters of `s` (emoji / combining marks stay whole). */
143
+ function graphemes(s, locale) {
144
+ const seg = segmenter(locale, 'grapheme');
145
+ if (seg)
146
+ return Array.from(seg.segment(s), (x) => x.segment);
147
+ return Array.from(s);
148
+ }
149
+ /**
150
+ * Word-ish tokens of `s`, whitespace kept as separate tokens. CJK text is
151
+ * segmented into words with `Intl.Segmenter`, or per character without it.
152
+ */
153
+ function words(s, locale) {
154
+ const seg = segmenter(locale, 'word');
155
+ const out = [];
156
+ if (seg) {
157
+ for (const x of seg.segment(s)) {
158
+ const last = out[out.length - 1];
159
+ // glue punctuation onto the previous word so it never starts a line alone
160
+ if (!x.isWordLike && !/^\s+$/.test(x.segment) && last && !/^\s+$/.test(last))
161
+ out[out.length - 1] = last + x.segment;
162
+ else
163
+ out.push(x.segment);
164
+ }
165
+ return out;
166
+ }
167
+ for (const part of s.split(/(\s+)/)) {
168
+ if (!part)
169
+ continue;
170
+ if (/^\s+$/.test(part) || !CJK.test(part))
171
+ out.push(part);
172
+ else {
173
+ let buf = '';
174
+ for (const ch of Array.from(part)) {
175
+ if (CJK.test(ch)) {
176
+ if (buf)
177
+ out.push(buf), (buf = '');
178
+ out.push(ch);
179
+ }
180
+ else if (/[\p{P}]/u.test(ch) && out.length)
181
+ out[out.length - 1] += ch;
182
+ else
183
+ buf += ch;
184
+ }
185
+ if (buf)
186
+ out.push(buf);
187
+ }
188
+ }
189
+ return out;
190
+ }
191
+ function dirOf(el, text) {
192
+ const attr = el.closest?.('[dir]')?.getAttribute('dir');
193
+ if (attr === 'rtl' || attr === 'ltr')
194
+ return attr;
195
+ try {
196
+ const d = getComputedStyle(el).direction;
197
+ if (d === 'rtl')
198
+ return 'rtl';
199
+ }
200
+ catch {
201
+ /* no layout */
202
+ }
203
+ return RTL.test(text) && !/[A-Za-z]/.test(text.replace(RTL, '')) ? 'rtl' : 'ltr';
204
+ }
205
+ function splitText(el, options = {}) {
206
+ const by = new Set((Array.isArray(options.by) ? options.by : String(options.by ?? 'char').split(/[\s,]+/)).filter(Boolean));
207
+ const cls = options.className || 'usa-split';
208
+ const locale = options.locale || el.closest?.('[lang]')?.getAttribute('lang') || undefined;
209
+ const original = Array.from(el.childNodes).map((n) => n.cloneNode(true));
210
+ const text = el.textContent || '';
211
+ const direction = dirOf(el, text);
212
+ const chars = [];
213
+ const wordEls = [];
214
+ let lines = [];
215
+ const doc = el.ownerDocument;
216
+ const span = (c, t) => {
217
+ const s = doc.createElement('span');
218
+ s.className = c;
219
+ if (t !== undefined)
220
+ s.textContent = t;
221
+ return s;
222
+ };
223
+ const splitNode = (node) => {
224
+ if (node.nodeType === 3) {
225
+ const frag = doc.createDocumentFragment();
226
+ for (const w of words(node.nodeValue || '', locale)) {
227
+ if (/^\s+$/.test(w)) {
228
+ frag.append(doc.createTextNode(w));
229
+ continue;
230
+ }
231
+ const wordEl = span(`${cls}-word`);
232
+ wordEl.style.display = 'inline-block';
233
+ wordEl.style.whiteSpace = 'nowrap';
234
+ wordEl.dataset.index = String(wordEls.length);
235
+ wordEls.push(wordEl);
236
+ // Arabic script joins its letters: keep the word whole (shaping), even in char mode.
237
+ if (by.has('char') && !JOINING_SCRIPT.test(w)) {
238
+ for (const g of graphemes(w, locale)) {
239
+ const c = span(`${cls}-char`, g);
240
+ c.style.display = 'inline-block';
241
+ c.dataset.index = String(chars.length);
242
+ chars.push(c);
243
+ wordEl.append(c);
244
+ }
245
+ }
246
+ else {
247
+ wordEl.textContent = w;
248
+ if (by.has('char')) {
249
+ wordEl.dataset.whole = '';
250
+ chars.push(wordEl);
251
+ }
252
+ }
253
+ frag.append(wordEl);
254
+ }
255
+ node.parentNode.replaceChild(frag, node);
256
+ }
257
+ else if (node.nodeType === 1 && !/^(BR|SCRIPT|STYLE|SVG|IMG)$/i.test(node.tagName)) {
258
+ Array.from(node.childNodes).forEach(splitNode);
259
+ }
260
+ };
261
+ const wrap = doc.createElement('span');
262
+ wrap.setAttribute('aria-hidden', 'true');
263
+ wrap.className = `${cls}-body`;
264
+ original.forEach((n) => wrap.append(n.cloneNode(true)));
265
+ Array.from(wrap.childNodes).forEach(splitNode);
266
+ const sr = span(`${cls}-sr`, text.replace(/\s+/g, ' ').trim());
267
+ sr.setAttribute('style', SR);
268
+ el.replaceChildren(sr, wrap);
269
+ el.setAttribute('data-split', [...by].join(' '));
270
+ if (direction === 'rtl')
271
+ el.setAttribute('data-split-dir', 'rtl');
272
+ const relayout = () => {
273
+ // unwrap old lines
274
+ for (const l of lines)
275
+ l.replaceWith(...Array.from(l.childNodes));
276
+ lines = [];
277
+ if (!by.has('line') || !wordEls.length)
278
+ return lines;
279
+ const groups = [];
280
+ let lastTop = null;
281
+ for (const w of wordEls) {
282
+ const top = Math.round(w.offsetTop);
283
+ if (lastTop === null || Math.abs(top - lastTop) > 2)
284
+ groups.push([]);
285
+ groups[groups.length - 1].push(w);
286
+ lastTop = top;
287
+ }
288
+ groups.forEach((g, i) => {
289
+ // only group words that share a parent (inline markup keeps its words)
290
+ const parent = g[0].parentNode;
291
+ const same = g.filter((w) => w.parentNode === parent);
292
+ const line = span(`${cls}-line`);
293
+ line.style.display = 'inline-block';
294
+ line.dataset.index = String(i);
295
+ parent.insertBefore(line, same[0]);
296
+ let n = same[0];
297
+ const end = same[same.length - 1];
298
+ while (n) {
299
+ const next = n.nextSibling;
300
+ line.append(n);
301
+ if (n === end)
302
+ break;
303
+ n = next;
304
+ }
305
+ // keep the space between lines outside the line box
306
+ lines.push(line);
307
+ });
308
+ return lines;
309
+ };
310
+ relayout();
311
+ return {
312
+ chars,
313
+ words: wordEls,
314
+ get lines() {
315
+ return lines;
316
+ },
317
+ direction,
318
+ relayout,
319
+ revert() {
320
+ el.replaceChildren(...original.map((n) => n.cloneNode(true)));
321
+ el.removeAttribute('data-split');
322
+ el.removeAttribute('data-split-dir');
323
+ },
324
+ };
325
+ }
326
+ /** Order indices `0…n-1` by choreography: from the start, end, center outwards, edges inwards, or random (seeded). */
327
+ function splitOrder(n, from = 'start', seed = 1) {
328
+ const idx = Array.from({ length: n }, (_, i) => i);
329
+ const mid = (n - 1) / 2;
330
+ if (from === 'end')
331
+ return idx.map((i) => n - 1 - i);
332
+ if (from === 'center')
333
+ return idx.map((i) => Math.round(Math.abs(i - mid) * 2) / 2);
334
+ if (from === 'edges')
335
+ return idx.map((i) => Math.round((mid - Math.abs(i - mid)) * 2) / 2);
336
+ if (from === 'random') {
337
+ let s = seed;
338
+ const r = () => ((s = (s * 16807) % 2147483647) / 2147483647);
339
+ const shuffled = idx.slice().sort(() => r() - 0.5);
340
+ const rank = [];
341
+ shuffled.forEach((v, i) => (rank[v] = i));
342
+ return rank;
343
+ }
344
+ return idx;
345
+ }
346
+ /**
347
+ * Split `el` and build a `timeline()` with one step per unit — play it,
348
+ * `scrub()` it with scroll, `reverse()` or `seek()` it.
349
+ *
350
+ * ```ts
351
+ * const { timeline: tl } = splitTimeline(h1, { by: 'char', preset: 'blur', from: 'center' });
352
+ * tl.play();
353
+ * ```
354
+ */
355
+ function splitTimeline(el, options = {}) {
356
+ const split = splitText(el, options);
357
+ const by = Array.isArray(options.by) ? options.by : String(options.by ?? 'char').split(/[\s,]+/);
358
+ const unit = options.unit || (by.includes('char') ? 'char' : by.includes('word') ? 'word' : 'line');
359
+ const units = unit === 'char' ? split.chars : unit === 'word' ? split.words : split.lines;
360
+ const stagger = options.stagger ?? (unit === 'char' ? 30 : unit === 'word' ? 80 : 140);
361
+ const order = splitOrder(units.length, options.from);
362
+ const tl = core.timeline({ defaults: { duration: options.duration ?? 500, easing: options.easing } });
363
+ units.forEach((u, i) => tl.to(u, options.preset || 'fade-up', { at: order[i] * stagger }));
364
+ tl.seek(0);
365
+ return { split, timeline: tl };
366
+ }
367
+
124
368
  function defineSplitText(tag = 'usa-split-text') {
125
369
  return base.defineElement(tag, (Base) => class UsaSplitText extends Base {
126
370
  constructor() {
127
371
  super(...arguments);
128
372
  this._source = null;
129
373
  this._timer = 0;
374
+ this._steps = 0;
130
375
  }
131
376
  static get observedAttributes() {
132
377
  return ['by', 'text'];
@@ -138,28 +383,50 @@ function defineSplitText(tag = 'usa-split-text') {
138
383
  if (this._source === null)
139
384
  this._source = this.getAttribute('text') ?? (this.textContent || '').replace(/\s+/g, ' ').trim();
140
385
  const text = this.getAttribute('text') ?? this._source;
141
- const byWords = this.str('by', 'chars') === 'words';
386
+ const mode = this.str('by', 'chars');
387
+ const byWords = mode !== 'chars';
388
+ const lang = this.closest('[lang]')?.getAttribute('lang') || undefined;
142
389
  const frag = document.createDocumentFragment();
143
390
  frag.append(base.srText(text));
144
- let i = 0;
145
- text.split(' ').forEach((word, w) => {
146
- if (w > 0)
391
+ const units = [];
392
+ for (const word of words(text, lang)) {
393
+ if (/^\s+$/.test(word)) {
147
394
  frag.append(' ');
395
+ continue;
396
+ }
148
397
  const wordEl = document.createElement('span');
149
398
  wordEl.className = 'usa-split-word';
150
399
  wordEl.setAttribute('aria-hidden', 'true');
151
- const parts = byWords ? [word] : Array.from(word);
400
+ const parts = byWords || JOINING_SCRIPT.test(word) ? [word] : graphemes(word, lang);
152
401
  for (const part of parts) {
153
402
  const u = document.createElement('span');
154
403
  u.className = 'usa-split-unit';
155
404
  u.textContent = part;
156
- u.style.setProperty('--i', String(i++));
405
+ units.push(u);
157
406
  wordEl.append(u);
158
407
  }
159
408
  frag.append(wordEl);
160
- });
409
+ }
161
410
  this.replaceChildren(frag);
162
- this.style.setProperty('--usa-split-stagger', `${this.num('stagger', byWords ? 70 : 28)}ms`);
411
+ // cascade order: per unit, or per line for by="lines"
412
+ let rank = units.map((_, k) => k);
413
+ if (mode === 'lines') {
414
+ let line = -1;
415
+ let top = null;
416
+ rank = units.map((u) => {
417
+ const t = Math.round(u.parentElement.offsetTop);
418
+ if (top === null || Math.abs(t - top) > 2)
419
+ line++;
420
+ top = t;
421
+ return line;
422
+ });
423
+ }
424
+ const groups = Math.max(0, ...rank) + 1;
425
+ const order = splitOrder(groups, this.str('from', 'start'));
426
+ units.forEach((u, k) => u.style.setProperty('--i', String(order[rank[k]] ?? 0)));
427
+ const i = Math.max(0, ...units.map((_, k) => order[rank[k]] ?? 0)) + 1;
428
+ this._steps = i;
429
+ this.style.setProperty('--usa-split-stagger', `${this.num('stagger', mode === 'lines' ? 140 : byWords ? 70 : 28)}ms`);
163
430
  this.style.setProperty('--usa-split-duration', `${this.num('duration', 620)}ms`);
164
431
  this.style.setProperty('--usa-split-delay', `${this.num('delay', 0)}ms`);
165
432
  this.style.setProperty('--usa-split-count', String(i));
@@ -193,8 +460,8 @@ function defineSplitText(tag = 'usa-split-text') {
193
460
  this.setAttribute('data-state', 'hidden');
194
461
  void this.offsetWidth;
195
462
  this.setAttribute('data-state', 'play');
196
- const n = this.units.length;
197
- const total = this.num('delay', 0) + this.num('duration', 620) + Math.max(0, n - 1) * this.num('stagger', this.str('by') === 'words' ? 70 : 28);
463
+ const by = this.str('by', 'chars');
464
+ const total = this.num('delay', 0) + this.num('duration', 620) + Math.max(0, this._steps - 1) * this.num('stagger', by === 'lines' ? 140 : by === 'words' ? 70 : 28);
198
465
  this._timer = setTimeout(() => {
199
466
  this.setAttribute('data-state', 'shown');
200
467
  this.emit('complete');
@@ -680,6 +947,7 @@ function defineTextComponents() {
680
947
 
681
948
  exports.configureComponents = base.configureComponents;
682
949
  exports.prefersReducedMotion = base.prefersReducedMotion;
950
+ exports.JOINING_SCRIPT = JOINING_SCRIPT;
683
951
  exports.defineCounter = defineCounter;
684
952
  exports.defineGlitch = defineGlitch;
685
953
  exports.defineGradientText = defineGradientText;
@@ -693,5 +961,10 @@ exports.defineTextRotate = defineTextRotate;
693
961
  exports.defineTypewriter = defineTypewriter;
694
962
  exports.defineWaveText = defineWaveText;
695
963
  exports.easeOutExpo = easeOutExpo;
964
+ exports.graphemes = graphemes;
696
965
  exports.scrambleFrame = scrambleFrame;
966
+ exports.splitOrder = splitOrder;
967
+ exports.splitText = splitText;
968
+ exports.splitTimeline = splitTimeline;
969
+ exports.splitWords = words;
697
970
  //# sourceMappingURL=text.cjs.map