feat(ui): add docking, viewport controls and composed settings
Add shared dock layouts, navigation cube, range bands, progress actions and comparison surfaces. Extend toolbar menus and loading composition, and align tokens, registry entries, documentation and the living catalog.
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
import type { ReactNode, CSSProperties } from "react";
|
||||
export interface ComparisonTableProps {
|
||||
density?: "default" | "compact";
|
||||
label: string;
|
||||
heading: ReactNode;
|
||||
columns: readonly { id: string; label: ReactNode }[];
|
||||
rows: readonly { id: string; label: ReactNode; cells: readonly ReactNode[] }[];
|
||||
}
|
||||
/** One label column, one non-collapsing column per entity. Scrolls as a unit. */
|
||||
export function ComparisonTable({ density = "default", label, heading, columns, rows }: ComparisonTableProps) {
|
||||
return <div className="nodedc-comparison-table" data-density={density} role="region" aria-label={label} tabIndex={0}
|
||||
style={{ "--nodedc-comparison-columns": columns.length + 1 } as CSSProperties}>
|
||||
<table aria-label={label}>
|
||||
<colgroup><col/>{columns.map(column => <col key={column.id}/>)}</colgroup>
|
||||
<thead><tr><th scope="col">{heading}</th>{columns.map(column => <th key={column.id} scope="col">{column.label}</th>)}</tr></thead>
|
||||
<tbody>{rows.map(row => <tr key={row.id}><th scope="row">{row.label}</th>{columns.map((column, index) => <td key={column.id}>{row.cells[index] ?? "—"}</td>)}</tr>)}</tbody>
|
||||
</table>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { HTMLAttributes } from "react";
|
||||
import { cn } from "./cn.js";
|
||||
/** Secondary explanatory copy; identical inside and outside SettingsCard headers. */
|
||||
export function Description({ className, ...props }: HTMLAttributes<HTMLParagraphElement>) {
|
||||
return <p {...props} className={cn("nodedc-description", className)} />;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import {createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode} from "react";
|
||||
import {DndContext, PointerSensor, useDraggable, useSensor, useSensors, type DragMoveEvent} from "@dnd-kit/core";
|
||||
import {DragHandle} from "./DragDrop.js";
|
||||
import {SplitPane} from "./SplitPane.js";
|
||||
import {cn} from "./cn.js";
|
||||
import {dockIds, dockPosition, dockRects, moveDockPanel, pruneDockTree, resizeDockSplit, dockMinimum, constrainDockTree, preferDockSizes, type DockMinimum, type DockMove, type DockRect, type DockTree} from "@nodedc/ui-core";
|
||||
|
||||
const DockContext = createContext<{disabled: boolean; onKey: (id: string, event: KeyboardEvent<HTMLDivElement>) => void}>({disabled: true, onKey: () => {}});
|
||||
/** The shared six-dot grip supports pointer dragging and keyboard docking. */
|
||||
export function DockHandle({id, label}: {id: string; label: string}) {
|
||||
const {disabled, onKey} = useContext(DockContext);
|
||||
const {attributes, listeners, setNodeRef} = useDraggable({id, disabled});
|
||||
return <div ref={setNodeRef} className="nodedc-dock-layout__handle" onKeyDown={event => onKey(id, event)}>
|
||||
<DragHandle label={`Переместить · ${label}`} attributes={{...attributes, "aria-disabled": disabled}} listeners={listeners}/>
|
||||
</div>;
|
||||
}
|
||||
|
||||
export interface DockLayoutProps {
|
||||
tree: DockTree | null;
|
||||
onTreeChange: (tree: DockTree) => void;
|
||||
panels: {id: string; label: string; minimumSize?: DockMinimum; preferredSize?: DockMinimum}[];
|
||||
renderPanel: (id: string) => ReactNode;
|
||||
focusedId?: string | null;
|
||||
className?: string;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
/** Media stay in stable sibling hosts; only geometry changes, including focus. */
|
||||
export function DockLayout({tree, onTreeChange, panels, renderPanel, focusedId, className, children}: DockLayoutProps) {
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
// React must not reorder these DOM siblings: moving an iframe node reloads
|
||||
// its browsing context even when its key and portal content are unchanged.
|
||||
const hostOrder = useRef<string[]>([]);
|
||||
const available = new Set(panels.map(panel => panel.id));
|
||||
hostOrder.current = hostOrder.current.filter(id => available.has(id));
|
||||
for (const panel of panels) if (!hostOrder.current.includes(panel.id)) hostOrder.current.push(panel.id);
|
||||
const [bounds, setBounds] = useState<DockRect>({left: 0, top: 0, width: 0, height: 0});
|
||||
const [active, setActive] = useState<string | null>(null), [target, setTarget] = useState<DockMove | null>(null);
|
||||
const [keyboard, setKeyboard] = useState(false);
|
||||
const sensors = useSensors(useSensor(PointerSensor, {activationConstraint: {distance: 6}}));
|
||||
const ids = panels.map(panel => panel.id), visibleTree = pruneDockTree(tree, focusedId ? [focusedId] : ids);
|
||||
const minimums = Object.fromEntries(panels.filter(p => p.minimumSize).map(p => [p.id, p.minimumSize!]));
|
||||
const minimum = dockMinimum(visibleTree, minimums);
|
||||
const canvas = {...bounds, width: Math.max(bounds.width, minimum.width), height: Math.max(bounds.height, minimum.height)};
|
||||
const preferred = Object.fromEntries(panels.filter(p => p.preferredSize).map(p => [p.id,p.preferredSize!]));
|
||||
const constrained = constrainDockTree(preferDockSizes(visibleTree,canvas,preferred), canvas, minimums);
|
||||
const rects = dockRects(constrained, canvas);
|
||||
const disabled = !!focusedId || ids.length < 2;
|
||||
const reset = () => {setActive(null); setTarget(null); setKeyboard(false);};
|
||||
useLayoutEffect(() => {
|
||||
const element = host.current!;
|
||||
const measure = () => {const r = element.getBoundingClientRect(); setBounds({left: 0, top: 0, width: r.width, height: r.height});};
|
||||
measure(); const observer = new ResizeObserver(measure); observer.observe(element); return () => observer.disconnect();
|
||||
}, []);
|
||||
useEffect(() => {if (disabled || (active && !ids.includes(active))) reset();}, [disabled, panels.map(p => p.id).join("\0")]);
|
||||
// Block iframe hit-testing only during a drag so pointer motion stays in the document.
|
||||
const locate = (event: DragMoveEvent): DockMove | null => {
|
||||
const start = event.activatorEvent as PointerEvent, box = host.current!.getBoundingClientRect();
|
||||
const x = start.clientX + event.delta.x - box.left, y = start.clientY + event.delta.y - box.top;
|
||||
for (const [id, rect] of Object.entries(rects)) {
|
||||
const position = dockPosition(rect, x, y);
|
||||
if (position && id !== String(event.active.id)) return {activeId: String(event.active.id), overId: id, position};
|
||||
}
|
||||
return null;
|
||||
};
|
||||
const commit = (move: DockMove | null) => {
|
||||
const next = move && moveDockPanel(constrained, move);
|
||||
if (next) onTreeChange(next);
|
||||
reset();
|
||||
};
|
||||
const onKey = (id: string, event: KeyboardEvent<HTMLDivElement>) => {
|
||||
if (disabled) return;
|
||||
if (!keyboard) {
|
||||
if (event.key !== " " && event.key !== "Enter") return;
|
||||
const overId = ids.find(value => value !== id)!;
|
||||
setActive(id); setTarget({activeId: id, overId, position: "center"}); setKeyboard(true);
|
||||
} else if (event.key === "Escape") reset();
|
||||
else if (event.key === "Enter" || event.key === " ") commit(target);
|
||||
else if (event.key === "Tab") {
|
||||
const candidates = dockIds(visibleTree).filter(value => value !== active), index = candidates.indexOf(target?.overId ?? "");
|
||||
setTarget({activeId: active!, overId: candidates[(index + (event.shiftKey ? -1 : 1) + candidates.length) % candidates.length], position: target?.position ?? "center"});
|
||||
} else {
|
||||
const position = ({ArrowLeft: "left", ArrowRight: "right", ArrowUp: "top", ArrowDown: "bottom", Home: "center"} as const)[event.key as "ArrowLeft"];
|
||||
if (!position || !target) return;
|
||||
setTarget({...target, position});
|
||||
}
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
};
|
||||
const preview = target ? dockRects(moveDockPanel(constrained, target), canvas)[target.activeId] : null;
|
||||
const action = target ? ({center: "Поменять местами", left: "Слева", right: "Справа", top: "Сверху", bottom: "Снизу"})[target.position] : "Выберите окно и край";
|
||||
const label = target ? panels.find(panel => panel.id === target.overId)?.label : "";
|
||||
return <DndContext sensors={sensors} autoScroll={false}
|
||||
onDragStart={event => {setActive(String(event.active.id)); setKeyboard(false);}}
|
||||
onDragMove={event => setTarget(locate(event))}
|
||||
onDragEnd={event => commit(locate(event))} onDragCancel={reset}>
|
||||
<DockContext.Provider value={{disabled, onKey}}>
|
||||
<div className={cn("nodedc-dock-layout", className)} data-docking={active ? "true" : undefined}>
|
||||
<div ref={host} className="nodedc-dock-layout__canvas" style={{minWidth:minimum.width, minHeight:minimum.height}}>
|
||||
<DockSlots tree={constrained} bounds={canvas} minimums={minimums} onResize={(path, ratio) => {if (constrained) onTreeChange(constrainDockTree(resizeDockSplit(constrained, path, ratio), canvas, minimums)!);}}/>
|
||||
{hostOrder.current.map(id => panels.find(panel => panel.id === id)!).map(panel => <div key={panel.id} className="nodedc-dock-layout__panel" data-dock-id={panel.id}
|
||||
data-dock-source={active === panel.id ? "true" : undefined} style={rects[panel.id] ?? {display: "none"}}>{renderPanel(panel.id)}</div>)}
|
||||
{active ? <div className="nodedc-dock-layout__overlay" aria-hidden="true">
|
||||
{preview ? <div className="nodedc-dock-layout__preview" data-dock-position={target!.position} style={preview}><span>{action} · {label}</span></div> : null}
|
||||
</div> : null}
|
||||
<div className="nodedc-dock-layout__announcement" role="status" aria-live="polite">{active ? `${action}${label ? ` · ${label}` : ""}. Tab — окно, стрелки — край, Home — обмен, Enter — применить, Escape — отменить.` : ""}</div>
|
||||
</div>
|
||||
</div>
|
||||
{children}
|
||||
</DockContext.Provider>
|
||||
</DndContext>;
|
||||
}
|
||||
|
||||
function DockSlots({tree, bounds, minimums, onResize, path = ""}: {tree: DockTree | null; bounds: DockMinimum; minimums: Record<string,DockMinimum>; onResize: (path: string, ratio: number) => void; path?: string}) {
|
||||
if (!tree || "id" in tree) return null;
|
||||
const key = tree.axis === "x" ? "width" : "height", span = bounds[key];
|
||||
return <SplitPane className="nodedc-dock-layout__split" separatorAppearance="invisible" orientation={tree.axis === "x" ? "vertical" : "horizontal"}
|
||||
primarySize={tree.ratio} minPrimarySize={span ? dockMinimum(tree.first,minimums)[key]/span*100 : 0} minSecondarySize={span ? dockMinimum(tree.second,minimums)[key]/span*100 : 0} onPrimarySizeChange={ratio => onResize(path, ratio)} separatorLabel="Изменить размеры окон"
|
||||
primary={<DockSlots tree={tree.first} bounds={{...bounds,[key]:span*tree.ratio/100}} minimums={minimums} onResize={onResize} path={path + "0"}/>}
|
||||
secondary={<DockSlots tree={tree.second} bounds={{...bounds,[key]:span*(1-tree.ratio/100)}} minimums={minimums} onResize={onResize} path={path + "1"}/>}/>;
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useMemo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useId,
|
||||
@@ -9,9 +12,12 @@ import {
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { computeFloatingPosition, type FloatingPlacement } from "@nodedc/ui-core";
|
||||
import { computeFloatingPosition, type FloatingPlacement, type RectLike } from "@nodedc/ui-core";
|
||||
import { cn } from "./cn.js";
|
||||
|
||||
const DropdownLineage = createContext<readonly string[]>([]);
|
||||
const openDropdowns = new Map<string, readonly string[]>();
|
||||
|
||||
export interface DropdownTriggerApi {
|
||||
open: boolean;
|
||||
show: () => void;
|
||||
@@ -34,6 +40,11 @@ export interface DropdownProps {
|
||||
surfaceClassName?: string;
|
||||
surfaceRole?: "menu" | "listbox" | "dialog";
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
/** Animated controls may reserve their maximum extent as a stable anchor. */
|
||||
getAnchorRect?: () => RectLike | null;
|
||||
flip?: boolean;
|
||||
/** Capture-phase dismissal may consume a scene gesture before its tools run. */
|
||||
onPointerDownOutside?: (event: PointerEvent) => void;
|
||||
}
|
||||
|
||||
export function Dropdown({
|
||||
@@ -48,8 +59,13 @@ export function Dropdown({
|
||||
surfaceClassName,
|
||||
surfaceRole = "menu",
|
||||
onOpenChange,
|
||||
getAnchorRect,
|
||||
flip = true,
|
||||
onPointerDownOutside,
|
||||
}: DropdownProps) {
|
||||
const instanceId = useId();
|
||||
const ancestors = useContext(DropdownLineage);
|
||||
const lineage = useMemo(() => [...ancestors, instanceId], [ancestors, instanceId]);
|
||||
const surfaceId = `${instanceId.replaceAll(":", "")}-surface`;
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [anchorElement, setAnchorElement] = useState<HTMLElement | null>(null);
|
||||
@@ -72,7 +88,7 @@ export function Dropdown({
|
||||
const updatePosition = useCallback(() => {
|
||||
const anchorNode = anchorElement ?? triggerElement;
|
||||
if (!anchorNode || !surfaceRef.current) return;
|
||||
const anchor = anchorNode.getBoundingClientRect();
|
||||
const anchor = getAnchorRect?.() ?? anchorNode.getBoundingClientRect();
|
||||
const anchorVisible = (
|
||||
anchor.bottom > 0
|
||||
&& anchor.top < window.innerHeight
|
||||
@@ -93,58 +109,73 @@ export function Dropdown({
|
||||
surfaceWidth,
|
||||
surfaceHeight,
|
||||
placement,
|
||||
offset,
|
||||
offset, flip,
|
||||
});
|
||||
setSurfaceStyle({
|
||||
const next:CSSProperties = {
|
||||
top: position.top,
|
||||
left: position.left,
|
||||
width: surfaceWidth,
|
||||
width: Math.min(surfaceWidth, position.maxWidth ?? surfaceWidth),
|
||||
maxHeight: position.maxHeight,
|
||||
visibility: "visible",
|
||||
});
|
||||
}, [anchorElement, close, minWidth, offset, placement, triggerElement, width]);
|
||||
};
|
||||
setSurfaceStyle(old => Object.keys(next).every(key => old[key as keyof CSSProperties] === next[key as keyof CSSProperties]) ? old : next);
|
||||
}, [anchorElement, close, minWidth, offset, placement, triggerElement, width, getAnchorRect, flip]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!isOpen) return;
|
||||
updatePosition();
|
||||
}, [isOpen, updatePosition]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || !getAnchorRect) return;
|
||||
let frame:number;
|
||||
const tick=()=>{updatePosition();frame=requestAnimationFrame(tick);};
|
||||
frame=requestAnimationFrame(tick);
|
||||
return()=>cancelAnimationFrame(frame);
|
||||
},[isOpen,getAnchorRect,updatePosition]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
const handlePointerDown = (event: PointerEvent) => {
|
||||
const target = event.target;
|
||||
if (!(target instanceof Node)) return;
|
||||
if (anchorElement?.contains(target) || triggerElement?.contains(target) || surfaceRef.current?.contains(target)) return;
|
||||
const surface = (target instanceof Element ? target : target.parentElement)?.closest('[data-dropdown-lineage]');
|
||||
if (surface?.getAttribute('data-dropdown-lineage')?.split(' ').includes(instanceId)) return;
|
||||
close();
|
||||
onPointerDownOutside?.(event);
|
||||
};
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") {
|
||||
if (event.key === "Escape" && !event.defaultPrevented) {
|
||||
if ([...openDropdowns].some(([id, parents]) => id !== instanceId && parents.includes(instanceId))) return;
|
||||
close();
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
event.stopImmediatePropagation();
|
||||
triggerElement?.focus();
|
||||
}
|
||||
};
|
||||
const handleOtherOpen = (event: Event) => {
|
||||
const detail = (event as CustomEvent<{ id?: string }>).detail;
|
||||
if (detail.id !== instanceId) close();
|
||||
const detail = (event as CustomEvent<{ id?: string; lineage?: readonly string[] }>).detail;
|
||||
if (detail.id !== instanceId && !detail.lineage?.includes(instanceId)) close();
|
||||
};
|
||||
const handleViewportChange = () => updatePosition();
|
||||
|
||||
window.dispatchEvent(new CustomEvent("nodedc-dropdown-open", { detail: { id: instanceId } }));
|
||||
document.addEventListener("pointerdown", handlePointerDown);
|
||||
openDropdowns.set(instanceId, lineage);
|
||||
window.dispatchEvent(new CustomEvent("nodedc-dropdown-open", { detail: { id: instanceId, lineage } }));
|
||||
document.addEventListener("pointerdown", handlePointerDown, true);
|
||||
document.addEventListener("keydown", handleKeyDown, true);
|
||||
window.addEventListener("nodedc-dropdown-open", handleOtherOpen as EventListener);
|
||||
window.addEventListener("resize", handleViewportChange);
|
||||
window.addEventListener("scroll", handleViewportChange, true);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", handlePointerDown);
|
||||
openDropdowns.delete(instanceId);
|
||||
document.removeEventListener("pointerdown", handlePointerDown, true);
|
||||
document.removeEventListener("keydown", handleKeyDown, true);
|
||||
window.removeEventListener("nodedc-dropdown-open", handleOtherOpen as EventListener);
|
||||
window.removeEventListener("resize", handleViewportChange);
|
||||
window.removeEventListener("scroll", handleViewportChange, true);
|
||||
};
|
||||
}, [anchorElement, close, instanceId, isOpen, triggerElement, updatePosition]);
|
||||
}, [anchorElement, close, instanceId, isOpen, triggerElement, updatePosition, lineage, onPointerDownOutside]);
|
||||
|
||||
return (
|
||||
<span className={cn("nodedc-dropdown-anchor", className)}>
|
||||
@@ -154,13 +185,16 @@ export function Dropdown({
|
||||
<div
|
||||
ref={surfaceRef}
|
||||
id={surfaceId}
|
||||
data-dropdown-lineage={lineage.join(' ')}
|
||||
className={cn("nodedc-dropdown-surface", surfaceClassName)}
|
||||
role={surfaceRole}
|
||||
style={surfaceStyle}
|
||||
>
|
||||
{typeof children === "function" ? children({ close }) : children}
|
||||
<DropdownLineage.Provider value={lineage}>
|
||||
{typeof children === "function" ? children({ close }) : children}
|
||||
</DropdownLineage.Provider>
|
||||
</div>,
|
||||
document.body,
|
||||
document.fullscreenElement ?? document.body,
|
||||
)
|
||||
: null}
|
||||
</span>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { useLayoutEffect, useRef, type ReactNode } from "react";
|
||||
import { HeaderAvatar } from "./AppHeader.js";
|
||||
import { Icon, type IconName } from "./Icon.js";
|
||||
import { Window } from "./Window.js";
|
||||
@@ -43,6 +43,8 @@ export function FeatureSettingsWindow<T extends string>({
|
||||
footer,
|
||||
headerActions,
|
||||
}: FeatureSettingsWindowProps<T>) {
|
||||
const contentRef = useRef<HTMLElement>(null);
|
||||
useLayoutEffect(() => { if (contentRef.current) contentRef.current.scrollTop = 0; }, [activeSection]);
|
||||
return (
|
||||
<Window
|
||||
open={open}
|
||||
@@ -56,7 +58,7 @@ export function FeatureSettingsWindow<T extends string>({
|
||||
onClose={onClose}
|
||||
>
|
||||
<div className="nodedc-feature-settings">
|
||||
<aside className="nodedc-feature-settings__navigation" aria-label="Разделы настроек">
|
||||
<aside className="nodedc-feature-settings__navigation" aria-label="Разделы настроек" tabIndex={0}>
|
||||
<div className="nodedc-feature-settings__identity">
|
||||
<HeaderAvatar label={identity.avatarLabel} imageUrl={identity.avatarUrl} />
|
||||
<span><strong>{identity.title}</strong>{identity.subtitle ? <small>{identity.subtitle}</small> : null}</span>
|
||||
@@ -82,7 +84,7 @@ export function FeatureSettingsWindow<T extends string>({
|
||||
})}
|
||||
</nav>
|
||||
</aside>
|
||||
<section className="nodedc-feature-settings__content">{children}</section>
|
||||
<section ref={contentRef} className="nodedc-feature-settings__content" aria-label="Содержимое настроек" tabIndex={0}>{children}</section>
|
||||
</div>
|
||||
</Window>
|
||||
);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { cn } from "./cn.js";
|
||||
|
||||
export interface FieldFrameProps {
|
||||
label: string;
|
||||
labelPlacement?: "above" | "below";
|
||||
hint?: string;
|
||||
description?: string;
|
||||
htmlFor?: string;
|
||||
@@ -10,9 +11,9 @@ export interface FieldFrameProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function FieldFrame({ label, hint, description, htmlFor, children, className }: FieldFrameProps) {
|
||||
export function FieldFrame({ label, hint, description, htmlFor, children, className, labelPlacement = "above" }: FieldFrameProps) {
|
||||
return (
|
||||
<label className={cn("nodedc-field", className)} htmlFor={htmlFor}>
|
||||
<label className={cn("nodedc-field", labelPlacement === "below" && "nodedc-field--caption", className)} htmlFor={htmlFor}>
|
||||
<span className="nodedc-field__label-row">
|
||||
<span className="nodedc-field__label">{label}</span>
|
||||
{hint ? <span className="nodedc-field__hint">{hint}</span> : null}
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
import {
|
||||
MousePointer2,
|
||||
CirclePlus,
|
||||
Box,
|
||||
Scan,
|
||||
PenTool,
|
||||
RectangleHorizontal,
|
||||
Spline,
|
||||
Undo2,
|
||||
Redo2,
|
||||
Activity,
|
||||
AlertTriangle,
|
||||
Boxes,
|
||||
@@ -39,6 +48,7 @@ import {
|
||||
Play,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
RotateCw,
|
||||
Save,
|
||||
Search,
|
||||
Settings,
|
||||
@@ -57,6 +67,15 @@ import {
|
||||
} from "lucide-react";
|
||||
|
||||
const icons = {
|
||||
"add-point": CirclePlus,
|
||||
perspective: Box,
|
||||
orthographic: Scan,
|
||||
select: MousePointer2,
|
||||
pen: PenTool,
|
||||
rectangle: RectangleHorizontal,
|
||||
curve: Spline,
|
||||
undo: Undo2,
|
||||
redo: Redo2,
|
||||
activity: Activity,
|
||||
alert: AlertTriangle,
|
||||
apps: Boxes,
|
||||
@@ -99,6 +118,7 @@ const icons = {
|
||||
plus: Plus,
|
||||
profile: UserCircle,
|
||||
refresh: RefreshCw,
|
||||
"rotate-clockwise": RotateCw,
|
||||
save: Save,
|
||||
search: Search,
|
||||
settings: Settings,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { InspectorSelectPolicyContext } from "./InspectorContext.js";
|
||||
import { Select, type SelectProps } from "./Select.js";
|
||||
import { cn } from "./cn.js";
|
||||
import { Icon } from "./Icon.js";
|
||||
import { IconButton } from "./Button.js";
|
||||
|
||||
export interface InspectorSectionSpec {
|
||||
id: string;
|
||||
@@ -13,6 +14,7 @@ export interface InspectorSectionSpec {
|
||||
disabled?: boolean;
|
||||
tone?: "default" | "accent";
|
||||
icon?: ReactNode;
|
||||
action?: { label: string; icon: ReactNode; onAction: () => void; disabled?: boolean };
|
||||
}
|
||||
|
||||
export interface InspectorProps {
|
||||
@@ -74,6 +76,7 @@ export function Inspector({
|
||||
const isOpen = openIds.has(section.id);
|
||||
return (
|
||||
<section className="nodedc-inspector__section" key={section.id}>
|
||||
<div className="nodedc-inspector__section-head" data-action={section.action ? "true" : undefined}>
|
||||
<button
|
||||
type="button"
|
||||
className="nodedc-inspector__section-trigger"
|
||||
@@ -91,8 +94,13 @@ export function Inspector({
|
||||
<span className="nodedc-inspector__section-description">{section.description}</span>
|
||||
) : null}
|
||||
</span>
|
||||
<span className="nodedc-inspector__section-chevron" aria-hidden="true"><Icon name="chevron-right" size={14} /></span>
|
||||
<span className="nodedc-inspector__section-chevron" aria-hidden="true"><Icon name={variant === "panel" ? "chevron-down" : "chevron-right"} size={14} /></span>
|
||||
</button>
|
||||
{section.action ? <IconButton className="nodedc-inspector__section-action" label={section.action.label}
|
||||
disabled={section.disabled || section.action.disabled} onClick={section.action.onAction}>
|
||||
{section.action.icon}
|
||||
</IconButton> : null}
|
||||
</div>
|
||||
{isOpen ? <div className="nodedc-inspector__section-content">{section.content}</div> : null}
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
import { createContext } from "react";
|
||||
/** A composed content surface owns one pending indicator. Windows reset this scope. */
|
||||
export const LoadingContext = createContext<null | ((id: string, pending: boolean) => void)>(null);
|
||||
@@ -1,23 +1,38 @@
|
||||
import type { HTMLAttributes } from "react";
|
||||
import { useCallback, useContext, useId, useLayoutEffect, useState, type HTMLAttributes } from "react";
|
||||
import { ActivityIndicator } from "./ActivityIndicator.js";
|
||||
import { LoadingContext } from "./LoadingContext.js";
|
||||
import { cn } from "./cn.js";
|
||||
|
||||
export interface LoadingRegionProps extends HTMLAttributes<HTMLDivElement> {
|
||||
loading: boolean;
|
||||
label: string;
|
||||
/** Collect nested initial-content loads into this surface's single indicator. */
|
||||
aggregate?: boolean;
|
||||
}
|
||||
|
||||
/** Keeps content mounted and centers pending feedback inside its own bounds. */
|
||||
export function LoadingRegion({ loading, label, children, className, ...props }: LoadingRegionProps) {
|
||||
return (
|
||||
<div {...props} className={cn("nodedc-loading-region", className)} aria-busy={loading}>
|
||||
{children}
|
||||
{loading ? (
|
||||
<div className="nodedc-loading-region__status" role="status" aria-label={label}>
|
||||
<ActivityIndicator />
|
||||
<span aria-hidden="true">{label}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
/** Keeps content mounted. Failures/unmounts release each nested pending lease. */
|
||||
export function LoadingRegion({ loading, label, aggregate = false, children, className, ...props }: LoadingRegionProps) {
|
||||
const parent = useContext(LoadingContext);
|
||||
const id = useId();
|
||||
const [pending, setPending] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const report = useCallback((key: string, busy: boolean) => {
|
||||
setPending(previous => {
|
||||
if (previous.has(key) === busy) return previous;
|
||||
const next = new Set(previous);
|
||||
if (busy) next.add(key); else next.delete(key);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
useLayoutEffect(() => {
|
||||
parent?.(id, loading);
|
||||
return () => parent?.(id, false);
|
||||
}, [parent, id, loading]);
|
||||
const busy = loading || (aggregate && !parent && pending.size > 0);
|
||||
const content = <div {...props} className={cn("nodedc-loading-region", className)} aria-busy={busy}>
|
||||
{children}
|
||||
{busy && !parent ? <div className="nodedc-loading-region__status" role="status" aria-label={label}>
|
||||
<ActivityIndicator /><span aria-hidden="true">{label}</span>
|
||||
</div> : null}
|
||||
</div>;
|
||||
return aggregate && !parent ? <LoadingContext.Provider value={report}>{content}</LoadingContext.Provider> : content;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import {useState,type CSSProperties} from "react";
|
||||
export type CubeDirection = [number,number,number];
|
||||
export interface NavigationCubeProps {
|
||||
/** Camera world quaternion, Y up. Directions point from target toward camera. */
|
||||
quaternion: readonly [number,number,number,number];
|
||||
onSelect: (direction:CubeDirection)=>void;
|
||||
size?:number; face?:string; text?:string; edge?:string; hover?:string; hoverText?:string; opacity?:number; edgeOpacity?:number;
|
||||
disabled?:boolean;
|
||||
label?:string;
|
||||
}
|
||||
const faces = [
|
||||
{axis:0,sign:1,label:"RIGHT"},{axis:0,sign:-1,label:"LEFT"},
|
||||
{axis:1,sign:1,label:"TOP"},{axis:1,sign:-1,label:"BOTTOM"},
|
||||
{axis:2,sign:1,label:"FRONT"},{axis:2,sign:-1,label:"BACK"},
|
||||
];
|
||||
const cuts=[-1,-.55,.55,1];
|
||||
/** Inverse quaternion rotation; avoids a renderer or additional WebGL context. */
|
||||
function view(p:number[],q:readonly number[]) {
|
||||
const n=Math.hypot(...q)||1;
|
||||
const [x,y,z,w]=[-q[0]/n,-q[1]/n,-q[2]/n,q[3]/n], [a,b,c]=p;
|
||||
const tx=2*(y*c-z*b),ty=2*(z*a-x*c),tz=2*(x*b-y*a);
|
||||
return [a+w*tx+y*tz-z*ty,b+w*ty+z*tx-x*tz,c+w*tz+x*ty-y*tx];
|
||||
}
|
||||
export function cubeRegions(quaternion:NavigationCubeProps["quaternion"]) {
|
||||
return faces.flatMap(face=>{
|
||||
const axes=[0,1,2].filter(k=>k!==face.axis),normal=[0,0,0];normal[face.axis]=face.sign;
|
||||
if(view(normal,quaternion)[2]<1e-5)return [];
|
||||
const point=(u:number,v:number)=>{const p=[0,0,0];p[face.axis]=face.sign;p[axes[0]]=u;p[axes[1]]=v;return p;};
|
||||
return Array.from({length:9},(_,i)=>{
|
||||
const row=Math.floor(i/3),col=i%3,direction=point(col-1,row-1) as CubeDirection;
|
||||
const label=faces.filter(f=>direction[f.axis]===f.sign).map(f=>f.label).join(" · ");
|
||||
const polygon=[[cuts[col],cuts[row]],[cuts[col+1],cuts[row]],[cuts[col+1],cuts[row+1]],[cuts[col],cuts[row+1]]]
|
||||
.map(([u,v])=>view(point(u,v),quaternion)).map(p=>`${60+p[0]*30},${60-p[1]*30}`).join(" ");
|
||||
const p=view(point(0,0),quaternion);
|
||||
// Face-local right/up tangents keep labels printed on the rotating face.
|
||||
const right=face.axis===0?[0,0,-face.sign]:face.axis===1?[1,0,0]:[face.sign,0,0];
|
||||
const up=face.axis===1?[0,0,-face.sign]:[0,1,0];
|
||||
const u=view(right,quaternion),v=view(up,quaternion);
|
||||
const textMatrix=[u[0],-u[1],-v[0],v[1],60+p[0]*30,60-p[1]*30];
|
||||
return {id:`${face.label}-${i}`,direction,label,polygon,faceLabel:i===4?face.label:null,textMatrix};
|
||||
});
|
||||
});
|
||||
}
|
||||
/** BIM-style face / edge / corner navigation, independent of the scene engine. */
|
||||
export function NavigationCube({quaternion,onSelect,disabled=false,label="Навигационный куб",size=66,face,text,edge,hover:highlight,hoverText,opacity=1,edgeOpacity=1}:NavigationCubeProps) {
|
||||
const [hover,setHover]=useState<string|null>(null);
|
||||
return <svg className="nodedc-navigation-cube" style={{width:size,height:size,opacity,"--cube-face":face,"--cube-text":text,"--cube-edge":edge,"--cube-edge-opacity":edgeOpacity,"--cube-hover":highlight,"--cube-hover-text":hoverText} as CSSProperties} viewBox="0 0 120 120" role="group" aria-label={label}>
|
||||
{cubeRegions(quaternion).map(r=><g key={r.id} role="button" aria-label={`Ракурс: ${r.label}`} aria-disabled={disabled}
|
||||
tabIndex={disabled?-1:0} className={hover===r.label?"is-hovered":""}
|
||||
onPointerEnter={()=>setHover(r.label)} onPointerLeave={()=>setHover(null)}
|
||||
onClick={()=>{if(!disabled)onSelect(r.direction);}}
|
||||
onKeyDown={e=>{if(!disabled&&(e.key==="Enter"||e.key===" ")){e.preventDefault();onSelect(r.direction);}}}>
|
||||
<title>{r.label}</title><polygon points={r.polygon}/>
|
||||
{r.faceLabel?<text transform={`matrix(${r.textMatrix.join(" ")})`} x={0} y={0} dy=".35em" textAnchor="middle">{r.faceLabel}</text>:null}
|
||||
</g>)}
|
||||
</svg>;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { useId } from "react";
|
||||
import { Button, type ButtonProps } from "./Button.js";
|
||||
import { ProgressBar } from "./ProgressBar.js";
|
||||
import { Icon } from "./Icon.js";
|
||||
import { cn } from "./cn.js";
|
||||
|
||||
export interface ProgressButtonProps extends Omit<ButtonProps, "children" | "loading" | "size"> {
|
||||
label: string;
|
||||
/** Presence means pending. Value is measured progress of the named phase, not elapsed time. */
|
||||
progress?: { label: string; value?: number; valueText?: string };
|
||||
}
|
||||
|
||||
export function ProgressButton({ label, progress, className, disabled, icon, ...props }: ProgressButtonProps) {
|
||||
const statusId = useId();
|
||||
return <div className={cn("nodedc-progress-button", className)} data-pending={!!progress || undefined}
|
||||
data-icon={!!icon || undefined}>
|
||||
<Button {...props} icon={icon} disabled={disabled || !!progress} aria-busy={!!progress}
|
||||
aria-label={label} aria-describedby={progress ? statusId : undefined}>
|
||||
<span className="nodedc-progress-button__label">{progress?.label ?? label}</span>
|
||||
</Button>
|
||||
{progress ? <>
|
||||
<span id={statusId} className="nodedc-progress-button__status" role="status">{progress.label}</span>
|
||||
<ProgressBar label={label} value={progress.value} valueText={progress.valueText ?? progress.label} />
|
||||
</> : null}
|
||||
</div>;
|
||||
}
|
||||
|
||||
/** Decorative animation of the canonical layers glyph. The surrounding action owns live status. */
|
||||
export function LayerStackIndicator() {
|
||||
return <Icon name="layers" className="nodedc-layer-stack-indicator" />;
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type InputHTMLAttributes, type KeyboardEvent, type PointerEvent } from "react";
|
||||
import { VerticalRangeBand, type RangeBandControlProps } from "./VerticalRangeBand.js";
|
||||
export type { RangeBandControlProps } from "./VerticalRangeBand.js";
|
||||
import { cn } from "./cn.js";
|
||||
import { Dropdown } from "./Dropdown.js";
|
||||
|
||||
@@ -13,7 +15,7 @@ export interface RangeControlProps extends Omit<InputHTMLAttributes<HTMLInputEle
|
||||
max?: number;
|
||||
};
|
||||
formatValue?: (value: number) => string;
|
||||
/** Unit-free endpoint labels beside the vertical scale. */
|
||||
/** Unit-free retained lower bound and moving upper/value boundary. */
|
||||
formatLimit?: (value: number) => string;
|
||||
/** Physical side for vertical endpoint labels; use the inward side of a scene rail. */
|
||||
limitSide?: "left" | "right";
|
||||
@@ -55,7 +57,16 @@ const editableNumber = (value: number) => (
|
||||
Number.isInteger(value) ? String(value) : String(Number(value.toFixed(12)))
|
||||
);
|
||||
|
||||
export function RangeControl({
|
||||
function isBand(props: RangeControlProps | RangeBandControlProps): props is RangeBandControlProps {
|
||||
return Array.isArray(props.value);
|
||||
}
|
||||
export function RangeControl(props: RangeControlProps): ReturnType<typeof SingleRangeControl>;
|
||||
export function RangeControl(props: RangeBandControlProps): ReturnType<typeof VerticalRangeBand>;
|
||||
export function RangeControl(props: RangeControlProps | RangeBandControlProps) {
|
||||
return isBand(props) ? <VerticalRangeBand {...props} /> : <SingleRangeControl {...props} />;
|
||||
}
|
||||
|
||||
function SingleRangeControl({
|
||||
label,
|
||||
orientation = "horizontal",
|
||||
value,
|
||||
@@ -141,17 +152,13 @@ export function RangeControl({
|
||||
};
|
||||
|
||||
if (orientation === "vertical") return (
|
||||
<div className="nodedc-range-scale" data-limit-side={limitSide}>
|
||||
<div className="nodedc-range-scale" data-limit-side={limitSide} style={style}>
|
||||
<div ref={rootRef} className={cn("nodedc-range", className)} style={style} data-orientation="vertical">
|
||||
<input ref={rangeRef} {...props} type="range" value={value} min={min} max={safeMax} step={step}
|
||||
disabled={disabled} tabIndex={tabIndex} aria-label={label} aria-orientation="vertical"
|
||||
aria-valuetext={displayValue} onChange={(event) => onChange(Number(event.target.value))} />
|
||||
<span className="nodedc-range__label">{label} · {displayValue}</span>
|
||||
<span className="nodedc-range__fill-text" aria-hidden="true">
|
||||
<span className="nodedc-range__label">{label} · {displayValue}</span>
|
||||
</span>
|
||||
</div>
|
||||
<span className="nodedc-range-scale__limit nodedc-range-scale__limit--max">{formatLimit(max)}</span>
|
||||
<span className="nodedc-range-scale__limit nodedc-range-scale__limit--max">{formatLimit(clampRangeValue(value, min, safeMax))}</span>
|
||||
<span className="nodedc-range-scale__limit nodedc-range-scale__limit--min">{formatLimit(min)}</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { forwardRef, type ButtonHTMLAttributes, type HTMLAttributes, type ReactNode } from "react";
|
||||
import { cn } from "./cn.js";
|
||||
|
||||
export interface SegmentedItem<T extends string> {
|
||||
@@ -7,48 +7,46 @@ export interface SegmentedItem<T extends string> {
|
||||
icon?: ReactNode;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export type SegmentedControlSize = "default" | "dense";
|
||||
|
||||
export interface SegmentedControlProps<T extends string> {
|
||||
value: T;
|
||||
export type SegmentedControlProps<T extends string> = {
|
||||
items: Array<SegmentedItem<T>>;
|
||||
label: string;
|
||||
size?: SegmentedControlSize;
|
||||
className?: string;
|
||||
onChange: (value: T) => void;
|
||||
} & ({ selectionMode?: "single"; value: T; onChange: (value: T) => void }
|
||||
| { selectionMode: "multiple"; value: readonly T[]; onChange: (value: T[]) => void });
|
||||
|
||||
export function SegmentedControl<T extends string>(props: SegmentedControlProps<T>) {
|
||||
const { items, label, size = "default", className } = props;
|
||||
const multiple = props.selectionMode === "multiple";
|
||||
return <div className={cn("nodedc-segmented", className)}
|
||||
role={multiple ? "group" : "tablist"} aria-label={label}
|
||||
data-size={size === "default" ? undefined : size}>
|
||||
{items.map(item => {
|
||||
const active = props.selectionMode === "multiple" ? props.value.includes(item.value) : props.value === item.value;
|
||||
return <button key={item.value} type="button" className="nodedc-segmented__item"
|
||||
role={multiple ? undefined : "tab"} aria-selected={multiple ? undefined : active}
|
||||
aria-pressed={multiple ? active : undefined} data-active={active ? "true" : undefined}
|
||||
disabled={item.disabled} onClick={() => {
|
||||
if (props.selectionMode === "multiple") {
|
||||
props.onChange(active ? props.value.filter(value => value !== item.value) : [...props.value, item.value]);
|
||||
} else props.onChange(item.value);
|
||||
}}>{item.icon}{item.label}</button>;
|
||||
})}
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function SegmentedControl<T extends string>({
|
||||
value,
|
||||
items,
|
||||
label,
|
||||
size = "default",
|
||||
className,
|
||||
onChange,
|
||||
}: SegmentedControlProps<T>) {
|
||||
return (
|
||||
<div
|
||||
className={cn("nodedc-segmented", className)}
|
||||
role="tablist"
|
||||
aria-label={label}
|
||||
data-size={size === "default" ? undefined : size}
|
||||
>
|
||||
{items.map((item) => (
|
||||
<button
|
||||
key={item.value}
|
||||
type="button"
|
||||
className="nodedc-segmented__item"
|
||||
role="tab"
|
||||
aria-selected={item.value === value}
|
||||
data-active={item.value === value ? "true" : undefined}
|
||||
disabled={item.disabled}
|
||||
onClick={() => onChange(item.value)}
|
||||
>
|
||||
{item.icon}
|
||||
{item.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
/** Shared capsule for independently controlled toggles and menu triggers. */
|
||||
export function SegmentedGroup({ label, size = "default", className, ...props }:
|
||||
HTMLAttributes<HTMLDivElement> & { label: string; size?: SegmentedControlSize }) {
|
||||
return <div {...props} className={cn("nodedc-segmented", className)} role="group" aria-label={label}
|
||||
data-size={size === "default" ? undefined : size} />;
|
||||
}
|
||||
|
||||
/** Caller supplies aria-pressed for toggles or aria-expanded/haspopup for menu triggers. */
|
||||
export const SegmentedButton = forwardRef<HTMLButtonElement,
|
||||
ButtonHTMLAttributes<HTMLButtonElement> & { active?: boolean }
|
||||
>(function SegmentedButton({ active, className, type = "button", ...props }, ref) {
|
||||
return <button {...props} ref={ref} type={type} className={cn("nodedc-segmented__item", className)}
|
||||
data-active={active ? "true" : undefined} />;
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { HTMLAttributes, ReactNode } from "react";
|
||||
import { Description } from "./Description.js";
|
||||
import { cn } from "./cn.js";
|
||||
|
||||
export interface SettingsCardProps extends Omit<HTMLAttributes<HTMLElement>, "title"> {
|
||||
@@ -16,7 +17,7 @@ export function SettingsCard({ eyebrow, title, description, actions, children, a
|
||||
<div className="nodedc-settings-card__titles">
|
||||
{eyebrow ? <span>{eyebrow}</span> : null}
|
||||
<h2>{title}</h2>
|
||||
{description ? <p>{description}</p> : null}
|
||||
{description ? <Description>{description}</Description> : null}
|
||||
</div>
|
||||
{actions ? <div className="nodedc-settings-card__actions">{actions}</div> : null}
|
||||
</header>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useRef, useState, type CSSProperties } from "react";
|
||||
import { useCallback, useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
|
||||
import {
|
||||
calculateToolbarTargets,
|
||||
NODEDC_TOOLBAR_DEFAULTS,
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
stepToolbarSpring,
|
||||
type ToolbarPlacement as CoreToolbarPlacement,
|
||||
} from "@nodedc/ui-core";
|
||||
import { Dropdown, type DropdownTriggerApi } from "./Dropdown.js";
|
||||
import { useToolbarMenus } from "./useToolbarMenus.js";
|
||||
import { cn } from "./cn.js";
|
||||
import { Icon, type IconName } from "./Icon.js";
|
||||
|
||||
@@ -17,6 +19,8 @@ export interface ToolbarItem<T extends string = string> {
|
||||
icon: IconName;
|
||||
active?: boolean;
|
||||
disabled?: boolean;
|
||||
shortcut?: string;
|
||||
menu?: ReactNode | ((close: () => void) => ReactNode);
|
||||
onSelect: (id: T) => void;
|
||||
}
|
||||
|
||||
@@ -31,8 +35,12 @@ export interface ToolbarProps<T extends string = string> {
|
||||
maxSize?: number;
|
||||
lensCount?: number;
|
||||
autoHide?: boolean;
|
||||
hideDelay?: number;
|
||||
gap?: number;
|
||||
label?: string;
|
||||
className?: string;
|
||||
/** Render inside a positioned viewport; edge reveal follows that viewport. */
|
||||
container?: HTMLElement;
|
||||
}
|
||||
|
||||
interface ToolbarMotion {
|
||||
@@ -55,9 +63,13 @@ export function Toolbar<T extends string = string>({
|
||||
maxSize = NODEDC_TOOLBAR_DEFAULTS.maxSize,
|
||||
lensCount = NODEDC_TOOLBAR_DEFAULTS.lensCount,
|
||||
autoHide = false,
|
||||
hideDelay = NODEDC_TOOLBAR_DEFAULTS.hideDelay,
|
||||
gap = NODEDC_TOOLBAR_DEFAULTS.gap,
|
||||
label = "Панель инструментов",
|
||||
className,
|
||||
container,
|
||||
}: ToolbarProps<T>) {
|
||||
const menus = useToolbarMenus();
|
||||
const [visible, setVisible] = useState(!autoHide);
|
||||
const [dockActive, setDockActive] = useState(false);
|
||||
const toolbarRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -68,16 +80,19 @@ export function Toolbar<T extends string = string>({
|
||||
const frameLastTsRef = useRef(0);
|
||||
const hideTimerRef = useRef<number | null>(null);
|
||||
const hoverDockRef = useRef(false);
|
||||
const openMenusRef = useRef(new Set<string>());
|
||||
|
||||
const vertical = placement !== "bottom";
|
||||
const normalized = normalizeToolbarSettings({ minSize, maxSize, lensCount });
|
||||
const vertical = placement === "left" || placement === "right";
|
||||
const normalized = normalizeToolbarSettings({ minSize, maxSize, lensCount, gap });
|
||||
const safeMin = normalized.minSize;
|
||||
const safeMax = normalized.maxSize;
|
||||
const safeLens = normalized.lensCount;
|
||||
const safeGap = Math.min(24,normalized.gap);
|
||||
const safeDelay = Math.max(0,Math.min(15000,Number.isFinite(hideDelay)?hideDelay:NODEDC_TOOLBAR_DEFAULTS.hideDelay));
|
||||
const radius = Math.max(7, Math.round(safeMin * 0.28));
|
||||
const glyphSize = Math.max(12, Math.min(18, Math.round(safeMin * 0.62)));
|
||||
const settingsRef = useRef({ minSize: safeMin, maxSize: safeMax, lensCount: safeLens, vertical });
|
||||
settingsRef.current = { minSize: safeMin, maxSize: safeMax, lensCount: safeLens, vertical };
|
||||
const settingsRef = useRef({ minSize: safeMin, maxSize: safeMax, lensCount: safeLens, gap:safeGap, vertical });
|
||||
settingsRef.current = { minSize: safeMin, maxSize: safeMax, lensCount: safeLens, gap:safeGap, vertical };
|
||||
actionKeysRef.current = items.map((item) => String(item.id));
|
||||
|
||||
const getMotion = useCallback((key: string) => {
|
||||
@@ -176,7 +191,7 @@ export function Toolbar<T extends string = string>({
|
||||
const toolbar = toolbarRef.current;
|
||||
const keys = actionKeysRef.current;
|
||||
if (!toolbar || !keys.length) return;
|
||||
const { minSize: currentMin, maxSize: currentMax, lensCount: currentLens, vertical: isVertical } = settingsRef.current;
|
||||
const { minSize: currentMin, maxSize: currentMax, lensCount: currentLens, gap:currentGap, vertical: isVertical } = settingsRef.current;
|
||||
const toolbarRect = toolbar.getBoundingClientRect();
|
||||
const entries = keys
|
||||
.map((key) => {
|
||||
@@ -193,7 +208,7 @@ export function Toolbar<T extends string = string>({
|
||||
const targets = calculateToolbarTargets(
|
||||
entries.map((entry) => entry.center),
|
||||
pointerCoordinate,
|
||||
{ minSize: currentMin, maxSize: currentMax, lensCount: currentLens, gap: NODEDC_TOOLBAR_DEFAULTS.gap },
|
||||
{ minSize: currentMin, maxSize: currentMax, lensCount: currentLens, gap: currentGap },
|
||||
);
|
||||
entries.forEach(({ key }, index) => {
|
||||
const target = targets[index];
|
||||
@@ -213,18 +228,19 @@ export function Toolbar<T extends string = string>({
|
||||
if (!autoHide || hideTimerRef.current != null) return;
|
||||
hideTimerRef.current = window.setTimeout(() => {
|
||||
hideTimerRef.current = null;
|
||||
if (hoverDockRef.current) return;
|
||||
if (hoverDockRef.current || openMenusRef.current.size || toolbarRef.current?.contains(document.activeElement)) return;
|
||||
setVisible(false);
|
||||
resetMagnification();
|
||||
}, NODEDC_TOOLBAR_DEFAULTS.hideDelay);
|
||||
}, [autoHide, resetMagnification]);
|
||||
}, safeDelay);
|
||||
}, [autoHide, resetMagnification, safeDelay]);
|
||||
|
||||
useEffect(() => {
|
||||
if (hideTimerRef.current != null) { window.clearTimeout(hideTimerRef.current); hideTimerRef.current = null; }
|
||||
if (!autoHide) {
|
||||
setVisible(true);
|
||||
return;
|
||||
}
|
||||
setVisible(false);
|
||||
setVisible(hoverDockRef.current || openMenusRef.current.size > 0);
|
||||
setDockActive(false);
|
||||
}, [autoHide]);
|
||||
|
||||
@@ -236,17 +252,19 @@ export function Toolbar<T extends string = string>({
|
||||
if (!autoHide) return;
|
||||
const handlePointerMove = (event: PointerEvent) => {
|
||||
const threshold = Math.max(32, settingsRef.current.maxSize * 0.75);
|
||||
const nearEdge = placement === "left"
|
||||
? event.clientX <= threshold
|
||||
const bounds = container?.getBoundingClientRect() ?? {left:0, top:0, right:window.innerWidth, bottom:window.innerHeight};
|
||||
const inside = event.clientX >= bounds.left && event.clientX <= bounds.right && event.clientY >= bounds.top && event.clientY <= bounds.bottom;
|
||||
const nearEdge = inside && (placement === "left"
|
||||
? event.clientX <= bounds.left + threshold
|
||||
: placement === "right"
|
||||
? event.clientX >= window.innerWidth - threshold
|
||||
: event.clientY >= window.innerHeight - threshold;
|
||||
? event.clientX >= bounds.right - threshold
|
||||
: placement === "top" ? event.clientY <= bounds.top + threshold : event.clientY >= bounds.bottom - threshold);
|
||||
if (nearEdge) showDock();
|
||||
else if (!hoverDockRef.current) scheduleHide();
|
||||
};
|
||||
window.addEventListener("pointermove", handlePointerMove, { passive: true });
|
||||
return () => window.removeEventListener("pointermove", handlePointerMove);
|
||||
}, [autoHide, placement, scheduleHide, showDock]);
|
||||
}, [autoHide, placement, container, scheduleHide, showDock]);
|
||||
|
||||
useEffect(() => {
|
||||
const handlePointerMove = (event: PointerEvent) => {
|
||||
@@ -271,6 +289,11 @@ export function Toolbar<T extends string = string>({
|
||||
if (hideTimerRef.current != null) window.clearTimeout(hideTimerRef.current);
|
||||
}, []);
|
||||
|
||||
useEffect(()=>{
|
||||
const keys=new Set(items.map(i=>String(i.id)));
|
||||
for(const key of openMenusRef.current)if(!keys.has(key)){openMenusRef.current.delete(key);delete menus.apis.current[key];if(menus.active.current===key)menus.active.current=null;}
|
||||
},[items,menus]);
|
||||
|
||||
const style = {
|
||||
"--nodedc-toolbar-bg": background,
|
||||
"--nodedc-toolbar-border": border,
|
||||
@@ -279,7 +302,7 @@ export function Toolbar<T extends string = string>({
|
||||
"--nodedc-toolbar-min-size": `${safeMin}px`,
|
||||
"--nodedc-toolbar-max-size": `${safeMax}px`,
|
||||
"--nodedc-toolbar-radius": `${radius}px`,
|
||||
"--nodedc-toolbar-gap": `${NODEDC_TOOLBAR_DEFAULTS.gap}px`,
|
||||
"--nodedc-toolbar-gap": `${safeGap}px`,
|
||||
"--nodedc-toolbar-padding": `${NODEDC_TOOLBAR_DEFAULTS.padding}px`,
|
||||
} as CSSProperties;
|
||||
|
||||
@@ -287,6 +310,7 @@ export function Toolbar<T extends string = string>({
|
||||
<div
|
||||
className={cn("nodedc-toolbar-wrap", className)}
|
||||
data-placement={placement}
|
||||
data-scope={container ? "viewport" : "window"}
|
||||
data-visible={visible ? "true" : undefined}
|
||||
data-active={dockActive ? "true" : undefined}
|
||||
data-autohide={autoHide ? "true" : undefined}
|
||||
@@ -324,17 +348,23 @@ export function Toolbar<T extends string = string>({
|
||||
>
|
||||
{items.map((item) => {
|
||||
const key = String(item.id);
|
||||
return (
|
||||
const button = (api?: DropdownTriggerApi) => {
|
||||
if(api)menus.apis.current[key]=api;
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
ref={(element) => { buttonRefs.current[key] = element; }}
|
||||
ref={(element) => { buttonRefs.current[key] = element; api?.setTriggerRef(element); }}
|
||||
type="button"
|
||||
className="nodedc-toolbar__button"
|
||||
data-toolbar-menu={item.menu ? key : undefined}
|
||||
data-active={item.active ? "true" : undefined}
|
||||
aria-label={item.label}
|
||||
title={item.shortcut ? `${item.label} · ${item.shortcut}` : item.label}
|
||||
aria-keyshortcuts={item.shortcut}
|
||||
aria-pressed={item.active}
|
||||
disabled={item.disabled}
|
||||
onFocus={(event) => {
|
||||
showDock();
|
||||
const button = event.currentTarget;
|
||||
const toolbarRect = toolbarRef.current?.getBoundingClientRect();
|
||||
if (!toolbarRect) return;
|
||||
@@ -345,11 +375,34 @@ export function Toolbar<T extends string = string>({
|
||||
updateMagnification(coordinate);
|
||||
}}
|
||||
onBlur={resetMagnification}
|
||||
onClick={() => item.onSelect(item.id)}
|
||||
aria-haspopup={item.menu ? "menu" : undefined}
|
||||
aria-expanded={item.menu ? api?.open : undefined}
|
||||
onClick={() => item.menu ? api?.toggle() : item.onSelect(item.id)}
|
||||
>
|
||||
<Icon name={item.icon} size={glyphSize} />
|
||||
</button>
|
||||
);
|
||||
);};
|
||||
return item.menu ? <Dropdown key={key} placement={placement === "right" ? "left-start" : placement === "left" ? "right-start" : placement === "bottom" ? "top-end" : "bottom-end"} flip={false} getAnchorRect={()=>{
|
||||
const button=buttonRefs.current[key], toolbar=toolbarRef.current;
|
||||
if(!button||!toolbar)return null;
|
||||
const b=button.getBoundingClientRect(), t=toolbar.getBoundingClientRect();
|
||||
// Reserve the largest possible icon, including while its spring is still moving.
|
||||
const pad=Math.max(safeMax,...Object.values(buttonRefs.current).map(n=>n?.getBoundingClientRect().width??0));
|
||||
if(placement==="right")return {...b.toJSON(),left:t.right-pad,right:t.right,width:pad};
|
||||
if(placement==="left")return {...b.toJSON(),left:t.left,right:t.left+pad,width:pad};
|
||||
if(placement==="bottom")return {...b.toJSON(),top:t.bottom-pad,bottom:t.bottom,height:pad};
|
||||
return {...b.toJSON(),top:t.top,bottom:t.top+pad,height:pad};
|
||||
}} width={220} trigger={button} onPointerDownOutside={event=>{
|
||||
const target=event.target as Element;
|
||||
// Dismiss a menu before a viewport tool can turn this same click into an edit.
|
||||
if(container?.contains(target)&&!target.closest('button,input,select,textarea,a,[role="button"],[role="tab"]')){
|
||||
event.preventDefault();event.stopPropagation();
|
||||
}
|
||||
}} onOpenChange={open => {
|
||||
if(open){openMenusRef.current.add(key);menus.active.current=key;showDock();}else{openMenusRef.current.delete(key);if(menus.active.current===key)menus.active.current=null;scheduleHide();}
|
||||
}}>
|
||||
{({close}) => typeof item.menu === "function" ? item.menu(close) : item.menu}
|
||||
</Dropdown> : button();
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useRef, type CSSProperties, type PointerEvent } from "react";
|
||||
import type { RangeControlProps } from "./RangeControl.js";
|
||||
import { cn } from "./cn.js";
|
||||
import { moveRangeBoundary, nearestRangeBoundary, normalizeRangeBand } from "./rangeBand.js";
|
||||
|
||||
export interface RangeBandControlProps extends Omit<RangeControlProps, "value" | "onChange" | "orientation" | "exactValueBounds"> {
|
||||
orientation: "vertical";
|
||||
value: readonly [number, number];
|
||||
onChange: (value: [number, number]) => void;
|
||||
lowerLabel?: string;
|
||||
upperLabel?: string;
|
||||
}
|
||||
|
||||
/** Two native keyboard targets, with one pointer track selecting its nearest boundary. */
|
||||
export function VerticalRangeBand({ label, value, min, max, step = 1, onChange,
|
||||
lowerLabel = `${label}: нижняя граница`, upperLabel = `${label}: верхняя граница`,
|
||||
formatValue = String, formatLimit = String, limitSide = "right", disabled = false,
|
||||
className, style, orientation: _orientation, ...props }: RangeBandControlProps) {
|
||||
const safeMax = max > min ? max : min + 1;
|
||||
const band = normalizeRangeBand(value, min, safeMax);
|
||||
const current = useRef(band); current.current = band;
|
||||
const inputs = useRef<(HTMLInputElement | null)[]>([]);
|
||||
const drag = useRef<{ id: number; boundary: 0 | 1 } | null>(null);
|
||||
const progress = band.map(n => (n - min) / (safeMax - min) * 100);
|
||||
const variables = { ...style, "--nodedc-range-lower": `${progress[0]}%`,
|
||||
"--nodedc-range-upper": `${progress[1]}%` } as CSSProperties;
|
||||
const change = (boundary: 0 | 1, next: number) => {
|
||||
const result = moveRangeBoundary(current.current, boundary, next, min, safeMax, step);
|
||||
current.current = result; onChange(result);
|
||||
};
|
||||
const position = (event: PointerEvent<HTMLDivElement>) => {
|
||||
const rect = event.currentTarget.getBoundingClientRect();
|
||||
return min + Math.max(0, Math.min(1, (rect.bottom - event.clientY) / rect.height)) * (safeMax - min);
|
||||
};
|
||||
const end = (event: PointerEvent<HTMLDivElement>) => {
|
||||
if (drag.current?.id !== event.pointerId) return;
|
||||
drag.current = null;
|
||||
if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
};
|
||||
return <div className="nodedc-range-scale" data-band="true" data-limit-side={limitSide} data-disabled={disabled || undefined} style={variables}>
|
||||
<div className={cn("nodedc-range", className)} data-orientation="vertical">
|
||||
<div className="nodedc-range-band__target"
|
||||
onPointerDown={event => {
|
||||
if (disabled || event.button !== 0 || drag.current) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
const next = position(event), boundary = nearestRangeBoundary(current.current, next);
|
||||
drag.current = { id: event.pointerId, boundary };
|
||||
inputs.current[boundary]?.focus({ preventScroll: true });
|
||||
event.currentTarget.setPointerCapture(event.pointerId); change(boundary, next);
|
||||
}}
|
||||
onPointerMove={event => {
|
||||
if (disabled || drag.current?.id !== event.pointerId) return;
|
||||
event.preventDefault(); event.stopPropagation(); change(drag.current.boundary, position(event));
|
||||
}} onPointerUp={end} onPointerCancel={end} onLostPointerCapture={() => { drag.current = null; }}>
|
||||
{([0, 1] as const).map(boundary => <input {...props} key={boundary}
|
||||
ref={node => { inputs.current[boundary] = node; }} type="range" data-boundary={boundary === 0 ? "lower" : "upper"}
|
||||
min={min} max={safeMax} step={step} value={band[boundary]} disabled={disabled}
|
||||
aria-label={boundary === 0 ? lowerLabel : upperLabel} aria-orientation="vertical"
|
||||
aria-valuemin={boundary === 0 ? min : band[0]} aria-valuemax={boundary === 0 ? band[1] : safeMax}
|
||||
aria-valuetext={formatValue(band[boundary])}
|
||||
onChange={event => change(boundary, Number(event.target.value))} />)}
|
||||
</div>
|
||||
</div>
|
||||
<span className="nodedc-range-scale__limit nodedc-range-scale__limit--max">{formatLimit(band[1])}</span>
|
||||
<span className="nodedc-range-scale__limit nodedc-range-scale__limit--min">{formatLimit(band[0])}</span>
|
||||
</div>;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
} from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { InspectorSelectPolicyContext } from "./InspectorContext.js";
|
||||
import { LoadingContext } from "./LoadingContext.js";
|
||||
import { cn } from "./cn.js";
|
||||
import { Icon } from "./Icon.js";
|
||||
|
||||
@@ -154,7 +155,7 @@ export function Window({
|
||||
};
|
||||
|
||||
return createPortal(
|
||||
<InspectorSelectPolicyContext.Provider value={false}>
|
||||
<LoadingContext.Provider value={null}><InspectorSelectPolicyContext.Provider value={false}>
|
||||
<div className="nodedc-overlay nodedc-ui-root" data-placement={placement} onPointerDown={handleBackdropPointerDown}>
|
||||
<div
|
||||
ref={dialogRef}
|
||||
@@ -196,8 +197,8 @@ export function Window({
|
||||
{footer ? <footer className="nodedc-window__footer">{footer}</footer> : null}
|
||||
</div>
|
||||
</div>
|
||||
</InspectorSelectPolicyContext.Provider>,
|
||||
document.body,
|
||||
</InspectorSelectPolicyContext.Provider></LoadingContext.Provider>,
|
||||
document.fullscreenElement ?? document.body,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ export interface WorkspaceWindowProps extends Omit<HTMLAttributes<HTMLDivElement
|
||||
minWidth?: number;
|
||||
minHeight?: number;
|
||||
resizable?: boolean;
|
||||
resizeIndicator?: boolean;
|
||||
autoHeight?: boolean;
|
||||
active?: boolean;
|
||||
zIndex?: number;
|
||||
@@ -124,6 +125,7 @@ export function WorkspaceWindow({
|
||||
minWidth = 260,
|
||||
minHeight = 180,
|
||||
resizable = true,
|
||||
resizeIndicator = true,
|
||||
autoHeight = false,
|
||||
active = false,
|
||||
zIndex,
|
||||
@@ -377,6 +379,7 @@ export function WorkspaceWindow({
|
||||
data-active={active ? "true" : undefined}
|
||||
data-maximized={maximized ? "true" : undefined}
|
||||
data-resizable={resizable ? "true" : undefined}
|
||||
data-resize-indicator={resizeIndicator ? undefined : "hidden"}
|
||||
data-auto-height={autoHeight ? "true" : undefined}
|
||||
data-interaction={interactionKind ?? undefined}
|
||||
role="dialog"
|
||||
|
||||
@@ -1,20 +1,26 @@
|
||||
export * from "./AppHeader.js";
|
||||
export * from "./ActivityIndicator.js";
|
||||
export * from "./LoadingRegion.js";
|
||||
export * from "./Description.js";
|
||||
export * from "./ComparisonTable.js";
|
||||
export * from "./AdminNavigationPanel.js";
|
||||
export * from "./ApplicationShell.js";
|
||||
export * from "./ApplicationSidePanel.js";
|
||||
export * from "./ApplicationWorkspace.js";
|
||||
export * from "./Button.js";
|
||||
export * from "./ProgressButton.js";
|
||||
export * from "./Checker.js";
|
||||
export * from "./ConfirmationModal.js";
|
||||
export * from "./Dropdown.js";
|
||||
export * from "./DragDrop.js";
|
||||
export * from "./DockLayout.js";
|
||||
export {decodeDockTree, dockIds, balancedDockTree, reconcileDockTree, pruneDockTree, moveDockPanel, resizeDockSplit, dockRects, dockPosition, type DockTree, type DockMove, type DockRect, type DockPosition} from "@nodedc/ui-core";
|
||||
export * from "./Field.js";
|
||||
export * from "./FeatureSettingsWindow.js";
|
||||
export * from "./Glass.js";
|
||||
export * from "./Inspector.js";
|
||||
export * from "./Icon.js";
|
||||
export * from "./NavigationCube.js";
|
||||
export * from "./MediaSourceField.js";
|
||||
export * from "./RangeControl.js";
|
||||
export * from "./ResourceRow.js";
|
||||
@@ -36,3 +42,5 @@ export * from "./EnvironmentMediaPlaylistEditor.js";
|
||||
export * from "./EnvironmentBackgroundMedia.js";
|
||||
export * from "./LandingStage.js";
|
||||
export {KeyButton, type KeyButtonProps} from './KeyButton.js';
|
||||
|
||||
export type {DockMinimum, DockMinimums} from "@nodedc/ui-core";
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
export type RangeBand = readonly [number, number];
|
||||
const clamp = (n: number, min: number, max: number) => Math.max(min, Math.min(max, n));
|
||||
|
||||
export function normalizeRangeBand(value: RangeBand, min: number, max: number): [number, number] {
|
||||
const low = clamp(value[0], min, max);
|
||||
return [low, clamp(value[1], low, max)];
|
||||
}
|
||||
|
||||
export function nearestRangeBoundary([low, high]: RangeBand, value: number): 0 | 1 {
|
||||
// Coincident boundaries remain separable: below pulls the lower, above the upper.
|
||||
return value <= (low + high) / 2 ? 0 : 1;
|
||||
}
|
||||
|
||||
export function moveRangeBoundary(value: RangeBand, boundary: 0 | 1, next: number,
|
||||
min: number, max: number, step: string | number = 1): [number, number] {
|
||||
const band = normalizeRangeBand(value, min, max);
|
||||
const increment = Number(step);
|
||||
const bounded = clamp(next, min, max);
|
||||
// Exact endpoints stay reachable even when the range is not step-aligned.
|
||||
const aligned = bounded === min || bounded === max || !Number.isFinite(increment) || increment <= 0
|
||||
? bounded : Number((min + Math.round((bounded - min) / increment) * increment).toPrecision(12));
|
||||
band[boundary] = boundary === 0 ? clamp(aligned, min, band[1]) : clamp(aligned, band[0], max);
|
||||
return band;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import {useEffect,useRef} from "react";
|
||||
import {movingToMenu,type MenuPoint} from "@nodedc/ui-core";
|
||||
import type {DropdownTriggerApi} from "./Dropdown.js";
|
||||
export function useToolbarMenus() {
|
||||
const apis=useRef<Record<string,DropdownTriggerApi>>({});
|
||||
const active=useRef<string|null>(null);
|
||||
useEffect(()=>{
|
||||
let previous:MenuPoint|null=null, origin:MenuPoint|null=null, pending:string|null=null, timer:number|undefined;
|
||||
const clear=()=>{window.clearTimeout(timer);timer=undefined;pending=null;};
|
||||
const open=(key:string)=>{clear();apis.current[key]?.show();};
|
||||
const move=(event:PointerEvent)=>{
|
||||
const current={x:event.clientX,y:event.clientY}, old=previous;previous=current;
|
||||
const key=active.current;if(!key){clear();origin=null;return;}
|
||||
const api=apis.current[key], surface=document.getElementById(api?.surfaceId);
|
||||
const target=event.target instanceof Element?event.target:null;
|
||||
if(surface?.contains(target)){clear();origin=current;return;}
|
||||
const button=target?.closest<HTMLButtonElement>('[data-toolbar-menu]');
|
||||
const next=button?.dataset.toolbarMenu;
|
||||
if(next===key){clear();origin=current;return;}
|
||||
if(!next||!apis.current[next]||button?.disabled){clear();return;}
|
||||
if(!origin)origin=old??current;
|
||||
const delay=surface&&old&&movingToMenu(origin,old,current,surface.getBoundingClientRect());
|
||||
if(!delay){open(next);origin=current;return;}
|
||||
if(pending===next)return;
|
||||
clear();pending=next;
|
||||
// Bounded grace: pausing on a sibling still switches, crossing diagonally into the menu does not.
|
||||
timer=window.setTimeout(()=>open(next),300);
|
||||
};
|
||||
document.addEventListener("pointermove",move,{passive:true});
|
||||
return()=>{clear();document.removeEventListener("pointermove",move);};
|
||||
},[]);
|
||||
return {apis,active};
|
||||
}
|
||||
Reference in New Issue
Block a user