import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type HTMLAttributes, type PointerEvent, type ReactNode, } from "react"; import { createPortal } from "react-dom"; import { InspectorSelectPolicyContext } from "./InspectorContext.js"; import { LoadingContext } from "./LoadingContext.js"; import { WindowSuspensionContext } from "./WindowSuspensionContext.js"; import { cn } from "./cn.js"; import { Icon } from "./Icon.js"; import { IconButton } from "./Button.js"; import { fitWindow, resizeWindow, windowResizeEdges, type WindowRect, type ResizeEdge } from "./windowGeometry.js"; const focusableSelector = [ "a[href]", "button:not([disabled])", "input:not([disabled])", "select:not([disabled])", "textarea:not([disabled])", "[tabindex]:not([tabindex='-1'])", ].join(","); export type WindowSize = "sm" | "md" | "lg"; export type WindowPlacement = "center" | "end"; export type { WindowRect } from "./windowGeometry.js"; export interface WindowProps extends Omit, "title"> { open: boolean; title: ReactNode; subtitle?: ReactNode; children: ReactNode; footer?: ReactNode; /** Context actions beside close, using canonical IconButton controls. */ headerActions?: ReactNode; /** Keep contextual actions immediately before close when requested. */ headerActionsPlacement?: "before-move" | "before-close"; size?: WindowSize; placement?: WindowPlacement; closeLabel?: string; closeOnBackdrop?: boolean; closeOnEscape?: boolean; lockBodyScroll?: boolean; trapFocus?: boolean; draggable?: boolean; /** Resize a modeless inspector using the same eight edges as floating windows. */ resizable?: boolean; initialRect?: WindowRect; /** Application-owned geometry, restored on open and on external undo/import. */ rect?: WindowRect; /** One commit after a drag/resize, or a keyboard geometry step. */ onRectCommit?: (rect: WindowRect) => void; /** Centered windows can become modeless without remounting their contents. */ allowFloating?: boolean; onClose: () => void; } export function Window({ open, title, subtitle, children, footer, headerActions, headerActionsPlacement = "before-move", size = "md", placement = "center", closeLabel = "Закрыть", closeOnBackdrop, closeOnEscape = true, lockBodyScroll, trapFocus, draggable = false, resizable = false, initialRect, rect, onRectCommit, allowFloating = true, onClose, className, style, ...props }: WindowProps) { const [suspensions, setSuspensions] = useState(0); const suspend = useCallback(() => {setSuspensions(value => value + 1); return () => setSuspensions(value => Math.max(0, value - 1));}, []); const suspended = suspensions > 0; const titleId = useId(); const descriptionId = useId(); const dialogRef = useRef(null); const onCloseRef = useRef(onClose); const dragRef = useRef<{ pointerId: number; offsetX: number; offsetY: number } | null>(null); const [dragPosition, setDragPosition] = useState<{ left: number; top: number } | null>(null); const [floating, setFloating] = useState(false); const [floatingRect, setFloatingRect] = useState(null); const rectRef = useRef(null); const initialRectRef = useRef(null); const commitRef = useRef(onRectCommit); commitRef.current = onRectCommit; const changeRect = (next: WindowRect | null) => { rectRef.current = next; setFloatingRect(next); }; const gestureChanged = useRef(false); const resizeRef = useRef<{ pointerId: number; x: number; y: number; rect: WindowRect; edge: ResizeEdge } | null>(null); const isFloating = floating && allowFloating && placement === "center"; const freeGeometry = isFloating || (resizable && placement === "end"); const canDrag = draggable || freeGeometry; const shouldLockBodyScroll = !suspended && !isFloating && (lockBodyScroll ?? placement === "center"); const shouldTrapFocus = !suspended && !isFloating && (trapFocus ?? placement === "center"); const modeRef = useRef({ shouldTrapFocus, isFloating, suspended }); modeRef.current = { shouldTrapFocus, isFloating, suspended }; onCloseRef.current = onClose; useEffect(() => { if (!open || typeof document === "undefined") return; const previousActiveElement = document.activeElement instanceof HTMLElement ? document.activeElement : null; const frame = window.requestAnimationFrame(() => { const firstFocusable = Array.from(dialogRef.current?.querySelectorAll(focusableSelector) ?? []).find(element => element.getClientRects().length > 0); (firstFocusable ?? dialogRef.current)?.focus(); }); const handleKeyDown = (event: KeyboardEvent) => { if (event.defaultPrevented || modeRef.current.suspended) return; // Portalled child dialogs own their Escape/Tab keys. A parent listener // can run first, so event.defaultPrevented alone cannot guard nesting. const focusedDialog = document.activeElement?.closest('[role="dialog"]'); if (focusedDialog && focusedDialog !== dialogRef.current) return; if (!focusedDialog) { const topModal = Array.from(document.querySelectorAll('[role="dialog"][aria-modal="true"]')).filter(dialog => dialog.getClientRects().length > 0).at(-1); if (topModal && topModal !== dialogRef.current) return; } if (event.key === "Escape" && closeOnEscape && (!modeRef.current.isFloating || dialogRef.current?.contains(document.activeElement))) { event.preventDefault(); onCloseRef.current(); return; } if (event.key !== "Tab" || !modeRef.current.shouldTrapFocus || !dialogRef.current) return; const focusable = Array.from(dialogRef.current.querySelectorAll(focusableSelector)).filter(element => element.getClientRects().length > 0); if (focusable.length === 0) { event.preventDefault(); dialogRef.current.focus(); return; } const first = focusable[0]; const last = focusable[focusable.length - 1]; if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); } else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); } }; document.addEventListener("keydown", handleKeyDown); return () => { window.cancelAnimationFrame(frame); document.removeEventListener("keydown", handleKeyDown); if (!modeRef.current.isFloating || document.activeElement === document.body || dialogRef.current?.contains(document.activeElement)) previousActiveElement?.focus(); }; }, [closeOnEscape, open]); useEffect(() => { if (!open || !shouldLockBodyScroll) return; const previousOverflow = document.body.style.overflow; document.body.style.overflow = "hidden"; return () => { document.body.style.overflow = previousOverflow; }; }, [open, shouldLockBodyScroll]); useLayoutEffect(() => { if (open && freeGeometry && !dragRef.current && !resizeRef.current) { // The modal move toggle already restores its local rectangle. An // uncontrolled floating window must retain it when toggled twice. if (placement === "center" && !onRectCommit && !rect && rectRef.current) return; const bounds=dialogRef.current?.getBoundingClientRect(); if(bounds){ initialRectRef.current ??= initialRect??{left:bounds.left,top:bounds.top,width:bounds.width,height:bounds.height}; changeRect(fitWindow(rect??initialRectRef.current,{width:window.innerWidth,height:window.innerHeight})); } } },[open,freeGeometry,rect?.left,rect?.top,rect?.width,rect?.height]); useEffect(() => { if (!open) { setDragPosition(null); setFloating(false); changeRect(null); initialRectRef.current = null; dragRef.current = null; resizeRef.current = null; } }, [open]); useEffect(() => { if (!canDrag || !open) return; const handlePointerMove = (event: globalThis.PointerEvent) => { const resizing = resizeRef.current; if (resizing && event.pointerId === resizing.pointerId) { gestureChanged.current = true; changeRect(resizeWindow(resizing.rect, resizing.edge, event.clientX - resizing.x, event.clientY - resizing.y, { width: window.innerWidth, height: window.innerHeight })); return; } const drag = dragRef.current; const dialog = dialogRef.current; if (!drag || !dialog || event.pointerId !== drag.pointerId) return; const bounds = dialog.getBoundingClientRect(); if (freeGeometry) { gestureChanged.current = true; changeRect(fitWindow({ left: event.clientX - drag.offsetX, top: event.clientY - drag.offsetY, width: bounds.width, height: bounds.height }, { width: window.innerWidth, height: window.innerHeight })); return; } const left = Math.max(8, Math.min(window.innerWidth - bounds.width - 8, event.clientX - drag.offsetX)); const top = Math.max(76, Math.min(window.innerHeight - bounds.height - 8, event.clientY - drag.offsetY)); setDragPosition({ left, top }); }; const handlePointerUp = (event: globalThis.PointerEvent) => { const owned = dragRef.current?.pointerId === event.pointerId || resizeRef.current?.pointerId === event.pointerId; if (dragRef.current?.pointerId === event.pointerId) dragRef.current = null; if (resizeRef.current?.pointerId === event.pointerId) resizeRef.current = null; if (owned && gestureChanged.current && rectRef.current) { gestureChanged.current = false; commitRef.current?.({...rectRef.current}); } }; window.addEventListener("pointermove", handlePointerMove); window.addEventListener("pointerup", handlePointerUp); window.addEventListener("pointercancel", handlePointerUp); return () => { window.removeEventListener("pointermove", handlePointerMove); window.removeEventListener("pointerup", handlePointerUp); window.removeEventListener("pointercancel", handlePointerUp); }; }, [canDrag, freeGeometry, open]); useEffect(() => { if (!freeGeometry || !open) return; const fit = () => { if(rectRef.current) changeRect(fitWindow(rect ?? rectRef.current, { width: window.innerWidth, height: window.innerHeight })); }; window.addEventListener("resize", fit); return () => window.removeEventListener("resize", fit); }, [freeGeometry, open, rect]); if (!open || typeof document === "undefined") return null; const allowBackdropClose = !isFloating && (closeOnBackdrop ?? placement === "center"); const handleBackdropPointerDown = (event: PointerEvent) => { if (allowBackdropClose && event.target === event.currentTarget) onClose(); }; return createPortal(
{ if (!freeGeometry || !floatingRect || event.target !== event.currentTarget || !event.key.startsWith("Arrow")) return; event.preventDefault(); const dx = event.key === "ArrowLeft" ? -10 : event.key === "ArrowRight" ? 10 : 0; const dy = event.key === "ArrowUp" ? -10 : event.key === "ArrowDown" ? 10 : 0; const bounds = { width: window.innerWidth, height: window.innerHeight }; const next = event.shiftKey ? resizeWindow(floatingRect, "se", dx, dy, bounds) : fitWindow({ ...floatingRect, left: floatingRect.left + dx, top: floatingRect.top + dy }, bounds); changeRect(next); commitRef.current?.(next); }} onPointerDown={(event) => { if (!canDrag || event.button !== 0 || (event.target as HTMLElement).closest("button, input, select, textarea, a")) return; const bounds = dialogRef.current?.getBoundingClientRect(); if (!bounds) return; dragRef.current = { pointerId: event.pointerId, offsetX: event.clientX - bounds.left, offsetY: event.clientY - bounds.top }; gestureChanged.current = false; event.currentTarget.setPointerCapture(event.pointerId); event.preventDefault(); }} >

{title}

{subtitle ?

{subtitle}

: null}
{headerActionsPlacement === "before-move" && headerActions} {allowFloating && placement === "center" && { dragRef.current = null; resizeRef.current = null; if (!isFloating) { const rect = dialogRef.current?.getBoundingClientRect(); if (rect) changeRect(fitWindow(rectRef.current ?? { left: rect.left, top: rect.top, width: rect.width, height: rect.height }, { width: window.innerWidth, height: window.innerHeight })); } setFloating(!isFloating); }}>} {headerActionsPlacement === "before-close" && headerActions}
{freeGeometry && windowResizeEdges.map(edge =>
, document.fullscreenElement ?? document.body, ); } export function WindowFooterActions({ children, className, ...props }: HTMLAttributes) { return
{children}
; }