UNPKG

shave

Version:

Shave is a javascript plugin that truncates multi-line text within a html element based on set max height

16 lines 2.27 kB
/** shave - Shave is a javascript plugin that truncates multi-line text within a html element based on set max height @version v5.1.0 @link https://github.com/yowainwright/shave#readme @author Jeff Wainwright <yowainwright@gmail.com> (jeffry.in) @license MIT **/ var jqueryShave=(()=>{function Z(t){return typeof t=="string"?[...document.querySelectorAll(t)]:"length"in t?[...t]:[t]}function N(t,o,n={}){if(typeof o>"u"||isNaN(o))throw Error("maxHeight is required");let i=Z(t);if(!i.length)return;let{character:T="\u2026",classname:w="js-shave",spaces:E=!0,charclassname:C="js-shave-char",link:r={},delimiter:l}=n,g=typeof E=="boolean"?E:!0,x=r&&JSON.stringify(r)!=="{}"&&r.href,L=x?"a":"span";for(let v=0;v<i.length;v+=1){let e=i[v],s=e.style,O=e.querySelector("."+w),f=e.textContent===void 0?"innerText":"textContent";O&&(e.removeChild(e.querySelector("."+C)),e[f]=e[f]);let j=e[f],a;if(l?a=j.split(l):a=g?j.split(" "):j,a.length<2)continue;let P=s.height;s.height="auto";let S=s.maxHeight;if(s.maxHeight="none",e.offsetHeight<=o){s.height=P,s.maxHeight=S;continue}let q=x&&r.textContent?r.textContent:T,d=document.createElement(L),k={className:C,textContent:q};for(let c in k)d[c]=k[c],d.textContent=T;if(x)for(let c in r)d[c]=r[c];let h=a.length-1,A=0,y;for(;A<h;){y=A+h+1>>1;let c=a.slice(0,y);e[f]=H(l,g,c),e.insertAdjacentElement("beforeend",d),e.offsetHeight>o?h=y-1:A=y}let Q=a.slice(0,h);e[f]=H(l,g,Q),e.insertAdjacentElement("beforeend",d);let u=a.slice(h),b=Array.isArray(u),p="";l&&b?p=l+u.join(l):g&&b?p=" "+u.join(" "):b?p=u.join(""):p=u;let W=document.createTextNode(p),m=document.createElement("span");m.classList.add(w),m.style.display="none",m.appendChild(W),e.insertAdjacentElement("beforeend",m),s.height=P,s.maxHeight=S}}function H(t,o,n){let i=Array.isArray(n);return t&&i?n.join(t):o&&i?n.join(" "):i?n.join(""):n}if(typeof window<"u"){let t=window.$||window.jQuery||window.Zepto;t&&(t.fn.shave=function(n,i){return N(this,n,i),this})}})(); // Auto-initialize jQuery plugin if jQuery is available if (typeof jQuery !== 'undefined' || typeof $ !== 'undefined') { const jq = jQuery || $; if (jq && jq.fn && !jq.fn.shave) { jqueryShave.default && jqueryShave.default(jq); } } //# sourceMappingURL=jquery.shave.global.js.map