Files
daedalOS/hooks/useIFrameFocuser.ts

46 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-08-28 23:01:05 -07:00
import { useSession } from "contexts/session";
2023-02-07 22:40:12 -08:00
import { useProcessesRef } from "hooks/useProcessesRef";
import { useEffect } from "react";
2021-08-28 23:01:05 -07:00
import { ONE_TIME_PASSIVE_EVENT } from "utils/constants";
const useIFrameFocuser = (): void => {
const { setForegroundId } = useSession();
2023-02-07 22:40:12 -08:00
const processesRef = useProcessesRef();
2021-08-28 23:01:05 -07:00
useEffect(() => {
2022-11-20 14:12:01 -08:00
const focusIframeWindow = (): void => {
if (document.activeElement instanceof HTMLIFrameElement) {
const [id] =
2023-07-12 00:01:43 -07:00
Object.entries(processesRef.current).find(
([, { componentWindow }]) =>
componentWindow?.contains(document.activeElement)
2022-11-20 14:12:01 -08:00
) || [];
if (id) {
setForegroundId(id);
window.addEventListener(
"click",
({ target }) => {
const [focusId = ""] =
Object.entries(processesRef.current).find(
([, { componentWindow }]) =>
target instanceof HTMLElement &&
componentWindow?.contains(target)
) || [];
setForegroundId(focusId);
},
ONE_TIME_PASSIVE_EVENT
);
}
}
};
2021-08-28 23:01:05 -07:00
window.addEventListener("blur", focusIframeWindow, { passive: true });
return () => window.removeEventListener("blur", focusIframeWindow);
2023-02-07 22:40:12 -08:00
}, [processesRef, setForegroundId]);
2021-08-28 23:01:05 -07:00
};
export default useIFrameFocuser;