Initial commit xmarticaims

This commit is contained in:
2026-11-02 10:26:32 -06:00
commit e74236f5c1
9764 changed files with 2880647 additions and 0 deletions
@@ -0,0 +1,18 @@
/**
* Anime.js - text - CJS
* @version v4.5.0
* @license MIT
* @copyright 2026 - Julian Garnier
*/
'use strict';
var split = require('./split.cjs');
var scramble = require('./scramble.cjs');
exports.TextSplitter = split.TextSplitter;
exports.split = split.split;
exports.splitText = split.splitText;
exports.scrambleText = scramble.scrambleText;
@@ -0,0 +1,2 @@
export * from "./split.js";
export * from "./scramble.js";
@@ -0,0 +1,9 @@
/**
* Anime.js - text - ESM
* @version v4.5.0
* @license MIT
* @copyright 2026 - Julian Garnier
*/
export { TextSplitter, split, splitText } from './split.js';
export { scrambleText } from './scramble.js';
@@ -0,0 +1,282 @@
/**
* Anime.js - text - CJS
* @version v4.5.0
* @license MIT
* @copyright 2026 - Julian Garnier
*/
'use strict';
var random = require('../utils/random.cjs');
var globals = require('../core/globals.cjs');
var helpers = require('../core/helpers.cjs');
var parser = require('../easings/eases/parser.cjs');
var consts = require('../core/consts.cjs');
/**
* @import {
* ScrambleTextParams,
* FunctionValue,
* } from '../types/index.js'
*/
/**
* @typedef {Object} ScrambleTextTween
* @property {Number} from
* @property {Number} to
* @property {Number} duration
* @property {Number} delay
* @property {String} ease
* @property {(v: Number) => String} modifier
*/
/**
* '-' is the range operator; place it at the start or end of the string to use it as a literal (e.g. '-abc' or 'abc-')
* @param {String} str
* @return {String}
*/
const expandCharRanges = (str) => {
let result = '';
for (let i = 0, l = str.length; i < l; i++) {
if (i + 2 < l && str[i + 1] === '-' && str.charCodeAt(i) < str.charCodeAt(i + 2)) {
const start = str.charCodeAt(i);
const end = str.charCodeAt(i + 2);
for (let c = start; c <= end; c++) result += String.fromCharCode(c);
i += 2;
} else {
result += str[i];
}
}
return result;
};
const charSets = {
lowercase: 'a-z',
uppercase: 'A-Z',
numbers: '0-9',
symbols: '!%#_|*+=',
braille: '⠀-⣿',
blocks: '▀-▟',
shades: '░-▓',
};
const originalTexts = new WeakMap();
/**
* Returns a function-based tween value that scrambles the target's text content,
* progressively revealing the original text.
*
* @param {ScrambleTextParams} [params]
* @return {FunctionValue<ScrambleTextTween>}
*/
const scrambleText = (params = {}) => {
if (!params) params = {};
const charsParam = params.chars;
const easeFn = parser.parseEase(params.ease || 'linear');
const text = params.text;
const fromParam = params.from;
const reversed = params.reversed || false;
const perturbation = params.perturbation || 0;
const cursorParam = params.cursor;
const cursorChars = cursorParam === true ? '_'
: typeof cursorParam === 'number' ? String.fromCharCode(cursorParam)
: typeof cursorParam === 'string' ? cursorParam
: '';
const cursorLen = cursorChars.length;
const seed = params.seed || 0;
const override = params.override !== undefined ? params.override : true;
const revealRate = params.revealRate || 60;
const interval = 1000 * globals.globals.timeScale / revealRate;
const settleDuration = params.settleDuration || 300 * globals.globals.timeScale;
const settleRate = params.settleRate || 30;
const durationParam = params.duration;
const revealDelayParam = params.revealDelay;
const delayParam = params.delay;
const onChange = params.onChange || consts.noop;
return (target, index, targets, prevTween) => {
const rawChars = typeof charsParam === 'function' ? charsParam(target, index, targets) : (charsParam || 'a-zA-Z0-9!%#_');
const characters = expandCharRanges(charSets[rawChars] || rawChars);
const totalChars = characters.length - 1;
const duration = typeof durationParam === 'function' ? durationParam(target, index, targets) : durationParam;
const revealDelay = typeof revealDelayParam === 'function' ? revealDelayParam(target, index, targets) : (revealDelayParam || 0);
const delay = typeof delayParam === 'function' ? delayParam(target, index, targets) : (delayParam || 0);
const rng = seed ? random.createSeededRandom(seed) : random.createSeededRandom();
if (!originalTexts.has(target)) originalTexts.set(target, target.textContent);
const startingText = prevTween ? prevTween._value : target.textContent;
const targetText = text !== undefined
? (typeof text === 'function' ? text(target, index, targets) : text)
: prevTween ? prevTween._value
: originalTexts.get(target);
const settledText = targetText === ' ' || targetText === '&nbsp;' ? ' ' : targetText;
const startLength = startingText === ' ' ? 0 : startingText.length;
const endLength = settledText.length;
const overrideChars = override === true ? characters
: typeof override === 'string' && override.length > 0 ? expandCharRanges(charSets[/** @type {String} */(override)] || /** @type {String} */(override))
: null;
const totalOverrideChars = overrideChars ? overrideChars.length - 1 : 0;
// Space override uses &nbsp; so the browser doesn't collapse consecutive spaces in innerHTML
const overrideChar = override === ' ' ? ' ' : null;
// When starting from blank, only animate the target text length to avoid padding beyond it
const animLength = override === '' ? endLength : Math.max(startLength, endLength);
// Compute total duration from interval spacing and settle time, or use the explicit duration
const animDuration = duration > 0 ? duration : (animLength - 1) * interval + settleDuration;
const computedDuration = helpers.round((animDuration + revealDelay) / globals.globals.timeScale, 0) * globals.globals.timeScale;
const revealDelayRatio = revealDelay > 0 ? helpers.round(revealDelay / computedDuration, 12) : 0;
// Auto-resolve reveal direction: shrinking text reveals from right, growing from left
const resolvedFrom = fromParam === undefined || fromParam === 'auto' ? (endLength < startLength ? 'right' : 'left') : fromParam;
const charOrder = new Int32Array(animLength);
if (resolvedFrom === 'random') {
for (let i = 0; i < animLength; i++) charOrder[i] = i;
for (let i = animLength - 1; i > 0; i--) {
const j = rng(0, i);
const t = charOrder[i]; charOrder[i] = charOrder[j]; charOrder[j] = t;
}
} else {
const ref = resolvedFrom === 'right' ? (override === '' || !startLength ? animLength : startLength) - 1
: resolvedFrom === 'center' ? ((override === '' || !startLength ? animLength : startLength) - 1) / 2
: typeof resolvedFrom === 'number' ? resolvedFrom
: 0;
const abs = Math.abs;
const indices = new Array(animLength);
for (let i = 0; i < animLength; i++) indices[i] = i;
indices.sort((a, b) => abs(a - ref) - abs(b - ref));
for (let i = 0; i < animLength; i++) charOrder[indices[i]] = i;
}
if (reversed) {
const last = animLength - 1;
for (let i = 0; i < animLength; i++) charOrder[i] = last - charOrder[i];
}
// settleRatio is the fraction of the animation each character spends in the active scrambling zone
const settleRatio = helpers.round(settleDuration / animDuration, 12);
// settleSpacing is the time gap between consecutive characters entering the active zone
const settleSpacing = helpers.round((1 - settleRatio) / animLength, 12);
const cursorZone = cursorLen * settleSpacing;
// stepRatio controls how often scramble characters refresh (based on settleRate)
const stepRatio = helpers.round(1000 * globals.globals.timeScale / (settleRate * computedDuration), 12);
// Pre-compute per-character start and settle times
const charStarts = new Float32Array(animLength);
const charEnds = new Float32Array(animLength);
const scale = perturbation > 0 ? perturbation * settleRatio : 0;
for (let c = 0; c < animLength; c++) {
const so = scale > 0 ? (rng(0, 2000) - 1000) / 1000 * scale : 0;
const eo = scale > 0 ? (rng(0, 2000) - 1000) / 1000 * scale : 0;
charStarts[c] = charOrder[c] * settleSpacing + so;
charEnds[c] = Math.ceil((charStarts[c] + settleRatio + eo) / stepRatio) * stepRatio;
}
// When text shrinks with non-sequential from modes, delay target settle times past all extras
if (endLength < animLength && resolvedFrom !== 'left' && resolvedFrom !== 'right' && resolvedFrom !== 'random') {
let maxExtraEnd = 0;
for (let c = endLength; c < animLength; c++) {
if (charEnds[c] > maxExtraEnd) maxExtraEnd = charEnds[c];
}
const targets = new Array(endLength);
for (let c = 0; c < endLength; c++) targets[c] = c;
targets.sort((a, b) => charOrder[a] - charOrder[b]);
const targetSpacing = (1 - maxExtraEnd) / endLength;
for (let i = 0; i < endLength; i++) {
const revealTime = maxExtraEnd + i * targetSpacing;
if (revealTime > charEnds[targets[i]]) {
charEnds[targets[i]] = revealTime;
}
}
}
// charCache holds the current scramble character for each position, refreshed at settleRate
const charCache = new Array(animLength);
for (let c = 0; c < animLength; c++) {
charCache[c] = characters[rng(0, totalChars)];
}
// overrideCache holds scramble characters for the starting text (override: true or custom string)
const overrideCache = overrideChars ? (overrideChars === characters ? charCache : new Array(animLength)) : null;
if (overrideCache && overrideCache !== charCache) {
for (let c = 0; c < animLength; c++) {
overrideCache[c] = overrideChar || /** @type {String} */(overrideChars)[rng(0, overrideChars.length - 1)];
}
}
// Build the initial display text based on override mode
let fillStartText = startingText;
if (!prevTween) {
if (override === '') {
fillStartText = '';
} else if (overrideChars) {
fillStartText = '';
for (let c = 0; c < startLength; c++) {
fillStartText += startingText[c] === ' ' ? ' ' : /** @type {Array<String>} */(overrideCache)[c];
}
}
}
let lastValue = -1;
let lastStep = -1;
let scrambled = '';
const hasOverride = override !== '';
const hasOverrideChars = !!overrideChars;
const hasCursor = cursorLen > 0;
return {
from: 0,
to: 1,
duration: computedDuration,
delay: delay,
ease: 'linear',
modifier: (v) => {
if (v === lastValue) return scrambled;
lastValue = v;
if (delay > 0 && v <= 0) { scrambled = startingText; return startingText; }
if (v <= 0) { scrambled = fillStartText; return fillStartText; }
if (v >= 1) { scrambled = settledText; return settledText; }
scrambled = '';
// Only refresh scramble characters when we cross a settleRate step boundary
const currentStep = (v / stepRatio) | 0;
const refreshChars = currentStep !== lastStep;
if (refreshChars) lastStep = currentStep;
// Subtract delay ratio to get the effective animation progress
const linear = revealDelayRatio > 0 ? (v - revealDelayRatio) / (1 - revealDelayRatio) : v;
const t = linear > 0 ? easeFn(linear) : 0;
for (let c = 0; c < animLength; c++) {
// Each character has its own start/end window based on its reveal order
const charStart = charStarts[c];
const charEnd = charEnds[c];
// Settled zone: character has finished its transition
if (t >= charEnd) {
if (c < endLength) scrambled += settledText[c];
continue;
}
// Pre-transition zone: reveal wave hasn't reached this character yet
if (t <= 0 || t < charStart) {
if (hasOverride && c < startLength) {
if (hasOverrideChars) {
if (startingText[c] === ' ') {
scrambled += ' ';
} else {
if (refreshChars) /** @type {Array<String>} */(overrideCache)[c] = overrideChar || /** @type {String} */(overrideChars)[rng(0, totalOverrideChars)];
scrambled += /** @type {Array<String>} */(overrideCache)[c];
}
} else {
// Default (override: false): show the original starting text
scrambled += startingText[c];
}
}
continue;
}
// Active zone: character is between charStart and charEnd
const isSpace = (c < endLength && settledText[c] === ' ') || (c < startLength && startingText[c] === ' ');
if (isSpace) {
scrambled += ' ';
} else if (hasCursor && t - charStart < cursorZone) {
// Cursor sub-zone: show cursor character based on position within cursor width
scrambled += cursorChars[cursorLen - 1 - (((t - charStart) / settleSpacing) | 0)];
} else {
// Scramble zone: show cycling random characters
if (refreshChars) charCache[c] = characters[rng(0, totalChars)];
scrambled += charCache[c];
}
}
if (refreshChars) onChange(scrambled, t);
return scrambled;
}
}
}
};
exports.scrambleText = scrambleText;
@@ -0,0 +1,11 @@
export function scrambleText(params?: ScrambleTextParams): FunctionValue<ScrambleTextTween>;
export type ScrambleTextTween = {
from: number;
to: number;
duration: number;
delay: number;
ease: string;
modifier: (v: number) => string;
};
import type { ScrambleTextParams } from '../types/index.js';
import type { FunctionValue } from '../types/index.js';
@@ -0,0 +1,280 @@
/**
* Anime.js - text - ESM
* @version v4.5.0
* @license MIT
* @copyright 2026 - Julian Garnier
*/
import { createSeededRandom } from '../utils/random.js';
import { globals } from '../core/globals.js';
import { round } from '../core/helpers.js';
import { parseEase } from '../easings/eases/parser.js';
import { noop } from '../core/consts.js';
/**
* @import {
* ScrambleTextParams,
* FunctionValue,
* } from '../types/index.js'
*/
/**
* @typedef {Object} ScrambleTextTween
* @property {Number} from
* @property {Number} to
* @property {Number} duration
* @property {Number} delay
* @property {String} ease
* @property {(v: Number) => String} modifier
*/
/**
* '-' is the range operator; place it at the start or end of the string to use it as a literal (e.g. '-abc' or 'abc-')
* @param {String} str
* @return {String}
*/
const expandCharRanges = (str) => {
let result = '';
for (let i = 0, l = str.length; i < l; i++) {
if (i + 2 < l && str[i + 1] === '-' && str.charCodeAt(i) < str.charCodeAt(i + 2)) {
const start = str.charCodeAt(i);
const end = str.charCodeAt(i + 2);
for (let c = start; c <= end; c++) result += String.fromCharCode(c);
i += 2;
} else {
result += str[i];
}
}
return result;
};
const charSets = {
lowercase: 'a-z',
uppercase: 'A-Z',
numbers: '0-9',
symbols: '!%#_|*+=',
braille: '⠀-⣿',
blocks: '▀-▟',
shades: '░-▓',
};
const originalTexts = new WeakMap();
/**
* Returns a function-based tween value that scrambles the target's text content,
* progressively revealing the original text.
*
* @param {ScrambleTextParams} [params]
* @return {FunctionValue<ScrambleTextTween>}
*/
const scrambleText = (params = {}) => {
if (!params) params = {};
const charsParam = params.chars;
const easeFn = parseEase(params.ease || 'linear');
const text = params.text;
const fromParam = params.from;
const reversed = params.reversed || false;
const perturbation = params.perturbation || 0;
const cursorParam = params.cursor;
const cursorChars = cursorParam === true ? '_'
: typeof cursorParam === 'number' ? String.fromCharCode(cursorParam)
: typeof cursorParam === 'string' ? cursorParam
: '';
const cursorLen = cursorChars.length;
const seed = params.seed || 0;
const override = params.override !== undefined ? params.override : true;
const revealRate = params.revealRate || 60;
const interval = 1000 * globals.timeScale / revealRate;
const settleDuration = params.settleDuration || 300 * globals.timeScale;
const settleRate = params.settleRate || 30;
const durationParam = params.duration;
const revealDelayParam = params.revealDelay;
const delayParam = params.delay;
const onChange = params.onChange || noop;
return (target, index, targets, prevTween) => {
const rawChars = typeof charsParam === 'function' ? charsParam(target, index, targets) : (charsParam || 'a-zA-Z0-9!%#_');
const characters = expandCharRanges(charSets[rawChars] || rawChars);
const totalChars = characters.length - 1;
const duration = typeof durationParam === 'function' ? durationParam(target, index, targets) : durationParam;
const revealDelay = typeof revealDelayParam === 'function' ? revealDelayParam(target, index, targets) : (revealDelayParam || 0);
const delay = typeof delayParam === 'function' ? delayParam(target, index, targets) : (delayParam || 0);
const rng = seed ? createSeededRandom(seed) : createSeededRandom();
if (!originalTexts.has(target)) originalTexts.set(target, target.textContent);
const startingText = prevTween ? prevTween._value : target.textContent;
const targetText = text !== undefined
? (typeof text === 'function' ? text(target, index, targets) : text)
: prevTween ? prevTween._value
: originalTexts.get(target);
const settledText = targetText === ' ' || targetText === '&nbsp;' ? ' ' : targetText;
const startLength = startingText === ' ' ? 0 : startingText.length;
const endLength = settledText.length;
const overrideChars = override === true ? characters
: typeof override === 'string' && override.length > 0 ? expandCharRanges(charSets[/** @type {String} */(override)] || /** @type {String} */(override))
: null;
const totalOverrideChars = overrideChars ? overrideChars.length - 1 : 0;
// Space override uses &nbsp; so the browser doesn't collapse consecutive spaces in innerHTML
const overrideChar = override === ' ' ? ' ' : null;
// When starting from blank, only animate the target text length to avoid padding beyond it
const animLength = override === '' ? endLength : Math.max(startLength, endLength);
// Compute total duration from interval spacing and settle time, or use the explicit duration
const animDuration = duration > 0 ? duration : (animLength - 1) * interval + settleDuration;
const computedDuration = round((animDuration + revealDelay) / globals.timeScale, 0) * globals.timeScale;
const revealDelayRatio = revealDelay > 0 ? round(revealDelay / computedDuration, 12) : 0;
// Auto-resolve reveal direction: shrinking text reveals from right, growing from left
const resolvedFrom = fromParam === undefined || fromParam === 'auto' ? (endLength < startLength ? 'right' : 'left') : fromParam;
const charOrder = new Int32Array(animLength);
if (resolvedFrom === 'random') {
for (let i = 0; i < animLength; i++) charOrder[i] = i;
for (let i = animLength - 1; i > 0; i--) {
const j = rng(0, i);
const t = charOrder[i]; charOrder[i] = charOrder[j]; charOrder[j] = t;
}
} else {
const ref = resolvedFrom === 'right' ? (override === '' || !startLength ? animLength : startLength) - 1
: resolvedFrom === 'center' ? ((override === '' || !startLength ? animLength : startLength) - 1) / 2
: typeof resolvedFrom === 'number' ? resolvedFrom
: 0;
const abs = Math.abs;
const indices = new Array(animLength);
for (let i = 0; i < animLength; i++) indices[i] = i;
indices.sort((a, b) => abs(a - ref) - abs(b - ref));
for (let i = 0; i < animLength; i++) charOrder[indices[i]] = i;
}
if (reversed) {
const last = animLength - 1;
for (let i = 0; i < animLength; i++) charOrder[i] = last - charOrder[i];
}
// settleRatio is the fraction of the animation each character spends in the active scrambling zone
const settleRatio = round(settleDuration / animDuration, 12);
// settleSpacing is the time gap between consecutive characters entering the active zone
const settleSpacing = round((1 - settleRatio) / animLength, 12);
const cursorZone = cursorLen * settleSpacing;
// stepRatio controls how often scramble characters refresh (based on settleRate)
const stepRatio = round(1000 * globals.timeScale / (settleRate * computedDuration), 12);
// Pre-compute per-character start and settle times
const charStarts = new Float32Array(animLength);
const charEnds = new Float32Array(animLength);
const scale = perturbation > 0 ? perturbation * settleRatio : 0;
for (let c = 0; c < animLength; c++) {
const so = scale > 0 ? (rng(0, 2000) - 1000) / 1000 * scale : 0;
const eo = scale > 0 ? (rng(0, 2000) - 1000) / 1000 * scale : 0;
charStarts[c] = charOrder[c] * settleSpacing + so;
charEnds[c] = Math.ceil((charStarts[c] + settleRatio + eo) / stepRatio) * stepRatio;
}
// When text shrinks with non-sequential from modes, delay target settle times past all extras
if (endLength < animLength && resolvedFrom !== 'left' && resolvedFrom !== 'right' && resolvedFrom !== 'random') {
let maxExtraEnd = 0;
for (let c = endLength; c < animLength; c++) {
if (charEnds[c] > maxExtraEnd) maxExtraEnd = charEnds[c];
}
const targets = new Array(endLength);
for (let c = 0; c < endLength; c++) targets[c] = c;
targets.sort((a, b) => charOrder[a] - charOrder[b]);
const targetSpacing = (1 - maxExtraEnd) / endLength;
for (let i = 0; i < endLength; i++) {
const revealTime = maxExtraEnd + i * targetSpacing;
if (revealTime > charEnds[targets[i]]) {
charEnds[targets[i]] = revealTime;
}
}
}
// charCache holds the current scramble character for each position, refreshed at settleRate
const charCache = new Array(animLength);
for (let c = 0; c < animLength; c++) {
charCache[c] = characters[rng(0, totalChars)];
}
// overrideCache holds scramble characters for the starting text (override: true or custom string)
const overrideCache = overrideChars ? (overrideChars === characters ? charCache : new Array(animLength)) : null;
if (overrideCache && overrideCache !== charCache) {
for (let c = 0; c < animLength; c++) {
overrideCache[c] = overrideChar || /** @type {String} */(overrideChars)[rng(0, overrideChars.length - 1)];
}
}
// Build the initial display text based on override mode
let fillStartText = startingText;
if (!prevTween) {
if (override === '') {
fillStartText = '';
} else if (overrideChars) {
fillStartText = '';
for (let c = 0; c < startLength; c++) {
fillStartText += startingText[c] === ' ' ? ' ' : /** @type {Array<String>} */(overrideCache)[c];
}
}
}
let lastValue = -1;
let lastStep = -1;
let scrambled = '';
const hasOverride = override !== '';
const hasOverrideChars = !!overrideChars;
const hasCursor = cursorLen > 0;
return {
from: 0,
to: 1,
duration: computedDuration,
delay: delay,
ease: 'linear',
modifier: (v) => {
if (v === lastValue) return scrambled;
lastValue = v;
if (delay > 0 && v <= 0) { scrambled = startingText; return startingText; }
if (v <= 0) { scrambled = fillStartText; return fillStartText; }
if (v >= 1) { scrambled = settledText; return settledText; }
scrambled = '';
// Only refresh scramble characters when we cross a settleRate step boundary
const currentStep = (v / stepRatio) | 0;
const refreshChars = currentStep !== lastStep;
if (refreshChars) lastStep = currentStep;
// Subtract delay ratio to get the effective animation progress
const linear = revealDelayRatio > 0 ? (v - revealDelayRatio) / (1 - revealDelayRatio) : v;
const t = linear > 0 ? easeFn(linear) : 0;
for (let c = 0; c < animLength; c++) {
// Each character has its own start/end window based on its reveal order
const charStart = charStarts[c];
const charEnd = charEnds[c];
// Settled zone: character has finished its transition
if (t >= charEnd) {
if (c < endLength) scrambled += settledText[c];
continue;
}
// Pre-transition zone: reveal wave hasn't reached this character yet
if (t <= 0 || t < charStart) {
if (hasOverride && c < startLength) {
if (hasOverrideChars) {
if (startingText[c] === ' ') {
scrambled += ' ';
} else {
if (refreshChars) /** @type {Array<String>} */(overrideCache)[c] = overrideChar || /** @type {String} */(overrideChars)[rng(0, totalOverrideChars)];
scrambled += /** @type {Array<String>} */(overrideCache)[c];
}
} else {
// Default (override: false): show the original starting text
scrambled += startingText[c];
}
}
continue;
}
// Active zone: character is between charStart and charEnd
const isSpace = (c < endLength && settledText[c] === ' ') || (c < startLength && startingText[c] === ' ');
if (isSpace) {
scrambled += ' ';
} else if (hasCursor && t - charStart < cursorZone) {
// Cursor sub-zone: show cursor character based on position within cursor width
scrambled += cursorChars[cursorLen - 1 - (((t - charStart) / settleSpacing) | 0)];
} else {
// Scramble zone: show cycling random characters
if (refreshChars) charCache[c] = characters[rng(0, totalChars)];
scrambled += charCache[c];
}
}
if (refreshChars) onChange(scrambled, t);
return scrambled;
}
}
}
};
export { scrambleText };
@@ -0,0 +1,503 @@
/**
* Anime.js - text - CJS
* @version v4.5.0
* @license MIT
* @copyright 2026 - Julian Garnier
*/
'use strict';
var consts = require('../core/consts.cjs');
var globals = require('../core/globals.cjs');
var helpers = require('../core/helpers.cjs');
var targets = require('../core/targets.cjs');
var values = require('../core/values.cjs');
var time = require('../utils/time.cjs');
/**
* @import {
* Tickable,
* DOMTarget,
* SplitTemplateParams,
* SplitFunctionValue,
* TextSplitterParams,
* } from '../types/index.js'
*/
const segmenter = (typeof Intl !== 'undefined') && Intl.Segmenter;
const valueRgx = /\{value\}/g;
const indexRgx = /\{i\}/g;
const whiteSpaceGroupRgx = /(\s+)/;
const whiteSpaceRgx = /^\s+$/;
const lineType = 'line';
const wordType = 'word';
const charType = 'char';
const dataLine = `data-line`;
/**
* @typedef {Object} Segment
* @property {String} segment
* @property {Boolean} [isWordLike]
*/
/**
* @typedef {Object} Segmenter
* @property {function(String): Iterable<Segment>} segment
*/
/** @type {Segmenter} */
let wordSegmenter = null;
/** @type {Segmenter} */
let graphemeSegmenter = null;
let $splitTemplate = null;
/**
* @param {Segment} seg
* @return {Boolean}
*/
const isSegmentWordLike = seg => {
return seg.isWordLike ||
seg.segment === ' ' || // Consider spaces as words first, then handle them diffrently later
helpers.isNum(+seg.segment); // Safari doesn't considers numbers as words
};
/**
* @param {HTMLElement} $el
*/
const setAriaHidden = $el => $el.setAttribute('aria-hidden', 'true');
/**
* @param {DOMTarget} $el
* @param {String} type
* @return {Array<HTMLElement>}
*/
const getAllTopLevelElements = ($el, type) => [.../** @type {*} */($el.querySelectorAll(`[data-${type}]:not([data-${type}] [data-${type}])`))];
const debugColors = { line: '#00D672', word: '#FF4B4B', char: '#5A87FF' };
/**
* @param {HTMLElement} $el
*/
const filterEmptyElements = $el => {
if (!$el.childElementCount && !$el.textContent.trim()) {
const $parent = $el.parentElement;
$el.remove();
if ($parent) filterEmptyElements($parent);
}
};
/**
* @param {HTMLElement} $el
* @param {Number} lineIndex
* @param {Set<HTMLElement|Node>} bin
* @returns {Set<HTMLElement|Node>}
*/
const filterLineElements = ($el, lineIndex, bin) => {
const dataLineAttr = $el.getAttribute(dataLine);
if (dataLineAttr !== null && +dataLineAttr !== lineIndex || $el.tagName === 'BR') {
bin.add($el);
// Also remove adjacent whitespace-only text nodes
const prev = $el.previousSibling;
const next = $el.nextSibling;
if (prev && prev.nodeType === 3 && whiteSpaceRgx.test(prev.textContent)) {
bin.add(prev);
}
if (next && next.nodeType === 3 && whiteSpaceRgx.test(next.textContent)) {
bin.add(next);
}
}
let i = $el.childElementCount;
while (i--) filterLineElements(/** @type {HTMLElement} */($el.children[i]), lineIndex, bin);
return bin;
};
/**
* @param {'line'|'word'|'char'} type
* @param {SplitTemplateParams} params
* @return {String}
*/
const generateTemplate = (type, params = {}) => {
let template = ``;
if (!params) params = {};
const classString = helpers.isStr(params.class) ? ` class="${params.class}"` : '';
const cloneType = values.setValue(params.clone, false);
const wrapType = values.setValue(params.wrap, false);
const overflow = wrapType ? wrapType === true ? 'clip' : wrapType : cloneType ? 'clip' : false;
if (wrapType) template += `<span${overflow ? ` style="overflow:${overflow};"` : ''}>`;
template += `<span${classString}${cloneType ? ` style="position:relative;"` : ''} data-${type}="{i}">`;
if (cloneType) {
const left = cloneType === 'left' ? '-100%' : cloneType === 'right' ? '100%' : '0';
const top = cloneType === 'top' ? '-100%' : cloneType === 'bottom' ? '100%' : '0';
template += `<span>{value}</span>`;
template += `<span inert style="position:absolute;top:${top};left:${left};white-space:nowrap;">{value}</span>`;
} else {
template += `{value}`;
}
template += `</span>`;
if (wrapType) template += `</span>`;
return template;
};
/**
* @param {String|SplitFunctionValue} htmlTemplate
* @param {Array<HTMLElement>} store
* @param {Node|HTMLElement} node
* @param {DocumentFragment} $parentFragment
* @param {'line'|'word'|'char'} type
* @param {Boolean} debug
* @param {Number} lineIndex
* @param {Number} [wordIndex]
* @param {Number} [charIndex]
* @return {HTMLElement}
*/
const processHTMLTemplate = (htmlTemplate, store, node, $parentFragment, type, debug, lineIndex, wordIndex, charIndex) => {
const isLine = type === lineType;
const isChar = type === charType;
const className = `_${type}_`;
const template = helpers.isFnc(htmlTemplate) ? htmlTemplate(node) : htmlTemplate;
const displayStyle = isLine ? 'block' : 'inline-block';
$splitTemplate.innerHTML = template
.replace(valueRgx, `<i class="${className}"></i>`)
.replace(indexRgx, `${isChar ? charIndex : isLine ? lineIndex : wordIndex}`);
const $content = $splitTemplate.content;
const $highestParent = /** @type {HTMLElement} */($content.firstElementChild);
const $split = /** @type {HTMLElement} */($content.querySelector(`[data-${type}]`)) || $highestParent;
const $replacables = /** @type {NodeListOf<HTMLElement>} */($content.querySelectorAll(`i.${className}`));
const replacablesLength = $replacables.length;
if (replacablesLength) {
$highestParent.style.display = displayStyle;
$split.style.display = displayStyle;
$split.setAttribute(dataLine, `${lineIndex}`);
if (!isLine) {
$split.setAttribute('data-word', `${wordIndex}`);
if (isChar) $split.setAttribute('data-char', `${charIndex}`);
}
let i = replacablesLength;
while (i--) {
const $replace = $replacables[i];
const $closestParent = $replace.parentElement;
$closestParent.style.display = displayStyle;
if (isLine) {
$closestParent.innerHTML = /** @type {HTMLElement} */(node).innerHTML;
} else {
$closestParent.replaceChild(node.cloneNode(true), $replace);
}
}
store.push($split);
$parentFragment.appendChild($content);
} else {
console.warn(`The expression "{value}" is missing from the provided template.`);
}
if (debug) $highestParent.style.outline = `1px dotted ${debugColors[type]}`;
return $highestParent;
};
/**
* A class that splits text into words and wraps them in span elements while preserving the original HTML structure.
* @class
*/
class TextSplitter {
/**
* @param {Element|NodeList|String|Array<Element>} target
* @param {TextSplitterParams} [parameters]
*/
constructor(target, parameters = {}) {
// Only init segmenters when needed
if (!wordSegmenter) wordSegmenter = segmenter ? new segmenter([], { granularity: wordType }) : {
segment: (text) => {
const segments = [];
const words = text.split(whiteSpaceGroupRgx);
for (let i = 0, l = words.length; i < l; i++) {
const segment = words[i];
segments.push({
segment,
isWordLike: !whiteSpaceRgx.test(segment), // Consider non-whitespace as word-like
});
}
return segments;
}
};
if (!graphemeSegmenter) graphemeSegmenter = segmenter ? new segmenter([], { granularity: 'grapheme' }) : {
segment: text => [...text].map(char => ({ segment: char }))
};
if (!$splitTemplate && consts.isBrowser) $splitTemplate = consts.doc.createElement('template');
if (globals.scope.current) globals.scope.current.register(this);
const { words, chars, lines, accessible, includeSpaces, debug } = parameters;
const $target = /** @type {HTMLElement} */((target = helpers.isArr(target) ? target[0] : target) && /** @type {Node} */(target).nodeType ? target : (targets.getNodeList(target) || [])[0]);
const lineParams = lines === true ? {} : lines;
const wordParams = words === true || helpers.isUnd(words) ? {} : words;
const charParams = chars === true ? {} : chars;
this.debug = values.setValue(debug, false);
this.includeSpaces = values.setValue(includeSpaces, false);
this.accessible = values.setValue(accessible, true);
this.linesOnly = lineParams && (!wordParams && !charParams);
/** @type {String|false|SplitFunctionValue} */
this.lineTemplate = helpers.isObj(lineParams) ? generateTemplate(lineType, /** @type {SplitTemplateParams} */(lineParams)) : lineParams;
/** @type {String|false|SplitFunctionValue} */
this.wordTemplate = helpers.isObj(wordParams) || this.linesOnly ? generateTemplate(wordType, /** @type {SplitTemplateParams} */(wordParams)) : wordParams;
/** @type {String|false|SplitFunctionValue} */
this.charTemplate = helpers.isObj(charParams) ? generateTemplate(charType, /** @type {SplitTemplateParams} */(charParams)) : charParams;
this.$target = $target;
this.html = $target && $target.innerHTML;
this.lines = [];
this.words = [];
this.chars = [];
this.effects = [];
this.effectsCleanups = [];
this.cache = null;
this.ready = false;
this.width = 0;
this.resizeTimeout = null;
const handleSplit = () => this.html && (lineParams || wordParams || charParams) && this.split();
// Make sure this is declared before calling handleSplit() in case revert() is called inside an effect callback
this.resizeObserver = new ResizeObserver(() => {
// Use a setTimeout instead of a Timer for better tree shaking
clearTimeout(this.resizeTimeout);
this.resizeTimeout = setTimeout(() => {
const currentWidth = /** @type {HTMLElement} */($target).offsetWidth;
if (currentWidth === this.width) return;
this.width = currentWidth;
handleSplit();
}, 150);
});
// Only declare the font ready promise when splitting by lines and not alreay split
if (this.lineTemplate && !this.ready) {
consts.doc.fonts.ready.then(handleSplit);
} else {
handleSplit();
}
$target ? this.resizeObserver.observe($target) : console.warn('No Text Splitter target found.');
}
/**
* @param {(...args: any[]) => Tickable | (() => void) | void} effect
* @return this
*/
addEffect(effect) {
if (!helpers.isFnc(effect)) { console.warn('Effect must return a function.'); return this; }
const refreshableEffect = time.keepTime(effect);
this.effects.push(refreshableEffect);
if (this.ready) this.effectsCleanups[this.effects.length - 1] = refreshableEffect(this);
return this;
}
revert() {
clearTimeout(this.resizeTimeout);
this.lines.length = this.words.length = this.chars.length = 0;
this.resizeObserver.disconnect();
// Make sure to revert the effects after disconnecting the resizeObserver to avoid triggering it in the process
this.effectsCleanups.forEach(cleanup => helpers.isFnc(cleanup) ? cleanup(this) : cleanup.revert && cleanup.revert());
this.$target.innerHTML = this.html;
return this;
}
/**
* Recursively processes a node and its children
* @param {Node} node
*/
splitNode(node) {
const wordTemplate = this.wordTemplate;
const charTemplate = this.charTemplate;
const includeSpaces = this.includeSpaces;
const debug = this.debug;
const nodeType = node.nodeType;
if (nodeType === 3) {
const nodeText = node.nodeValue;
// If the nodeText is only whitespace, leave it as is
if (nodeText.trim()) {
const tempWords = [];
const words = this.words;
const chars = this.chars;
const wordSegments = wordSegmenter.segment(nodeText);
const $wordsFragment = consts.doc.createDocumentFragment();
let prevSeg = null;
for (const wordSegment of wordSegments) {
const segment = wordSegment.segment;
const isWordLike = isSegmentWordLike(wordSegment);
// Determine if this segment should be a new word, first segment always becomes a new word
if (!prevSeg || (isWordLike && (prevSeg && (isSegmentWordLike(prevSeg))))) {
tempWords.push(segment);
} else {
// Only concatenate if both current and previous are non-word-like and don't contain spaces
const lastWordIndex = tempWords.length - 1;
const lastWord = tempWords[lastWordIndex];
if (!whiteSpaceGroupRgx.test(lastWord) && !whiteSpaceGroupRgx.test(segment)) {
tempWords[lastWordIndex] += segment;
} else {
tempWords.push(segment);
}
}
prevSeg = wordSegment;
}
for (let i = 0, l = tempWords.length; i < l; i++) {
const word = tempWords[i];
if (!word.trim()) {
// Preserve whitespace only if includeSpaces is false and if the current space is not the first node
if (i && includeSpaces) continue;
$wordsFragment.appendChild(consts.doc.createTextNode(word));
} else {
const nextWord = tempWords[i + 1];
const hasWordFollowingSpace = includeSpaces && nextWord && !nextWord.trim();
const wordToProcess = word;
const charSegments = charTemplate ? graphemeSegmenter.segment(wordToProcess) : null;
const $charsFragment = charTemplate ? consts.doc.createDocumentFragment() : consts.doc.createTextNode(hasWordFollowingSpace ? word + '\xa0' : word);
if (charTemplate) {
const charSegmentsArray = [...charSegments];
for (let j = 0, jl = charSegmentsArray.length; j < jl; j++) {
const charSegment = charSegmentsArray[j];
const isLastChar = j === jl - 1;
// If this is the last character and includeSpaces is true with a following space, append the space
const charText = isLastChar && hasWordFollowingSpace ? charSegment.segment + '\xa0' : charSegment.segment;
const $charNode = consts.doc.createTextNode(charText);
processHTMLTemplate(charTemplate, chars, $charNode, /** @type {DocumentFragment} */($charsFragment), charType, debug, -1, words.length, chars.length);
}
}
if (wordTemplate) {
processHTMLTemplate(wordTemplate, words, $charsFragment, $wordsFragment, wordType, debug, -1, words.length, chars.length);
// Chars elements must be re-parsed in the split() method if both words and chars are parsed
} else if (charTemplate) {
$wordsFragment.appendChild($charsFragment);
} else {
$wordsFragment.appendChild(consts.doc.createTextNode(word));
}
// Skip the next iteration if we included a space
if (hasWordFollowingSpace) i++;
}
}
node.parentNode.replaceChild($wordsFragment, node);
}
} else if (nodeType === 1) {
// Converting to an array is necessary to work around childNodes pottential mutation
const childNodes = /** @type {Array<Node>} */([.../** @type {*} */(node.childNodes)]);
for (let i = 0, l = childNodes.length; i < l; i++) this.splitNode(childNodes[i]);
}
}
/**
* @param {Boolean} clearCache
* @return {this}
*/
split(clearCache = false) {
const $el = this.$target;
const isCached = !!this.cache && !clearCache;
const lineTemplate = this.lineTemplate;
const wordTemplate = this.wordTemplate;
const charTemplate = this.charTemplate;
const fontsReady = consts.doc.fonts.status !== 'loading';
const canSplitLines = lineTemplate && fontsReady;
this.ready = !lineTemplate || fontsReady;
if (canSplitLines || clearCache) {
// No need to revert effects animations here since it's already taken care by the refreshable
this.effectsCleanups.forEach(cleanup => helpers.isFnc(cleanup) && cleanup(this));
}
if (!isCached) {
if (clearCache) {
$el.innerHTML = this.html;
this.words.length = this.chars.length = 0;
}
this.splitNode($el);
this.cache = $el.innerHTML;
}
if (canSplitLines) {
if (isCached) $el.innerHTML = this.cache;
this.lines.length = 0;
if (wordTemplate) this.words = getAllTopLevelElements($el, wordType);
}
// Always reparse characters after a line reset or if both words and chars are activated
if (charTemplate && (canSplitLines || wordTemplate)) {
this.chars = getAllTopLevelElements($el, charType);
}
// Words are used when lines only and prioritized over chars
const elementsArray = this.words.length ? this.words : this.chars;
let y, linesCount = 0;
for (let i = 0, l = elementsArray.length; i < l; i++) {
const $el = elementsArray[i];
const { top, height } = $el.getBoundingClientRect();
if (!helpers.isUnd(y) && top - y > height * .5) linesCount++;
$el.setAttribute(dataLine, `${linesCount}`);
const nested = $el.querySelectorAll(`[${dataLine}]`);
let c = nested.length;
while (c--) nested[c].setAttribute(dataLine, `${linesCount}`);
y = top;
}
if (canSplitLines) {
const linesFragment = consts.doc.createDocumentFragment();
const parents = new Set();
const clones = [];
for (let lineIndex = 0; lineIndex < linesCount + 1; lineIndex++) {
const $clone = /** @type {HTMLElement} */($el.cloneNode(true));
filterLineElements($clone, lineIndex, new Set()).forEach($el => {
const $parent = $el.parentNode;
if ($parent) {
if ($el.nodeType === 1) parents.add(/** @type {HTMLElement} */($parent));
$parent.removeChild($el);
}
});
clones.push($clone);
}
parents.forEach(filterEmptyElements);
for (let cloneIndex = 0, clonesLength = clones.length; cloneIndex < clonesLength; cloneIndex++) {
processHTMLTemplate(lineTemplate, this.lines, clones[cloneIndex], linesFragment, lineType, this.debug, cloneIndex);
}
$el.innerHTML = '';
$el.appendChild(linesFragment);
if (wordTemplate) this.words = getAllTopLevelElements($el, wordType);
if (charTemplate) this.chars = getAllTopLevelElements($el, charType);
}
// Remove the word wrappers and clear the words array if lines split only
if (this.linesOnly) {
const words = this.words;
let w = words.length;
while (w--) {
const $word = words[w];
$word.replaceWith($word.textContent);
}
words.length = 0;
}
if (this.accessible && (canSplitLines || !isCached)) {
const $accessible = consts.doc.createElement('span');
// Make the accessible element visually-hidden (https://www.scottohara.me/blog/2017/04/14/inclusively-hidden.html)
$accessible.style.cssText = `position:absolute;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;white-space:nowrap;`;
// $accessible.setAttribute('tabindex', '-1');
$accessible.innerHTML = this.html;
$el.insertBefore($accessible, $el.firstChild);
this.lines.forEach(setAriaHidden);
this.words.forEach(setAriaHidden);
this.chars.forEach(setAriaHidden);
}
this.width = /** @type {HTMLElement} */($el).offsetWidth;
if (canSplitLines || clearCache) {
this.effects.forEach((effect, i) => this.effectsCleanups[i] = effect(this));
}
return this;
}
refresh() {
this.split(true);
}
}
/**
* @param {Element|NodeList|String|Array<Element>} target
* @param {TextSplitterParams} [parameters]
* @return {TextSplitter}
*/
const splitText = (target, parameters) => new TextSplitter(target, parameters);
/**
* @deprecated text.split() is deprecated, import splitText() directly, or text.splitText()
*
* @param {HTMLElement|NodeList|String|Array<HTMLElement>} target
* @param {TextSplitterParams} [parameters]
* @return {TextSplitter}
*/
const split = (target, parameters) => {
console.warn('text.split() is deprecated, import splitText() directly, or text.splitText()');
return new TextSplitter(target, parameters);
};
exports.TextSplitter = TextSplitter;
exports.split = split;
exports.splitText = splitText;
@@ -0,0 +1,62 @@
/**
* A class that splits text into words and wraps them in span elements while preserving the original HTML structure.
* @class
*/
export class TextSplitter {
/**
* @param {Element|NodeList|String|Array<Element>} target
* @param {TextSplitterParams} [parameters]
*/
constructor(target: Element | NodeList | string | Array<Element>, parameters?: TextSplitterParams);
debug: boolean;
includeSpaces: boolean;
accessible: boolean;
linesOnly: boolean;
/** @type {String|false|SplitFunctionValue} */
lineTemplate: string | false | SplitFunctionValue;
/** @type {String|false|SplitFunctionValue} */
wordTemplate: string | false | SplitFunctionValue;
/** @type {String|false|SplitFunctionValue} */
charTemplate: string | false | SplitFunctionValue;
$target: HTMLElement;
html: string;
lines: any[];
words: any[];
chars: any[];
effects: any[];
effectsCleanups: any[];
cache: string;
ready: boolean;
width: number;
resizeTimeout: NodeJS.Timeout;
resizeObserver: ResizeObserver;
/**
* @param {(...args: any[]) => Tickable | (() => void) | void} effect
* @return this
*/
addEffect(effect: (...args: any[]) => Tickable | (() => void) | void): this;
revert(): this;
/**
* Recursively processes a node and its children
* @param {Node} node
*/
splitNode(node: Node): void;
/**
* @param {Boolean} clearCache
* @return {this}
*/
split(clearCache?: boolean): this;
refresh(): void;
}
export function splitText(target: Element | NodeList | string | Array<Element>, parameters?: TextSplitterParams): TextSplitter;
export function split(target: HTMLElement | NodeList | string | Array<HTMLElement>, parameters?: TextSplitterParams): TextSplitter;
export type Segment = {
segment: string;
isWordLike?: boolean;
};
export type Segmenter = {
segment: (arg0: string) => Iterable<Segment>;
};
import type { SplitFunctionValue } from '../types/index.js';
import type { Tickable } from '../types/index.js';
import type { TextSplitterParams } from '../types/index.js';
@@ -0,0 +1,499 @@
/**
* Anime.js - text - ESM
* @version v4.5.0
* @license MIT
* @copyright 2026 - Julian Garnier
*/
import { isBrowser, doc } from '../core/consts.js';
import { scope } from '../core/globals.js';
import { isArr, isObj, isFnc, isUnd, isStr, isNum } from '../core/helpers.js';
import { getNodeList } from '../core/targets.js';
import { setValue } from '../core/values.js';
import { keepTime } from '../utils/time.js';
/**
* @import {
* Tickable,
* DOMTarget,
* SplitTemplateParams,
* SplitFunctionValue,
* TextSplitterParams,
* } from '../types/index.js'
*/
const segmenter = (typeof Intl !== 'undefined') && Intl.Segmenter;
const valueRgx = /\{value\}/g;
const indexRgx = /\{i\}/g;
const whiteSpaceGroupRgx = /(\s+)/;
const whiteSpaceRgx = /^\s+$/;
const lineType = 'line';
const wordType = 'word';
const charType = 'char';
const dataLine = `data-line`;
/**
* @typedef {Object} Segment
* @property {String} segment
* @property {Boolean} [isWordLike]
*/
/**
* @typedef {Object} Segmenter
* @property {function(String): Iterable<Segment>} segment
*/
/** @type {Segmenter} */
let wordSegmenter = null;
/** @type {Segmenter} */
let graphemeSegmenter = null;
let $splitTemplate = null;
/**
* @param {Segment} seg
* @return {Boolean}
*/
const isSegmentWordLike = seg => {
return seg.isWordLike ||
seg.segment === ' ' || // Consider spaces as words first, then handle them diffrently later
isNum(+seg.segment); // Safari doesn't considers numbers as words
};
/**
* @param {HTMLElement} $el
*/
const setAriaHidden = $el => $el.setAttribute('aria-hidden', 'true');
/**
* @param {DOMTarget} $el
* @param {String} type
* @return {Array<HTMLElement>}
*/
const getAllTopLevelElements = ($el, type) => [.../** @type {*} */($el.querySelectorAll(`[data-${type}]:not([data-${type}] [data-${type}])`))];
const debugColors = { line: '#00D672', word: '#FF4B4B', char: '#5A87FF' };
/**
* @param {HTMLElement} $el
*/
const filterEmptyElements = $el => {
if (!$el.childElementCount && !$el.textContent.trim()) {
const $parent = $el.parentElement;
$el.remove();
if ($parent) filterEmptyElements($parent);
}
};
/**
* @param {HTMLElement} $el
* @param {Number} lineIndex
* @param {Set<HTMLElement|Node>} bin
* @returns {Set<HTMLElement|Node>}
*/
const filterLineElements = ($el, lineIndex, bin) => {
const dataLineAttr = $el.getAttribute(dataLine);
if (dataLineAttr !== null && +dataLineAttr !== lineIndex || $el.tagName === 'BR') {
bin.add($el);
// Also remove adjacent whitespace-only text nodes
const prev = $el.previousSibling;
const next = $el.nextSibling;
if (prev && prev.nodeType === 3 && whiteSpaceRgx.test(prev.textContent)) {
bin.add(prev);
}
if (next && next.nodeType === 3 && whiteSpaceRgx.test(next.textContent)) {
bin.add(next);
}
}
let i = $el.childElementCount;
while (i--) filterLineElements(/** @type {HTMLElement} */($el.children[i]), lineIndex, bin);
return bin;
};
/**
* @param {'line'|'word'|'char'} type
* @param {SplitTemplateParams} params
* @return {String}
*/
const generateTemplate = (type, params = {}) => {
let template = ``;
if (!params) params = {};
const classString = isStr(params.class) ? ` class="${params.class}"` : '';
const cloneType = setValue(params.clone, false);
const wrapType = setValue(params.wrap, false);
const overflow = wrapType ? wrapType === true ? 'clip' : wrapType : cloneType ? 'clip' : false;
if (wrapType) template += `<span${overflow ? ` style="overflow:${overflow};"` : ''}>`;
template += `<span${classString}${cloneType ? ` style="position:relative;"` : ''} data-${type}="{i}">`;
if (cloneType) {
const left = cloneType === 'left' ? '-100%' : cloneType === 'right' ? '100%' : '0';
const top = cloneType === 'top' ? '-100%' : cloneType === 'bottom' ? '100%' : '0';
template += `<span>{value}</span>`;
template += `<span inert style="position:absolute;top:${top};left:${left};white-space:nowrap;">{value}</span>`;
} else {
template += `{value}`;
}
template += `</span>`;
if (wrapType) template += `</span>`;
return template;
};
/**
* @param {String|SplitFunctionValue} htmlTemplate
* @param {Array<HTMLElement>} store
* @param {Node|HTMLElement} node
* @param {DocumentFragment} $parentFragment
* @param {'line'|'word'|'char'} type
* @param {Boolean} debug
* @param {Number} lineIndex
* @param {Number} [wordIndex]
* @param {Number} [charIndex]
* @return {HTMLElement}
*/
const processHTMLTemplate = (htmlTemplate, store, node, $parentFragment, type, debug, lineIndex, wordIndex, charIndex) => {
const isLine = type === lineType;
const isChar = type === charType;
const className = `_${type}_`;
const template = isFnc(htmlTemplate) ? htmlTemplate(node) : htmlTemplate;
const displayStyle = isLine ? 'block' : 'inline-block';
$splitTemplate.innerHTML = template
.replace(valueRgx, `<i class="${className}"></i>`)
.replace(indexRgx, `${isChar ? charIndex : isLine ? lineIndex : wordIndex}`);
const $content = $splitTemplate.content;
const $highestParent = /** @type {HTMLElement} */($content.firstElementChild);
const $split = /** @type {HTMLElement} */($content.querySelector(`[data-${type}]`)) || $highestParent;
const $replacables = /** @type {NodeListOf<HTMLElement>} */($content.querySelectorAll(`i.${className}`));
const replacablesLength = $replacables.length;
if (replacablesLength) {
$highestParent.style.display = displayStyle;
$split.style.display = displayStyle;
$split.setAttribute(dataLine, `${lineIndex}`);
if (!isLine) {
$split.setAttribute('data-word', `${wordIndex}`);
if (isChar) $split.setAttribute('data-char', `${charIndex}`);
}
let i = replacablesLength;
while (i--) {
const $replace = $replacables[i];
const $closestParent = $replace.parentElement;
$closestParent.style.display = displayStyle;
if (isLine) {
$closestParent.innerHTML = /** @type {HTMLElement} */(node).innerHTML;
} else {
$closestParent.replaceChild(node.cloneNode(true), $replace);
}
}
store.push($split);
$parentFragment.appendChild($content);
} else {
console.warn(`The expression "{value}" is missing from the provided template.`);
}
if (debug) $highestParent.style.outline = `1px dotted ${debugColors[type]}`;
return $highestParent;
};
/**
* A class that splits text into words and wraps them in span elements while preserving the original HTML structure.
* @class
*/
class TextSplitter {
/**
* @param {Element|NodeList|String|Array<Element>} target
* @param {TextSplitterParams} [parameters]
*/
constructor(target, parameters = {}) {
// Only init segmenters when needed
if (!wordSegmenter) wordSegmenter = segmenter ? new segmenter([], { granularity: wordType }) : {
segment: (text) => {
const segments = [];
const words = text.split(whiteSpaceGroupRgx);
for (let i = 0, l = words.length; i < l; i++) {
const segment = words[i];
segments.push({
segment,
isWordLike: !whiteSpaceRgx.test(segment), // Consider non-whitespace as word-like
});
}
return segments;
}
};
if (!graphemeSegmenter) graphemeSegmenter = segmenter ? new segmenter([], { granularity: 'grapheme' }) : {
segment: text => [...text].map(char => ({ segment: char }))
};
if (!$splitTemplate && isBrowser) $splitTemplate = doc.createElement('template');
if (scope.current) scope.current.register(this);
const { words, chars, lines, accessible, includeSpaces, debug } = parameters;
const $target = /** @type {HTMLElement} */((target = isArr(target) ? target[0] : target) && /** @type {Node} */(target).nodeType ? target : (getNodeList(target) || [])[0]);
const lineParams = lines === true ? {} : lines;
const wordParams = words === true || isUnd(words) ? {} : words;
const charParams = chars === true ? {} : chars;
this.debug = setValue(debug, false);
this.includeSpaces = setValue(includeSpaces, false);
this.accessible = setValue(accessible, true);
this.linesOnly = lineParams && (!wordParams && !charParams);
/** @type {String|false|SplitFunctionValue} */
this.lineTemplate = isObj(lineParams) ? generateTemplate(lineType, /** @type {SplitTemplateParams} */(lineParams)) : lineParams;
/** @type {String|false|SplitFunctionValue} */
this.wordTemplate = isObj(wordParams) || this.linesOnly ? generateTemplate(wordType, /** @type {SplitTemplateParams} */(wordParams)) : wordParams;
/** @type {String|false|SplitFunctionValue} */
this.charTemplate = isObj(charParams) ? generateTemplate(charType, /** @type {SplitTemplateParams} */(charParams)) : charParams;
this.$target = $target;
this.html = $target && $target.innerHTML;
this.lines = [];
this.words = [];
this.chars = [];
this.effects = [];
this.effectsCleanups = [];
this.cache = null;
this.ready = false;
this.width = 0;
this.resizeTimeout = null;
const handleSplit = () => this.html && (lineParams || wordParams || charParams) && this.split();
// Make sure this is declared before calling handleSplit() in case revert() is called inside an effect callback
this.resizeObserver = new ResizeObserver(() => {
// Use a setTimeout instead of a Timer for better tree shaking
clearTimeout(this.resizeTimeout);
this.resizeTimeout = setTimeout(() => {
const currentWidth = /** @type {HTMLElement} */($target).offsetWidth;
if (currentWidth === this.width) return;
this.width = currentWidth;
handleSplit();
}, 150);
});
// Only declare the font ready promise when splitting by lines and not alreay split
if (this.lineTemplate && !this.ready) {
doc.fonts.ready.then(handleSplit);
} else {
handleSplit();
}
$target ? this.resizeObserver.observe($target) : console.warn('No Text Splitter target found.');
}
/**
* @param {(...args: any[]) => Tickable | (() => void) | void} effect
* @return this
*/
addEffect(effect) {
if (!isFnc(effect)) { console.warn('Effect must return a function.'); return this; }
const refreshableEffect = keepTime(effect);
this.effects.push(refreshableEffect);
if (this.ready) this.effectsCleanups[this.effects.length - 1] = refreshableEffect(this);
return this;
}
revert() {
clearTimeout(this.resizeTimeout);
this.lines.length = this.words.length = this.chars.length = 0;
this.resizeObserver.disconnect();
// Make sure to revert the effects after disconnecting the resizeObserver to avoid triggering it in the process
this.effectsCleanups.forEach(cleanup => isFnc(cleanup) ? cleanup(this) : cleanup.revert && cleanup.revert());
this.$target.innerHTML = this.html;
return this;
}
/**
* Recursively processes a node and its children
* @param {Node} node
*/
splitNode(node) {
const wordTemplate = this.wordTemplate;
const charTemplate = this.charTemplate;
const includeSpaces = this.includeSpaces;
const debug = this.debug;
const nodeType = node.nodeType;
if (nodeType === 3) {
const nodeText = node.nodeValue;
// If the nodeText is only whitespace, leave it as is
if (nodeText.trim()) {
const tempWords = [];
const words = this.words;
const chars = this.chars;
const wordSegments = wordSegmenter.segment(nodeText);
const $wordsFragment = doc.createDocumentFragment();
let prevSeg = null;
for (const wordSegment of wordSegments) {
const segment = wordSegment.segment;
const isWordLike = isSegmentWordLike(wordSegment);
// Determine if this segment should be a new word, first segment always becomes a new word
if (!prevSeg || (isWordLike && (prevSeg && (isSegmentWordLike(prevSeg))))) {
tempWords.push(segment);
} else {
// Only concatenate if both current and previous are non-word-like and don't contain spaces
const lastWordIndex = tempWords.length - 1;
const lastWord = tempWords[lastWordIndex];
if (!whiteSpaceGroupRgx.test(lastWord) && !whiteSpaceGroupRgx.test(segment)) {
tempWords[lastWordIndex] += segment;
} else {
tempWords.push(segment);
}
}
prevSeg = wordSegment;
}
for (let i = 0, l = tempWords.length; i < l; i++) {
const word = tempWords[i];
if (!word.trim()) {
// Preserve whitespace only if includeSpaces is false and if the current space is not the first node
if (i && includeSpaces) continue;
$wordsFragment.appendChild(doc.createTextNode(word));
} else {
const nextWord = tempWords[i + 1];
const hasWordFollowingSpace = includeSpaces && nextWord && !nextWord.trim();
const wordToProcess = word;
const charSegments = charTemplate ? graphemeSegmenter.segment(wordToProcess) : null;
const $charsFragment = charTemplate ? doc.createDocumentFragment() : doc.createTextNode(hasWordFollowingSpace ? word + '\xa0' : word);
if (charTemplate) {
const charSegmentsArray = [...charSegments];
for (let j = 0, jl = charSegmentsArray.length; j < jl; j++) {
const charSegment = charSegmentsArray[j];
const isLastChar = j === jl - 1;
// If this is the last character and includeSpaces is true with a following space, append the space
const charText = isLastChar && hasWordFollowingSpace ? charSegment.segment + '\xa0' : charSegment.segment;
const $charNode = doc.createTextNode(charText);
processHTMLTemplate(charTemplate, chars, $charNode, /** @type {DocumentFragment} */($charsFragment), charType, debug, -1, words.length, chars.length);
}
}
if (wordTemplate) {
processHTMLTemplate(wordTemplate, words, $charsFragment, $wordsFragment, wordType, debug, -1, words.length, chars.length);
// Chars elements must be re-parsed in the split() method if both words and chars are parsed
} else if (charTemplate) {
$wordsFragment.appendChild($charsFragment);
} else {
$wordsFragment.appendChild(doc.createTextNode(word));
}
// Skip the next iteration if we included a space
if (hasWordFollowingSpace) i++;
}
}
node.parentNode.replaceChild($wordsFragment, node);
}
} else if (nodeType === 1) {
// Converting to an array is necessary to work around childNodes pottential mutation
const childNodes = /** @type {Array<Node>} */([.../** @type {*} */(node.childNodes)]);
for (let i = 0, l = childNodes.length; i < l; i++) this.splitNode(childNodes[i]);
}
}
/**
* @param {Boolean} clearCache
* @return {this}
*/
split(clearCache = false) {
const $el = this.$target;
const isCached = !!this.cache && !clearCache;
const lineTemplate = this.lineTemplate;
const wordTemplate = this.wordTemplate;
const charTemplate = this.charTemplate;
const fontsReady = doc.fonts.status !== 'loading';
const canSplitLines = lineTemplate && fontsReady;
this.ready = !lineTemplate || fontsReady;
if (canSplitLines || clearCache) {
// No need to revert effects animations here since it's already taken care by the refreshable
this.effectsCleanups.forEach(cleanup => isFnc(cleanup) && cleanup(this));
}
if (!isCached) {
if (clearCache) {
$el.innerHTML = this.html;
this.words.length = this.chars.length = 0;
}
this.splitNode($el);
this.cache = $el.innerHTML;
}
if (canSplitLines) {
if (isCached) $el.innerHTML = this.cache;
this.lines.length = 0;
if (wordTemplate) this.words = getAllTopLevelElements($el, wordType);
}
// Always reparse characters after a line reset or if both words and chars are activated
if (charTemplate && (canSplitLines || wordTemplate)) {
this.chars = getAllTopLevelElements($el, charType);
}
// Words are used when lines only and prioritized over chars
const elementsArray = this.words.length ? this.words : this.chars;
let y, linesCount = 0;
for (let i = 0, l = elementsArray.length; i < l; i++) {
const $el = elementsArray[i];
const { top, height } = $el.getBoundingClientRect();
if (!isUnd(y) && top - y > height * .5) linesCount++;
$el.setAttribute(dataLine, `${linesCount}`);
const nested = $el.querySelectorAll(`[${dataLine}]`);
let c = nested.length;
while (c--) nested[c].setAttribute(dataLine, `${linesCount}`);
y = top;
}
if (canSplitLines) {
const linesFragment = doc.createDocumentFragment();
const parents = new Set();
const clones = [];
for (let lineIndex = 0; lineIndex < linesCount + 1; lineIndex++) {
const $clone = /** @type {HTMLElement} */($el.cloneNode(true));
filterLineElements($clone, lineIndex, new Set()).forEach($el => {
const $parent = $el.parentNode;
if ($parent) {
if ($el.nodeType === 1) parents.add(/** @type {HTMLElement} */($parent));
$parent.removeChild($el);
}
});
clones.push($clone);
}
parents.forEach(filterEmptyElements);
for (let cloneIndex = 0, clonesLength = clones.length; cloneIndex < clonesLength; cloneIndex++) {
processHTMLTemplate(lineTemplate, this.lines, clones[cloneIndex], linesFragment, lineType, this.debug, cloneIndex);
}
$el.innerHTML = '';
$el.appendChild(linesFragment);
if (wordTemplate) this.words = getAllTopLevelElements($el, wordType);
if (charTemplate) this.chars = getAllTopLevelElements($el, charType);
}
// Remove the word wrappers and clear the words array if lines split only
if (this.linesOnly) {
const words = this.words;
let w = words.length;
while (w--) {
const $word = words[w];
$word.replaceWith($word.textContent);
}
words.length = 0;
}
if (this.accessible && (canSplitLines || !isCached)) {
const $accessible = doc.createElement('span');
// Make the accessible element visually-hidden (https://www.scottohara.me/blog/2017/04/14/inclusively-hidden.html)
$accessible.style.cssText = `position:absolute;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;white-space:nowrap;`;
// $accessible.setAttribute('tabindex', '-1');
$accessible.innerHTML = this.html;
$el.insertBefore($accessible, $el.firstChild);
this.lines.forEach(setAriaHidden);
this.words.forEach(setAriaHidden);
this.chars.forEach(setAriaHidden);
}
this.width = /** @type {HTMLElement} */($el).offsetWidth;
if (canSplitLines || clearCache) {
this.effects.forEach((effect, i) => this.effectsCleanups[i] = effect(this));
}
return this;
}
refresh() {
this.split(true);
}
}
/**
* @param {Element|NodeList|String|Array<Element>} target
* @param {TextSplitterParams} [parameters]
* @return {TextSplitter}
*/
const splitText = (target, parameters) => new TextSplitter(target, parameters);
/**
* @deprecated text.split() is deprecated, import splitText() directly, or text.splitText()
*
* @param {HTMLElement|NodeList|String|Array<HTMLElement>} target
* @param {TextSplitterParams} [parameters]
* @return {TextSplitter}
*/
const split = (target, parameters) => {
console.warn('text.split() is deprecated, import splitText() directly, or text.splitText()');
return new TextSplitter(target, parameters);
};
export { TextSplitter, split, splitText };