From 4228a27ca880c3e94b455f0c469dc3bcda0b16ab Mon Sep 17 00:00:00 2001 From: nerocui Date: Thu, 15 Dec 2022 20:20:15 -0800 Subject: [PATCH] added host to hooks for instanceof check --- src/index.ts | 8 ++++++-- src/utils/useResolvedElement.ts | 5 +++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/index.ts b/src/index.ts index 21d1350..0354efe 100644 --- a/src/index.ts +++ b/src/index.ts @@ -38,16 +38,19 @@ export type RoundingFunction = (n: number) => number; function useResizeObserver( opts: { + host: Window & typeof globalThis, ref?: RefObject | T | null | undefined; onResize?: ResizeHandler; box?: ResizeObserverBoxOptions; round?: RoundingFunction; - } = {} + } = { + host: window + } ): HookResponse { // Saving the callback as a ref. With this, I don't need to put onResize in the // effect dep array, and just passing in an anonymous function without memoising // will not reinstantiate the hook's ResizeObserver. - const onResize = opts.onResize; + const { onResize, host } = opts; const onResizeRef = useRef(undefined); onResizeRef.current = onResize; const round = opts.round || Math.round; @@ -152,6 +155,7 @@ function useResizeObserver( }, [opts.box, round] ), + host, opts.ref ); diff --git a/src/utils/useResolvedElement.ts b/src/utils/useResolvedElement.ts index d2acd46..68f1b9a 100644 --- a/src/utils/useResolvedElement.ts +++ b/src/utils/useResolvedElement.ts @@ -7,7 +7,8 @@ type SubscriberResponse = SubscriberCleanupFunction | void; // refs to such extent, but then composing hooks and components could not opt out of unnecessary renders. export default function useResolvedElement( subscriber: (element: T) => SubscriberResponse, - refOrElement?: T | RefObject | null + host: Window & typeof globalThis = window, + refOrElement?: T | RefObject | null, ): RefCallback { const lastReportRef = useRef<{ element: T | null; @@ -31,7 +32,7 @@ export default function useResolvedElement( const element: T | null = cbElement ? cbElement : refOrElement - ? refOrElement instanceof Element + ? refOrElement instanceof host.Element ? refOrElement : refOrElement.current : null;