import { Rnd } from "react-rnd"; import { FC, memo, useCallback, useEffect, useMemo, useRef } from "react"; import useRnd from "./useRnd"; import { useWindows } from "../../../contexts/windows"; import { FOCUSABLE_ELEMENT, PREVENT_SCROLL } from "../../../utils/constants"; import { haltEvent } from "../../../utils/functions"; import { useConfig } from "@/contexts/config"; import { useSession } from "@/contexts/session"; import styled from "styled-components"; type RndWindowProps = { id: string; zIndex: number; children: React.ReactNode; }; const reRouteFocus = (focusElement?: HTMLElement) => (element?: Element): void => { element?.setAttribute("tabindex", FOCUSABLE_ELEMENT.tabIndex.toString()); element?.addEventListener("contextmenu", haltEvent); element?.addEventListener("mousedown", (event) => { event.preventDefault(); focusElement?.focus(PREVENT_SCROLL); }); }; const RndWindow: FC = ({ children, id, zIndex, ...extraProps }) => { const { linkElement, windows: { [id]: currentWindow }, } = useWindows(); const { previewID } = useSession(); const { disableAnimations } = useConfig(); const { Component, componentWindow, maximized, minimized } = currentWindow || {}; const rndRef = useRef(null); const rndProps = useRnd(id); const isPreview = previewID !== false; const isPreviewAndNotOnUs = isPreview && previewID !== id; const style = useMemo( () => ({ pointerEvents: minimized ? "none" : undefined, zIndex, // position: disableAnimations ? "absolute" : undefined, transform: "none", willChange: "transform", // willChange: !disableAnimations ? "transform" : "top,left", display: disableAnimations && minimized && (isPreview ? isPreviewAndNotOnUs : true) ? "none" : undefined, width: maximized ? "100%" : undefined, height: maximized ? "100%" : undefined, }), [minimized, zIndex, disableAnimations, isPreview, isPreviewAndNotOnUs, maximized] ); const linkComponentWindow = useCallback( (rndEntry: Rnd) => { rndRef.current = rndEntry; const rndWindowElements = rndEntry?.resizableElement?.current?.children || []; const [windowContainer] = rndWindowElements as HTMLElement[]; if (Component && !componentWindow && windowContainer) { linkElement(id, "componentWindow", windowContainer); } }, [Component, componentWindow, id, linkElement] ); useEffect(() => { if (!maximized) { const { current: currentRndWindow } = rndRef; const rndWindowElements = currentRndWindow?.resizableElement?.current?.children || []; const [windowContainer, resizeHandleContainer] = rndWindowElements as HTMLElement[]; const resizeHandles = [...(resizeHandleContainer?.children || [])]; resizeHandles.forEach(reRouteFocus(windowContainer)); } }, [maximized]); return ( {children} ); }; export default memo(RndWindow);