text-slicer 1.4.0-dev.7 → 1.4.0-dev.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1 +1 @@
1
- "use strict";class a{textElement;originalText;splitMode;cssVariables;dataAttributes;waitForFonts;fontReadyTimeout;stabilizeLayout;nowrapWords;useFlexWords;charIndexCounter=0;destroyed=!1;constructor(t={}){const{container:s=".text-slicer",splitMode:e="both",cssVariables:n=!1,dataAttributes:i=!1,waitForFonts:r=!1,fontReadyTimeout:o=1500,stabilizeLayout:l=!1,nowrapWords:h=!1,useFlexWords:d=!0}=t;if(this.textElement=typeof s=="string"?document.querySelector(s):s??null,!this.textElement)return this.originalText="",this.splitMode="both",this.cssVariables=!1,this.dataAttributes=!1,this.waitForFonts=!1,this.fontReadyTimeout=0,this.stabilizeLayout=!1,this.nowrapWords=!1,void(this.useFlexWords=!0);this.originalText=(this.textElement.textContent??"").trim(),this.splitMode=e,this.cssVariables=n,this.dataAttributes=i,this.waitForFonts=r,this.fontReadyTimeout=o,this.stabilizeLayout=l,this.nowrapWords=h,this.useFlexWords=d,this.originalText.length>0&&this.textElement.setAttribute("aria-label",this.originalText)}async init(){this.textElement&&(this.waitForFonts&&await a.waitFontsReady(this.fontReadyTimeout).catch(()=>{}),await a.nextFrame(),this.split())}destroy(){this.textElement&&!this.destroyed&&(this.textElement.innerHTML="",this.textElement.textContent=this.originalText,this.textElement.removeAttribute("aria-hidden"),this.destroyed=!0)}split(){if(!this.textElement)return;this.clear(),this.charIndexCounter=0;const t=document.createDocumentFragment(),s=this.originalText.split(" "),e=this.originalText.length;this.splitMode==="words"||this.splitMode==="both"?this.splitWords(t,s):this.splitMode==="chars"&&this.splitChars(t),this.textElement.appendChild(t),a.forceReflow(this.textElement),this.cssVariables&&(this.textElement.style.setProperty("--word-total",String(s.length)),this.textElement.style.setProperty("--char-total",String(e))),this.textElement.setAttribute("aria-hidden","false")}splitWords(t,s){s.forEach((e,n)=>{if(this.splitMode==="both"){const i=this.createWordSpan(n,e);for(const r of e)i.append(this.createCharSpan(r,!0));t.append(i)}else{const i=this.createWordSpan(n);i.append(document.createTextNode(e)),t.append(i)}n<s.length-1&&t.append(a.createSpaceSpan())})}splitChars(t){for(const s of this.originalText)t.append(this.createCharSpan(s,!1))}createWordSpan(t,s=""){const e=document.createElement("span");return e.classList.add("word"),this.dataAttributes&&e.setAttribute("data-word",s),this.cssVariables&&e.style.setProperty("--word-index",String(t)),(this.stabilizeLayout||this.useFlexWords)&&(a.applyWordLayout(e,this.useFlexWords),this.nowrapWords&&(e.style.whiteSpace="nowrap")),e}createCharSpan(t,s){const e=document.createElement("span");return e.textContent=t,this.dataAttributes&&e.setAttribute("data-char",t),t===" "?e.classList.add("whitespace"):(e.classList.add("char"),this.cssVariables&&e.style.setProperty("--char-index",String(this.charIndexCounter)),(this.stabilizeLayout||this.useFlexWords)&&a.applyCharLayout(e,s),this.charIndexCounter+=1),e}static createSpaceSpan(){const t=document.createElement("span");return t.classList.add("whitespace"),t.textContent=" ",t}clear(){this.textElement&&(this.textElement.innerHTML="")}static applyWordLayout(t,s){s?(t.style.display="inline-flex",t.style.flexWrap="nowrap",t.style.alignItems="baseline",t.style.verticalAlign="baseline",t.style.lineHeight="1em"):(t.style.display="inline-block",t.style.verticalAlign="baseline",t.style.lineHeight="1em"),t.style.backfaceVisibility="hidden"}static applyCharLayout(t,s){s?t.style.display="block":(t.style.display="inline-block",t.style.verticalAlign="baseline"),t.style.lineHeight="1em",t.style.willChange="transform",t.style.backfaceVisibility="hidden"}static forceReflow(t){t.offsetHeight}static nextFrame(){return new Promise(t=>requestAnimationFrame(()=>t()))}static getFontFaceSet(){const t=document;return typeof t.fonts=="object"&&t.fonts?t.fonts:null}static waitFontsReady(t){const s=a.getFontFaceSet();return s&&s.ready!==void 0?new Promise(e=>{let n=!1;const i=()=>{n||(n=!0,e())};s.ready.then(()=>i()).catch(()=>i()),t>0&&window.setTimeout(()=>i(),t)}):Promise.resolve()}}module.exports=a;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p={splitMode:"both",cssVariables:!1,dataAttributes:!1,keepWhitespaceNodes:!0,freezeWordWidths:!1},i=Object.freeze({word:"ts-word",char:"ts-char",whitespace:"ts-whitespace"}),o=" ",u=t=>typeof window>"u"||typeof document>"u"?null:t?typeof t=="string"?document.querySelector(t):t:null,a=t=>{const e=Intl.Segmenter;if(typeof e=="function"){const s=new e("en",{granularity:"grapheme"});return Array.from(s.segment(t),r=>r.segment)}return Array.from(t)},d=t=>t.split(o),h=t=>{const e={};return Object.keys(t).forEach(s=>{const r=t[s];r!==void 0&&(e[s]=r)}),e};exports.CLASSNAMES=i,exports.TextSlicer=class{el;original;opts;callbacks;charIndex;mounted;ro=null;frozen=!1;freezeWordWidthsBound=()=>{this.freezeWordWidths()};constructor(t={},e){const s=u(t.container);this.el=s,this.original=(r=>!!r&&typeof HTMLElement<"u"&&r instanceof HTMLElement)(s)?s.textContent?.toString()??"":"",this.opts={...p,...h(t)},this.callbacks=e,this.charIndex=0,this.mounted=!1}get metrics(){const t=this.original;return{wordTotal:t.length?d(t).length:0,charTotal:t.length,renderedAt:Date.now()}}init(){this.el&&(this.mounted=!0,this.split())}reinit(t,e){this.el&&(typeof t=="string"&&(this.original=t),e&&(this.opts={...this.opts,...h(e)}),this.split())}clear(){this.el&&(this.unfreezeWordWidths(),this.el.replaceChildren())}split(){if(!this.el)return;this.clear(),this.charIndex=0;const t=this.original,e=document.createDocumentFragment(),s=d(t);this.opts.splitMode==="chars"?this.appendChars(e,t):this.appendWords(e,s),this.el.appendChild(e),this.opts.cssVariables&&(this.el.style.setProperty("--word-total",String(s.length)),this.el.style.setProperty("--char-total",String(t.length))),this.scheduleFreezeWordWidths().then(()=>{this.callbacks?.onAfterRender?.(this.metrics)}).catch(()=>{})}destroy(){this.el&&(this.detachResizeObserver(),this.clear(),this.mounted=!1)}updateOptions(t){this.opts={...this.opts,...h(t)},this.mounted&&this.split()}appendWords(t,e){e.forEach((s,r)=>{if(this.opts.splitMode==="both"){const n=this.createWordSpan(r,s);for(const c of a(s)){const l=this.createCharSpan(c);n.append(l)}t.append(n)}else{const n=this.createWordSpan(r);n.append(document.createTextNode(s)),t.append(n)}r<e.length-1&&t.append(this.createSpaceSpan())})}appendChars(t,e){for(const s of a(e)){const r=this.createCharSpan(s);t.append(r)}}createWordSpan(t,e=""){const s=document.createElement("span");return s.classList.add(i.word),this.opts.dataAttributes&&e&&s.setAttribute("data-word",e),this.opts.cssVariables&&s.style.setProperty("--word-index",String(t)),s}createCharSpan(t){const e=document.createElement("span");return e.textContent=t,this.opts.dataAttributes&&e.setAttribute("data-char",t),t===o?(e.classList.add(i.whitespace),this.opts.keepWhitespaceNodes||(e.textContent=o)):(e.classList.add(i.char),this.opts.cssVariables&&e.style.setProperty("--char-index",String(this.charIndex)),this.charIndex+=1),e}createSpaceSpan(){const t=document.createElement("span");return t.classList.add(i.whitespace),t.textContent=o,t}async scheduleFreezeWordWidths(){if(this.el&&this.opts.freezeWordWidths){try{await document.fonts?.ready}catch{}await new Promise(t=>requestAnimationFrame(()=>t())),this.freezeWordWidths(),this.attachResizeObserver()}}freezeWordWidths(){this.el&&(this.el.querySelectorAll(`.${i.word}`).forEach(t=>{t.style.width="",t.style.flex="";const{width:e}=t.getBoundingClientRect();t.style.width=`${Math.ceil(e)}px`,t.style.flex="0 0 auto"}),this.frozen=!0)}unfreezeWordWidths(){!this.el||!this.frozen||(this.el.querySelectorAll(`.${i.word}`).forEach(t=>{t.style.width="",t.style.flex=""}),this.frozen=!1)}attachResizeObserver(){this.el&&this.opts.freezeWordWidths&&(this.ro||(this.ro=new ResizeObserver(()=>{this.freezeWordWidths()}),this.ro.observe(this.el)),window.addEventListener("resize",this.freezeWordWidthsBound,{passive:!0}))}detachResizeObserver(){this.ro&&(this.ro.disconnect(),this.ro=null),window.removeEventListener("resize",this.freezeWordWidthsBound)}};
package/dist/index.d.ts CHANGED
@@ -4,40 +4,48 @@ export interface TextSlicerOptions {
4
4
  splitMode?: SplitMode;
5
5
  cssVariables?: boolean;
6
6
  dataAttributes?: boolean;
7
- waitForFonts?: boolean;
8
- fontReadyTimeout?: number;
9
- stabilizeLayout?: boolean;
10
- nowrapWords?: boolean;
11
- useFlexWords?: boolean;
7
+ keepWhitespaceNodes?: boolean;
8
+ freezeWordWidths?: boolean;
12
9
  }
13
- declare class TextSlicer {
14
- private readonly textElement;
15
- private readonly originalText;
16
- private readonly splitMode;
17
- private readonly cssVariables;
18
- private readonly dataAttributes;
19
- private readonly waitForFonts;
20
- private readonly fontReadyTimeout;
21
- private readonly stabilizeLayout;
22
- private readonly nowrapWords;
23
- private readonly useFlexWords;
24
- private charIndexCounter;
25
- private destroyed;
26
- constructor(options?: TextSlicerOptions);
27
- init(): Promise<void>;
10
+ export interface TextSlicerMetrics {
11
+ wordTotal: number;
12
+ charTotal: number;
13
+ renderedAt: number;
14
+ }
15
+ export interface TextSlicerCallbacks {
16
+ onAfterRender?: (metrics: TextSlicerMetrics) => void;
17
+ }
18
+ export declare const CLASSNAMES: Readonly<{
19
+ word: "ts-word";
20
+ char: "ts-char";
21
+ whitespace: "ts-whitespace";
22
+ }>;
23
+ export declare class TextSlicer {
24
+ private readonly el;
25
+ private original;
26
+ private opts;
27
+ private callbacks;
28
+ private charIndex;
29
+ private mounted;
30
+ private ro;
31
+ private frozen;
32
+ private freezeWordWidthsBound;
33
+ constructor(options?: TextSlicerOptions, callbacks?: TextSlicerCallbacks);
34
+ get metrics(): TextSlicerMetrics;
35
+ init(): void;
36
+ reinit(newText?: string, next?: Partial<TextSlicerOptions>): void;
37
+ clear(): void;
38
+ split(): void;
28
39
  destroy(): void;
29
- private split;
30
- private splitWords;
31
- private splitChars;
40
+ updateOptions(next: Partial<TextSlicerOptions>): void;
41
+ private appendWords;
42
+ private appendChars;
32
43
  private createWordSpan;
33
44
  private createCharSpan;
34
- private static createSpaceSpan;
35
- private clear;
36
- private static applyWordLayout;
37
- private static applyCharLayout;
38
- private static forceReflow;
39
- private static nextFrame;
40
- private static getFontFaceSet;
41
- private static waitFontsReady;
45
+ private createSpaceSpan;
46
+ private scheduleFreezeWordWidths;
47
+ private freezeWordWidths;
48
+ private unfreezeWordWidths;
49
+ private attachResizeObserver;
50
+ private detachResizeObserver;
42
51
  }
43
- export default TextSlicer;
package/dist/index.es.js CHANGED
@@ -1,92 +1,126 @@
1
- class n {
2
- textElement;
3
- originalText;
4
- splitMode;
5
- cssVariables;
6
- dataAttributes;
7
- waitForFonts;
8
- fontReadyTimeout;
9
- stabilizeLayout;
10
- nowrapWords;
11
- useFlexWords;
12
- charIndexCounter = 0;
13
- destroyed = !1;
14
- constructor(t = {}) {
15
- const { container: s = ".text-slicer", splitMode: e = "both", cssVariables: a = !1, dataAttributes: i = !1, waitForFonts: r = !1, fontReadyTimeout: o = 1500, stabilizeLayout: l = !1, nowrapWords: h = !1, useFlexWords: d = !0 } = t;
16
- if (this.textElement = typeof s == "string" ? document.querySelector(s) : s ?? null, !this.textElement) return this.originalText = "", this.splitMode = "both", this.cssVariables = !1, this.dataAttributes = !1, this.waitForFonts = !1, this.fontReadyTimeout = 0, this.stabilizeLayout = !1, this.nowrapWords = !1, void (this.useFlexWords = !0);
17
- this.originalText = (this.textElement.textContent ?? "").trim(), this.splitMode = e, this.cssVariables = a, this.dataAttributes = i, this.waitForFonts = r, this.fontReadyTimeout = o, this.stabilizeLayout = l, this.nowrapWords = h, this.useFlexWords = d, this.originalText.length > 0 && this.textElement.setAttribute("aria-label", this.originalText);
18
- }
19
- async init() {
20
- this.textElement && (this.waitForFonts && await n.waitFontsReady(this.fontReadyTimeout).catch(() => {
21
- }), await n.nextFrame(), this.split());
1
+ const u = { splitMode: "both", cssVariables: !1, dataAttributes: !1, keepWhitespaceNodes: !0, freezeWordWidths: !1 }, n = Object.freeze({ word: "ts-word", char: "ts-char", whitespace: "ts-whitespace" }), h = " ", f = (r) => typeof window > "u" || typeof document > "u" ? null : r ? typeof r == "string" ? document.querySelector(r) : r : null, d = (r) => {
2
+ const t = Intl.Segmenter;
3
+ if (typeof t == "function") {
4
+ const e = new t("en", { granularity: "grapheme" });
5
+ return Array.from(e.segment(r), (s) => s.segment);
6
+ }
7
+ return Array.from(r);
8
+ }, c = (r) => r.split(h), a = (r) => {
9
+ const t = {};
10
+ return Object.keys(r).forEach((e) => {
11
+ const s = r[e];
12
+ s !== void 0 && (t[e] = s);
13
+ }), t;
14
+ };
15
+ class W {
16
+ el;
17
+ original;
18
+ opts;
19
+ callbacks;
20
+ charIndex;
21
+ mounted;
22
+ ro = null;
23
+ frozen = !1;
24
+ freezeWordWidthsBound = () => {
25
+ this.freezeWordWidths();
26
+ };
27
+ constructor(t = {}, e) {
28
+ const s = f(t.container);
29
+ this.el = s, this.original = ((i) => !!i && typeof HTMLElement < "u" && i instanceof HTMLElement)(s) ? s.textContent?.toString() ?? "" : "", this.opts = { ...u, ...a(t) }, this.callbacks = e, this.charIndex = 0, this.mounted = !1;
30
+ }
31
+ get metrics() {
32
+ const t = this.original;
33
+ return { wordTotal: t.length ? c(t).length : 0, charTotal: t.length, renderedAt: Date.now() };
34
+ }
35
+ init() {
36
+ this.el && (this.mounted = !0, this.split());
37
+ }
38
+ reinit(t, e) {
39
+ this.el && (typeof t == "string" && (this.original = t), e && (this.opts = { ...this.opts, ...a(e) }), this.split());
22
40
  }
23
- destroy() {
24
- this.textElement && !this.destroyed && (this.textElement.innerHTML = "", this.textElement.textContent = this.originalText, this.textElement.removeAttribute("aria-hidden"), this.destroyed = !0);
41
+ clear() {
42
+ this.el && (this.unfreezeWordWidths(), this.el.replaceChildren());
25
43
  }
26
44
  split() {
27
- if (!this.textElement) return;
28
- this.clear(), this.charIndexCounter = 0;
29
- const t = document.createDocumentFragment(), s = this.originalText.split(" "), e = this.originalText.length;
30
- this.splitMode === "words" || this.splitMode === "both" ? this.splitWords(t, s) : this.splitMode === "chars" && this.splitChars(t), this.textElement.appendChild(t), n.forceReflow(this.textElement), this.cssVariables && (this.textElement.style.setProperty("--word-total", String(s.length)), this.textElement.style.setProperty("--char-total", String(e))), this.textElement.setAttribute("aria-hidden", "false");
31
- }
32
- splitWords(t, s) {
33
- s.forEach((e, a) => {
34
- if (this.splitMode === "both") {
35
- const i = this.createWordSpan(a, e);
36
- for (const r of e) i.append(this.createCharSpan(r, !0));
37
- t.append(i);
45
+ if (!this.el) return;
46
+ this.clear(), this.charIndex = 0;
47
+ const t = this.original, e = document.createDocumentFragment(), s = c(t);
48
+ this.opts.splitMode === "chars" ? this.appendChars(e, t) : this.appendWords(e, s), this.el.appendChild(e), this.opts.cssVariables && (this.el.style.setProperty("--word-total", String(s.length)), this.el.style.setProperty("--char-total", String(t.length))), this.scheduleFreezeWordWidths().then(() => {
49
+ this.callbacks?.onAfterRender?.(this.metrics);
50
+ }).catch(() => {
51
+ });
52
+ }
53
+ destroy() {
54
+ this.el && (this.detachResizeObserver(), this.clear(), this.mounted = !1);
55
+ }
56
+ updateOptions(t) {
57
+ this.opts = { ...this.opts, ...a(t) }, this.mounted && this.split();
58
+ }
59
+ appendWords(t, e) {
60
+ e.forEach((s, i) => {
61
+ if (this.opts.splitMode === "both") {
62
+ const o = this.createWordSpan(i, s);
63
+ for (const l of d(s)) {
64
+ const p = this.createCharSpan(l);
65
+ o.append(p);
66
+ }
67
+ t.append(o);
38
68
  } else {
39
- const i = this.createWordSpan(a);
40
- i.append(document.createTextNode(e)), t.append(i);
69
+ const o = this.createWordSpan(i);
70
+ o.append(document.createTextNode(s)), t.append(o);
41
71
  }
42
- a < s.length - 1 && t.append(n.createSpaceSpan());
72
+ i < e.length - 1 && t.append(this.createSpaceSpan());
43
73
  });
44
74
  }
45
- splitChars(t) {
46
- for (const s of this.originalText) t.append(this.createCharSpan(s, !1));
75
+ appendChars(t, e) {
76
+ for (const s of d(e)) {
77
+ const i = this.createCharSpan(s);
78
+ t.append(i);
79
+ }
47
80
  }
48
- createWordSpan(t, s = "") {
49
- const e = document.createElement("span");
50
- return e.classList.add("word"), this.dataAttributes && e.setAttribute("data-word", s), this.cssVariables && e.style.setProperty("--word-index", String(t)), (this.stabilizeLayout || this.useFlexWords) && (n.applyWordLayout(e, this.useFlexWords), this.nowrapWords && (e.style.whiteSpace = "nowrap")), e;
81
+ createWordSpan(t, e = "") {
82
+ const s = document.createElement("span");
83
+ return s.classList.add(n.word), this.opts.dataAttributes && e && s.setAttribute("data-word", e), this.opts.cssVariables && s.style.setProperty("--word-index", String(t)), s;
51
84
  }
52
- createCharSpan(t, s) {
85
+ createCharSpan(t) {
53
86
  const e = document.createElement("span");
54
- return e.textContent = t, this.dataAttributes && e.setAttribute("data-char", t), t === " " ? e.classList.add("whitespace") : (e.classList.add("char"), this.cssVariables && e.style.setProperty("--char-index", String(this.charIndexCounter)), (this.stabilizeLayout || this.useFlexWords) && n.applyCharLayout(e, s), this.charIndexCounter += 1), e;
87
+ return e.textContent = t, this.opts.dataAttributes && e.setAttribute("data-char", t), t === h ? (e.classList.add(n.whitespace), this.opts.keepWhitespaceNodes || (e.textContent = h)) : (e.classList.add(n.char), this.opts.cssVariables && e.style.setProperty("--char-index", String(this.charIndex)), this.charIndex += 1), e;
55
88
  }
56
- static createSpaceSpan() {
89
+ createSpaceSpan() {
57
90
  const t = document.createElement("span");
58
- return t.classList.add("whitespace"), t.textContent = " ", t;
59
- }
60
- clear() {
61
- this.textElement && (this.textElement.innerHTML = "");
91
+ return t.classList.add(n.whitespace), t.textContent = h, t;
62
92
  }
63
- static applyWordLayout(t, s) {
64
- s ? (t.style.display = "inline-flex", t.style.flexWrap = "nowrap", t.style.alignItems = "baseline", t.style.verticalAlign = "baseline", t.style.lineHeight = "1em") : (t.style.display = "inline-block", t.style.verticalAlign = "baseline", t.style.lineHeight = "1em"), t.style.backfaceVisibility = "hidden";
65
- }
66
- static applyCharLayout(t, s) {
67
- s ? t.style.display = "block" : (t.style.display = "inline-block", t.style.verticalAlign = "baseline"), t.style.lineHeight = "1em", t.style.willChange = "transform", t.style.backfaceVisibility = "hidden";
93
+ async scheduleFreezeWordWidths() {
94
+ if (this.el && this.opts.freezeWordWidths) {
95
+ try {
96
+ await document.fonts?.ready;
97
+ } catch {
98
+ }
99
+ await new Promise((t) => requestAnimationFrame(() => t())), this.freezeWordWidths(), this.attachResizeObserver();
100
+ }
68
101
  }
69
- static forceReflow(t) {
70
- t.offsetHeight;
102
+ freezeWordWidths() {
103
+ this.el && (this.el.querySelectorAll(`.${n.word}`).forEach((t) => {
104
+ t.style.width = "", t.style.flex = "";
105
+ const { width: e } = t.getBoundingClientRect();
106
+ t.style.width = `${Math.ceil(e)}px`, t.style.flex = "0 0 auto";
107
+ }), this.frozen = !0);
71
108
  }
72
- static nextFrame() {
73
- return new Promise((t) => requestAnimationFrame(() => t()));
109
+ unfreezeWordWidths() {
110
+ !this.el || !this.frozen || (this.el.querySelectorAll(`.${n.word}`).forEach((t) => {
111
+ t.style.width = "", t.style.flex = "";
112
+ }), this.frozen = !1);
74
113
  }
75
- static getFontFaceSet() {
76
- const t = document;
77
- return typeof t.fonts == "object" && t.fonts ? t.fonts : null;
114
+ attachResizeObserver() {
115
+ this.el && this.opts.freezeWordWidths && (this.ro || (this.ro = new ResizeObserver(() => {
116
+ this.freezeWordWidths();
117
+ }), this.ro.observe(this.el)), window.addEventListener("resize", this.freezeWordWidthsBound, { passive: !0 }));
78
118
  }
79
- static waitFontsReady(t) {
80
- const s = n.getFontFaceSet();
81
- return s && s.ready !== void 0 ? new Promise((e) => {
82
- let a = !1;
83
- const i = () => {
84
- a || (a = !0, e());
85
- };
86
- s.ready.then(() => i()).catch(() => i()), t > 0 && window.setTimeout(() => i(), t);
87
- }) : Promise.resolve();
119
+ detachResizeObserver() {
120
+ this.ro && (this.ro.disconnect(), this.ro = null), window.removeEventListener("resize", this.freezeWordWidthsBound);
88
121
  }
89
122
  }
90
123
  export {
91
- n as default
124
+ n as CLASSNAMES,
125
+ W as TextSlicer
92
126
  };
package/dist/index.umd.js CHANGED
@@ -1 +1 @@
1
- (function(i,o){typeof exports=="object"&&typeof module<"u"?module.exports=o():typeof define=="function"&&define.amd?define(o):(i=typeof globalThis<"u"?globalThis:i||self).TextSlicer=o()})(this,function(){"use strict";class i{textElement;originalText;splitMode;cssVariables;dataAttributes;waitForFonts;fontReadyTimeout;stabilizeLayout;nowrapWords;useFlexWords;charIndexCounter=0;destroyed=!1;constructor(t={}){const{container:s=".text-slicer",splitMode:e="both",cssVariables:n=!1,dataAttributes:a=!1,waitForFonts:r=!1,fontReadyTimeout:l=1500,stabilizeLayout:h=!1,nowrapWords:d=!1,useFlexWords:c=!0}=t;if(this.textElement=typeof s=="string"?document.querySelector(s):s??null,!this.textElement)return this.originalText="",this.splitMode="both",this.cssVariables=!1,this.dataAttributes=!1,this.waitForFonts=!1,this.fontReadyTimeout=0,this.stabilizeLayout=!1,this.nowrapWords=!1,void(this.useFlexWords=!0);this.originalText=(this.textElement.textContent??"").trim(),this.splitMode=e,this.cssVariables=n,this.dataAttributes=a,this.waitForFonts=r,this.fontReadyTimeout=l,this.stabilizeLayout=h,this.nowrapWords=d,this.useFlexWords=c,this.originalText.length>0&&this.textElement.setAttribute("aria-label",this.originalText)}async init(){this.textElement&&(this.waitForFonts&&await i.waitFontsReady(this.fontReadyTimeout).catch(()=>{}),await i.nextFrame(),this.split())}destroy(){this.textElement&&!this.destroyed&&(this.textElement.innerHTML="",this.textElement.textContent=this.originalText,this.textElement.removeAttribute("aria-hidden"),this.destroyed=!0)}split(){if(!this.textElement)return;this.clear(),this.charIndexCounter=0;const t=document.createDocumentFragment(),s=this.originalText.split(" "),e=this.originalText.length;this.splitMode==="words"||this.splitMode==="both"?this.splitWords(t,s):this.splitMode==="chars"&&this.splitChars(t),this.textElement.appendChild(t),i.forceReflow(this.textElement),this.cssVariables&&(this.textElement.style.setProperty("--word-total",String(s.length)),this.textElement.style.setProperty("--char-total",String(e))),this.textElement.setAttribute("aria-hidden","false")}splitWords(t,s){s.forEach((e,n)=>{if(this.splitMode==="both"){const a=this.createWordSpan(n,e);for(const r of e)a.append(this.createCharSpan(r,!0));t.append(a)}else{const a=this.createWordSpan(n);a.append(document.createTextNode(e)),t.append(a)}n<s.length-1&&t.append(i.createSpaceSpan())})}splitChars(t){for(const s of this.originalText)t.append(this.createCharSpan(s,!1))}createWordSpan(t,s=""){const e=document.createElement("span");return e.classList.add("word"),this.dataAttributes&&e.setAttribute("data-word",s),this.cssVariables&&e.style.setProperty("--word-index",String(t)),(this.stabilizeLayout||this.useFlexWords)&&(i.applyWordLayout(e,this.useFlexWords),this.nowrapWords&&(e.style.whiteSpace="nowrap")),e}createCharSpan(t,s){const e=document.createElement("span");return e.textContent=t,this.dataAttributes&&e.setAttribute("data-char",t),t===" "?e.classList.add("whitespace"):(e.classList.add("char"),this.cssVariables&&e.style.setProperty("--char-index",String(this.charIndexCounter)),(this.stabilizeLayout||this.useFlexWords)&&i.applyCharLayout(e,s),this.charIndexCounter+=1),e}static createSpaceSpan(){const t=document.createElement("span");return t.classList.add("whitespace"),t.textContent=" ",t}clear(){this.textElement&&(this.textElement.innerHTML="")}static applyWordLayout(t,s){s?(t.style.display="inline-flex",t.style.flexWrap="nowrap",t.style.alignItems="baseline",t.style.verticalAlign="baseline",t.style.lineHeight="1em"):(t.style.display="inline-block",t.style.verticalAlign="baseline",t.style.lineHeight="1em"),t.style.backfaceVisibility="hidden"}static applyCharLayout(t,s){s?t.style.display="block":(t.style.display="inline-block",t.style.verticalAlign="baseline"),t.style.lineHeight="1em",t.style.willChange="transform",t.style.backfaceVisibility="hidden"}static forceReflow(t){t.offsetHeight}static nextFrame(){return new Promise(t=>requestAnimationFrame(()=>t()))}static getFontFaceSet(){const t=document;return typeof t.fonts=="object"&&t.fonts?t.fonts:null}static waitFontsReady(t){const s=i.getFontFaceSet();return s&&s.ready!==void 0?new Promise(e=>{let n=!1;const a=()=>{n||(n=!0,e())};s.ready.then(()=>a()).catch(()=>a()),t>0&&window.setTimeout(()=>a(),t)}):Promise.resolve()}}return i});
1
+ (function(n,o){typeof exports=="object"&&typeof module<"u"?o(exports):typeof define=="function"&&define.amd?define(["exports"],o):o((n=typeof globalThis<"u"?globalThis:n||self).TextSlicer={})})(this,function(n){"use strict";const o={splitMode:"both",cssVariables:!1,dataAttributes:!1,keepWhitespaceNodes:!0,freezeWordWidths:!1},i=Object.freeze({word:"ts-word",char:"ts-char",whitespace:"ts-whitespace"}),a=" ",p=t=>typeof window>"u"||typeof document>"u"?null:t?typeof t=="string"?document.querySelector(t):t:null,c=t=>{const e=Intl.Segmenter;if(typeof e=="function"){const s=new e("en",{granularity:"grapheme"});return Array.from(s.segment(t),r=>r.segment)}return Array.from(t)},l=t=>t.split(a),d=t=>{const e={};return Object.keys(t).forEach(s=>{const r=t[s];r!==void 0&&(e[s]=r)}),e};n.CLASSNAMES=i,n.TextSlicer=class{el;original;opts;callbacks;charIndex;mounted;ro=null;frozen=!1;freezeWordWidthsBound=()=>{this.freezeWordWidths()};constructor(t={},e){const s=p(t.container);this.el=s,this.original=(r=>!!r&&typeof HTMLElement<"u"&&r instanceof HTMLElement)(s)?s.textContent?.toString()??"":"",this.opts={...o,...d(t)},this.callbacks=e,this.charIndex=0,this.mounted=!1}get metrics(){const t=this.original;return{wordTotal:t.length?l(t).length:0,charTotal:t.length,renderedAt:Date.now()}}init(){this.el&&(this.mounted=!0,this.split())}reinit(t,e){this.el&&(typeof t=="string"&&(this.original=t),e&&(this.opts={...this.opts,...d(e)}),this.split())}clear(){this.el&&(this.unfreezeWordWidths(),this.el.replaceChildren())}split(){if(!this.el)return;this.clear(),this.charIndex=0;const t=this.original,e=document.createDocumentFragment(),s=l(t);this.opts.splitMode==="chars"?this.appendChars(e,t):this.appendWords(e,s),this.el.appendChild(e),this.opts.cssVariables&&(this.el.style.setProperty("--word-total",String(s.length)),this.el.style.setProperty("--char-total",String(t.length))),this.scheduleFreezeWordWidths().then(()=>{this.callbacks?.onAfterRender?.(this.metrics)}).catch(()=>{})}destroy(){this.el&&(this.detachResizeObserver(),this.clear(),this.mounted=!1)}updateOptions(t){this.opts={...this.opts,...d(t)},this.mounted&&this.split()}appendWords(t,e){e.forEach((s,r)=>{if(this.opts.splitMode==="both"){const h=this.createWordSpan(r,s);for(const f of c(s)){const u=this.createCharSpan(f);h.append(u)}t.append(h)}else{const h=this.createWordSpan(r);h.append(document.createTextNode(s)),t.append(h)}r<e.length-1&&t.append(this.createSpaceSpan())})}appendChars(t,e){for(const s of c(e)){const r=this.createCharSpan(s);t.append(r)}}createWordSpan(t,e=""){const s=document.createElement("span");return s.classList.add(i.word),this.opts.dataAttributes&&e&&s.setAttribute("data-word",e),this.opts.cssVariables&&s.style.setProperty("--word-index",String(t)),s}createCharSpan(t){const e=document.createElement("span");return e.textContent=t,this.opts.dataAttributes&&e.setAttribute("data-char",t),t===a?(e.classList.add(i.whitespace),this.opts.keepWhitespaceNodes||(e.textContent=a)):(e.classList.add(i.char),this.opts.cssVariables&&e.style.setProperty("--char-index",String(this.charIndex)),this.charIndex+=1),e}createSpaceSpan(){const t=document.createElement("span");return t.classList.add(i.whitespace),t.textContent=a,t}async scheduleFreezeWordWidths(){if(this.el&&this.opts.freezeWordWidths){try{await document.fonts?.ready}catch{}await new Promise(t=>requestAnimationFrame(()=>t())),this.freezeWordWidths(),this.attachResizeObserver()}}freezeWordWidths(){this.el&&(this.el.querySelectorAll(`.${i.word}`).forEach(t=>{t.style.width="",t.style.flex="";const{width:e}=t.getBoundingClientRect();t.style.width=`${Math.ceil(e)}px`,t.style.flex="0 0 auto"}),this.frozen=!0)}unfreezeWordWidths(){!this.el||!this.frozen||(this.el.querySelectorAll(`.${i.word}`).forEach(t=>{t.style.width="",t.style.flex=""}),this.frozen=!1)}attachResizeObserver(){this.el&&this.opts.freezeWordWidths&&(this.ro||(this.ro=new ResizeObserver(()=>{this.freezeWordWidths()}),this.ro.observe(this.el)),window.addEventListener("resize",this.freezeWordWidthsBound,{passive:!0}))}detachResizeObserver(){this.ro&&(this.ro.disconnect(),this.ro=null),window.removeEventListener("resize",this.freezeWordWidthsBound)}},Object.defineProperty(n,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "text-slicer",
3
- "version": "1.4.0-dev.7",
3
+ "version": "1.4.0-dev.9",
4
4
  "description": "TextSlicer is designed to split text within an HTML element into separate words and/or characters, wrapping each word and/or character in separate span elements.",
5
5
  "author": "ux-ui.pro",
6
6
  "license": "MIT",