UNPKG

split-with-kerning

Version:

Split a text into words and letters and respect the kerning

2 lines (1 loc) 2.57 kB
(function(s,d){typeof exports=="object"&&typeof module<"u"?d(exports):typeof define=="function"&&define.amd?define(["exports"],d):(s=typeof globalThis<"u"?globalThis:s||self,d(s.SplitWithKerning={}))})(this,function(s){"use strict";function d(e,t,r){if(!e)return 0;const o=e.charToGlyph(t),i=e.charToGlyph(r);if(!o||!i)return 0;let f=e.getKerningValue(o,i);return f/=e.unitsPerEm,f}function T(e){const t={};for(const r of e.kerningPairs)for(const o of r.left)for(const i of r.right)t[o+i]=r.value;return{unitsPerEm:e.unitsPerEm,kerningPairs:t}}function C(e,t,r={}){var h;if(!e)throw new Error("Element is required");const{wordSelector:o=".word",charSelector:i=".char"}=r,f=Array.from(e.querySelectorAll(o)),p=[];for(const n of f){const c=Array.from(n.querySelectorAll(i));for(let l=0;l<c.length;l++){const g=c[l];if(g.textContent){const a=t(g.textContent,((h=c[l+1])==null?void 0:h.textContent)??"");p.push({element:g,margin:`${a}em`})}}}if(p.length>0)for(const{element:n,margin:c}of p)n.style.marginInlineEnd=c}function w(e,t,r={}){C(e,(o,i)=>d(t,o,i),r)}function x(e,t,r={}){C(e,(o,i)=>(t.kerningPairs[`${o}${i}`]??0)/t.unitsPerEm,r)}function N(e,t="letter"){const r=e.innerHTML,o=e.getAttribute("aria-label"),i={value:e.textContent??"",words:[],element:e};function f(n){var g;const c=document.createDocumentFragment();let l=[];t==="none"?l=[n.textContent??""]:l=((g=n.textContent)==null?void 0:g.split(/(\s+)/))??[];for(const a of l)if(!a.trim())c.appendChild(document.createTextNode(a));else{const u=document.createElement("span");u.ariaHidden="true",u.className="word";const y={value:a,element:u};if(t==="word")u.textContent=a;else if(t==="none")u.textContent=a;else{y.letters=[];for(const E of a){const m=document.createElement("span");m.ariaHidden="true",m.className="char",m.textContent=E,u.appendChild(m);const b={value:E,element:m};y.letters.push(b)}}i.words.push(y),c.appendChild(u)}return c}function p(n){if(n.nodeType===Node.TEXT_NODE)return f(n);if(n.nodeType===Node.ELEMENT_NODE){const c=n.cloneNode(!1);for(const l of n.childNodes)c.appendChild(p(l));return c}return document.createDocumentFragment()}const h=document.createDocumentFragment();for(const n of[...e.childNodes])h.appendChild(p(n));return e.ariaLabel=e.textContent??"",e.innerHTML="",e.appendChild(h),{reset:()=>{e.innerHTML=r,o?e.setAttribute("aria-label",o):e.removeAttribute("aria-label")},splitted:i}}s.applyKerningFromExport=x,s.applyKerningFromFont=w,s.convertOptimizedToKerningPairs=T,s.getKerningValue=d,s.splitText=N,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})});