@ffsm/snapshot
Version:
React snapshot utilities for capturing and measuring DOM elements
2 lines (1 loc) • 1.06 kB
JavaScript
import{useRef as e,useCallback as r,useEffect as t}from"react";import{requestTimeout as n}from"@ffsm/requester";var i;function o(o,u={}){const{delay:c=0,lowerWidthBound:l=320,lowerHeightBound:d=0,retryInit:h=1,loading:s=!1,error:a=null,onRetry:f,validate:N,observer:I=!0}=u,m=e(null),E=e(0),_=r(e=>{const r=Math.max(d,0);return!(e.width<l)&&(!(r>0&&e.height<r)&&("function"!=typeof N||N(e)))},[l,d,N]),p=r(()=>{const e=m.current?.parentElement;if(!e)return void o(null,i.PARENT_NOT_FOUND);const r=e.clientWidth,t=e.clientHeight;_({width:r,height:t})?o({width:r,height:t},null):E.current<h?(E.current++,f?.(),n(p,c)):o(null,i.INVALID_SIZE)},[c,h,o,f,_]);return t(()=>(E.current=0,n(p,c).cancel),[p]),t(()=>{if(!I||s||a||!m.current?.parentElement||"undefined"==typeof ResizeObserver)return;const e=m.current?.parentElement,r=new ResizeObserver(()=>{E.current=0,p()});return r.observe(e),r.disconnect.bind(r)},[s,a,I,p]),m}!function(e){e.PARENT_NOT_FOUND="PARENT_NOT_FOUND",e.INVALID_SIZE="INVALID_SIZE"}(i||(i={}));export{i as SnapshotError,o as useSnapshot};