shave
Version:
Shave is a javascript plugin that truncates multi-line text within a html element based on set max height
2 lines (1 loc) • 2.11 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).shave=t()}(this,function(){"use strict";function T(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var o,r,i=n.call(e),a=[];try{for(;(void 0===t||0<t--)&&!(o=i.next()).done;)a.push(o.value)}catch(e){r={error:e}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}return a}function w(e,t,n){if(n||2===arguments.length)for(var o,r=0,i=t.length;r<i;r++)!o&&r in t||((o=o||Array.prototype.slice.call(t,0,r))[r]=t[r]);return e.concat(o||Array.prototype.slice.call(t))}return function(e,t,n){if(void 0===n&&(n={}),void 0===t||isNaN(t))throw Error("maxHeight is required");var o="string"==typeof(e=e)?w([],T(document.querySelectorAll(e)),!1):"length"in e?w([],T(e),!1):[e];if(o.length)for(var r=void 0===(e=n.character)?"…":e,i=void 0===(e=n.classname)?"js-shave":e,e=void 0===(e=n.spaces)||e,a=n.charclassname,l=void 0===a?"js-shave-char":a,f=void 0===(a=n.link)?{}:a,s="boolean"!=typeof e||e,c=f&&"{}"!==JSON.stringify(f)&&f.href,d=c?"a":"span",h=0;h<o.length;h+=1){var u=o[h],v=u.style,y=u.querySelector("."+i),m=void 0===u.textContent?"innerText":"textContent",y=(y&&(u.removeChild(u.querySelector("."+l)),u[m]=u[m]),u[m]),p=s?y.split(" "):y;if(!(p.length<2)){var y=v.height,g=(v.height="auto",v.maxHeight);if(v.maxHeight="none",!(u.offsetHeight<=t)){var x,b=c&&f.textContent?f.textContent:r,j=document.createElement(d),C={className:l,textContent:b};for(x in C)j[x]=C[x],j.textContent=r;if(c)for(var A in f)j[A]=f[A];for(var E=p.length-1,H=0;H<E;){var S,N=p.slice(0,S=H+E+1>>1);u[m]=s?N.join(" "):N,u.insertAdjacentElement("beforeend",j),u.offsetHeight>t?E=S-1:H=S}var b=p.slice(0,E),b=(u[m]=s?b.join(" "):b,u.insertAdjacentElement("beforeend",j),p.slice(E)),b=s?" "+b.join(" "):b,b=document.createTextNode(b),q=document.createElement("span");q.classList.add(i),q.style.display="none",q.appendChild(b),u.insertAdjacentElement("beforeend",q)}v.height=y,v.maxHeight=g}}}});