UNPKG

use-fit-text

Version:
3 lines (2 loc) 1.86 kB
var e,n=require("react"),t=(e=require("resize-observer-polyfill"))&&"object"==typeof e&&"default"in e?e.default:e,r={debug:10,info:20,warn:30,error:40,none:100},i="undefined"!=typeof window&&window.document&&window.document.createElement?n.useLayoutEffect:n.useEffect;module.exports=function(e){void 0===e&&(e={});var o=e.logLevel;void 0===o&&(o="info");var c=e.maxFontSize;void 0===c&&(c=100);var f=e.minFontSize;void 0===f&&(f=20);var u=e.onFinish,a=e.onStart,s=e.resolution;void 0===s&&(s=5);var l=r[o],S=n.useCallback(function(){return{calcKey:0,fontSize:c,fontSizePrev:f,fontSizeMax:c,fontSizeMin:f}},[c,f]),d=n.useRef(null),v=n.useRef(),z=n.useRef(!1),m=n.useState(S),w=m[0],M=m[1],h=w.calcKey,y=w.fontSize,x=w.fontSizeMax,b=w.fontSizeMin,g=w.fontSizePrev,F=null,K=n.useState(function(){return new t(function(){F=window.requestAnimationFrame(function(){z.current||(a&&a(),z.current=!0,M(Object.assign({},S(),{calcKey:h+1})))})})})[0];n.useEffect(function(){return d.current&&K.observe(d.current),function(){F&&window.cancelAnimationFrame(F),K.disconnect()}},[F,K]);var E=d.current&&d.current.innerHTML;return n.useEffect(function(){0===h||z.current||(E!==v.current&&(a&&a(),M(Object.assign({},S(),{calcKey:h+1}))),v.current=E)},[h,S,E,a]),i(function(){if(0!==h){var e=Math.abs(y-g)<=s,n=!!d.current&&(d.current.scrollHeight>d.current.offsetHeight||d.current.scrollWidth>d.current.offsetWidth),t=y>g;if(e)n&&y===g?(z.current=!1,l<=r.info&&console.info("[use-fit-text] reached `minFontSize = "+f+"` without fitting text")):n?M({fontSize:t?g:b,fontSizeMax:x,fontSizeMin:b,fontSizePrev:g,calcKey:h}):(z.current=!1,u&&u(y));else{var i,o=x,c=b;n?(i=t?g-y:b-y,o=Math.min(x,y)):(i=t?x-y:g-y,c=Math.max(b,y)),M({calcKey:h,fontSize:y+i/2,fontSizeMax:o,fontSizeMin:c,fontSizePrev:y})}}},[h,y,x,b,g,u,d,s]),{fontSize:y+"%",ref:d}}; //# sourceMappingURL=index.js.map