use-element-fit
Version:
useElementFit is a React hook that allows you to measure and element's based on certain restraints, similar to object-fit in CSS.
3 lines (2 loc) • 1.27 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("use-resize-observer")):"function"==typeof define&&define.amd?define(["exports","react","use-resize-observer"],t):t((e=e||self).useElementFit={},e.react,e.useResizeObserver)}(this,function(e,t,r){"use strict";var s;r=r&&r.hasOwnProperty("default")?r.default:r,function(e){e.CONTAIN="contain",e.COVER="cover",e.ALIGN_ONLY="align-only"}(s||(s={}));var n=s;e.ScaleMode=n,e.useElementFit=(e,s,i=n.CONTAIN,u=.5,o=.5,a,c)=>{const[f,d,h]=r(),[N,O]=t.useState(1),[l,y]=t.useState(1),[C,p]=t.useState(1),[b,v]=t.useState(1);return t.useEffect(()=>{const{width:t,height:r,x:f,y:N}=((e,t,r,s,i,u=.5,o=.5,a,c)=>{let f=0,d=0,h=0,N=0,O=1;switch(i!==n.CONTAIN&&i!==n.COVER||(h=r/e,N=s/t),i){case n.CONTAIN:O=h<N?h:N;break;case n.COVER:O=h>N?h:N;break;case n.ALIGN_ONLY:f=e,d=t}if(i===n.CONTAIN||i===n.COVER){if(a||c){let r=O,s=O;a&&(r=a/e),c&&(s=c/t);const n=r<s?r:s;O=Math.min(O,n)}f=e*O,d=t*O}return{width:Math.round(f),height:Math.round(d),x:Math.round((r-f)*u),y:Math.round((s-d)*o)}})(e,s,d,h,i,u,o,a,c);O(t),y(r),p(f),v(N)},[d,h,e,s,d,h,i,u,o,a,c]),{ref:f,width:N,height:l,x:C,y:b}},Object.defineProperty(e,"__esModule",{value:!0})});
//# sourceMappingURL=index.min.js.map