uwrap
Version:
A very fast and accurate text and line wrapping util
3 lines (2 loc) • 1.61 kB
JavaScript
/*! https://github.com/leeoniya/uWrap (v0.1.2) */
var uWrap=function(t){"use strict";const e="ABCDEFGHIJKLMNOPQRSTUVWXYZ",r=e+"abcdefghijklmnopqrstuvwxyz1234567890`~!@#$%^&*()_+-=[]\\{}|;':\",./<>? \t";return t.varPreLine=function(t){const n=function(t){const e=t.measureText("W").width,r=t.letterSpacing;t.letterSpacing="101px";const n=t.measureText("W").width;return t.letterSpacing=r,n>e}(t)?0:parseFloat(t.letterSpacing),l={};for(let e=0;r.length>e;e++)l[r.charCodeAt(e)]=t.measureText(r[e]).width+n;const o=parseFloat(t.wordSpacing);o>0&&(l[32]=o);const c={};for(let o=0;26>o;o++){let i=e.charCodeAt(o);c[i]={};for(let s=0;r.length>s;s++){let a=r.charCodeAt(s),u=t.measureText(`${e[o]}${r[s]}`).width-l[a]+n;c[i][a]=u}}const i=()=>{};function s(e,r,n=i){let o=0;for(;32===e.charCodeAt(o);)o++;let s=e.length-1;for(;32===e.charCodeAt(s);)s--;let a=o,u=0,h=0,f=-1,d=0,p=!1;for(let i=o;s>=i;i++){let o=e.charCodeAt(i),s=0;if(o in c){let t=e.charCodeAt(i+1);t in c[o]&&(s=c[o][t])}if(0===s&&(s=l[o]??(l[o]=t.measureText(e[i]).width)),32===o)e.charCodeAt(i+1)!==o&&(f=i+1,d=0),!p&&h>0&&(h+=s,u=i),p=!0;else if(10===o){if(!1===n(a,i))return;a=u=i+1,h=d=0,d=0,f=-1}else{if(u>a&&h+s>r){if(!1===n(a,u))return;h=d+s,a=u=f,d=0,f=-1}else 45===o&&e.charCodeAt(i+1)!==o&&(f=u=i+1,d=0),h+=s,d+=s;p=!1}}n(a,s+1)}let a=/\s|-/;return{each:s,split:(t,e,r=1/0)=>{let n=[];return a.test(t)?s(t,e,((e,l)=>{if(n.push(t.slice(e,l)),n.length===r)return!1})):n.push(t),n},count:(t,e)=>{let r=0;return a.test(t)?s(t,e,(()=>{r++})):r=1,r},test:(t,e)=>{let r=0;return a.test(t)?s(t,e,(()=>{if(2==++r)return!1})):r=1,2===r}}},t}({});