326 lines
16 KiB
TypeScript
326 lines
16 KiB
TypeScript
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<HTMLAttributes<HTMLDivElement>, "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<HTMLDivElement>(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<WindowRect | null>(null);
|
|
const rectRef = useRef<WindowRect | null>(null);
|
|
const initialRectRef = useRef<WindowRect | null>(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<HTMLElement>(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<HTMLElement>('[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<HTMLElement>(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<HTMLDivElement>) => {
|
|
if (allowBackdropClose && event.target === event.currentTarget) onClose();
|
|
};
|
|
|
|
return createPortal(
|
|
<LoadingContext.Provider value={null}><InspectorSelectPolicyContext.Provider value={false}>
|
|
<WindowSuspensionContext.Provider value={suspend}><div className="nodedc-overlay nodedc-ui-root" style={suspended ? {display:"none"} : undefined} data-placement={placement} data-floating={isFloating || undefined} onPointerDown={handleBackdropPointerDown}>
|
|
<div
|
|
ref={dialogRef}
|
|
className={cn("nodedc-window nodedc-glass-material nodedc-material-rim", className)}
|
|
data-material="glass-v4"
|
|
data-size={size === "md" ? undefined : size}
|
|
data-placement={placement}
|
|
data-draggable={canDrag ? "true" : undefined}
|
|
data-resizable={freeGeometry || undefined}
|
|
data-floating={isFloating || undefined}
|
|
role="dialog"
|
|
aria-modal={placement === "center" && !isFloating ? "true" : undefined}
|
|
aria-labelledby={titleId}
|
|
aria-describedby={subtitle ? descriptionId : undefined}
|
|
tabIndex={-1}
|
|
style={freeGeometry && floatingRect ? { ...style, position: "fixed", ...floatingRect, right: "auto", bottom: "auto", maxWidth: "none", maxHeight: "none" } : dragPosition ? { ...style, position: "fixed", left: dragPosition.left, top: dragPosition.top, right: "auto", bottom: "auto" } : style}
|
|
{...props}
|
|
>
|
|
<header
|
|
className="nodedc-window__head"
|
|
tabIndex={freeGeometry ? 0 : undefined}
|
|
aria-label={freeGeometry ? "Перемещение окна: стрелки; изменение размера: Shift и стрелки" : undefined}
|
|
onKeyDown={(event) => {
|
|
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();
|
|
}}
|
|
>
|
|
<div className="nodedc-window__titles">
|
|
<h2 id={titleId} className="nodedc-window__title">{title}</h2>
|
|
{subtitle ? <p id={descriptionId} className="nodedc-window__subtitle">{subtitle}</p> : null}
|
|
</div>
|
|
<div className="nodedc-window__actions">
|
|
{headerActionsPlacement === "before-move" && headerActions}
|
|
{allowFloating && placement === "center" && <IconButton label={isFloating ? "Вернуть модальный режим" : "Свободное окно"} aria-pressed={isFloating} onClick={() => {
|
|
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);
|
|
}}><Icon name="move" /></IconButton>}
|
|
{headerActionsPlacement === "before-close" && headerActions}
|
|
<button type="button" className="nodedc-window__close" aria-label={closeLabel} onClick={onClose}>
|
|
<Icon name="close" size={16} strokeWidth={1.6} />
|
|
</button>
|
|
</div>
|
|
</header>
|
|
{freeGeometry && windowResizeEdges.map(edge => <div key={edge} className="nodedc-window__resize" data-edge={edge} aria-hidden="true" onPointerDown={event => {
|
|
if (event.button !== 0 || !floatingRect) return;
|
|
resizeRef.current = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, rect: floatingRect, edge };
|
|
gestureChanged.current = false;
|
|
event.currentTarget.setPointerCapture(event.pointerId);
|
|
event.preventDefault(); event.stopPropagation();
|
|
}} />)}
|
|
<div className="nodedc-window__body">{children}</div>
|
|
{footer ? <footer className="nodedc-window__footer">{footer}</footer> : null}
|
|
</div>
|
|
</div>
|
|
</WindowSuspensionContext.Provider></InspectorSelectPolicyContext.Provider></LoadingContext.Provider>,
|
|
document.fullscreenElement ?? document.body,
|
|
);
|
|
}
|
|
|
|
export function WindowFooterActions({ children, className, ...props }: HTMLAttributes<HTMLDivElement>) {
|
|
return <div className={cn("nodedc-window__footer-actions", className)} {...props}>{children}</div>;
|
|
}
|