From 063dedbbc1573a825571c675bf6bfa8a1bc1c6cd Mon Sep 17 00:00:00 2001 From: AAGaming Date: Fri, 4 Oct 2024 23:51:36 -0400 Subject: [PATCH] feat(utils/react): add some window-related utils --- src/utils/react/react.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/utils/react/react.ts b/src/utils/react/react.ts index 8a4a04e..d3e0ad8 100644 --- a/src/utils/react/react.ts +++ b/src/utils/react/react.ts @@ -1,4 +1,5 @@ import * as React from 'react'; +import { Ref, useState } from 'react'; // this shouldn't need to be redeclared but it does for some reason @@ -150,3 +151,21 @@ export const findInReactTree = (node: any, filter: findInTreeFilter) => // Specialised findInTree for React nodes walkable: ['props', 'children', 'child', 'sibling'], }); + +/** + * Finds the parent window of a DOM element + */ +export function getParentWindow(elem: HTMLElement | null): WindowType | null | undefined { + return elem?.ownerDocument?.defaultView as any; +} + +/** + * React hook to find the host window of a component + * Pass the returned ref into a React element and window will be its host window. + * @returns [ref, window] + */ +export function useWindowRef(): [Ref, WindowType | null | undefined] { + const [win, setWin] = useState(null); + + return [(elem) => setWin(getParentWindow(elem)), win]; +} \ No newline at end of file