import React, { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { createPortal } from "react-dom"; import type { WebModuleRouter } from "./module-router.js"; import { areas, onToolbarPreferencesChanged, restoreToolbars, saveToolbars, readToolbarVisibility, setToolbarVisibility, type Area, type Placement } from "./toolbar-preferences.js"; import { ToolbarVisibilityMenu } from "./toolbar-visibility-menu.js"; const names = ["Workbench", "Solids", "Part Tools", "Boolean Tools", "Spreadsheet tools", "3D display controls"]; const Hosts = createContext>(new Map()); export function ToolbarGroup({ name, children }: { name: string; children: React.ReactNode }) { const hosts = useContext(Hosts); const host = hosts.get(name); return host ? createPortal(children, host) : null; } export function PersistentToolbarWorkspace({ router, documentId, workbench, children }: { router: WebModuleRouter; documentId: string; workbench: string; children: React.ReactNode; }) { const defaults = useMemo(() => names.filter(name => name === "Workbench" || name === "3D display controls" || (workbench === "Part" ? ["Solids", "Part Tools", "Boolean Tools"].includes(name) : workbench === "Spreadsheet" && name === "Spreadsheet tools")) .map(name => ({ name, area: "Top", breakBefore: false })), [workbench]); const hosts = useMemo(() => new Map(names.map(name => { const host = document.createElement("div"); host.className = "persistent-toolbar workbench-toolbar"; host.dataset.toolbarName = name; host.setAttribute("role", "toolbar"); host.setAttribute("aria-label", name); return [name, host] as const; })), []); const root = useRef(null); const arrangeButton = useRef(null); const editor = useRef(null); const [layout, setLayout] = useState(defaults); const [visibility, setVisibility] = useState>({}); const [draft, setDraft] = useState(null); const [ready, setReady] = useState(false); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); const [restoreAttempt, setRestoreAttempt] = useState(0); const revision = useRef(0); useEffect(() => { let disposed = false; const refresh = () => { const token = ++revision.current; setDraft(null); setReady(false); setError(""); void Promise.all([restoreToolbars(router, documentId, workbench, defaults), readToolbarVisibility(router, documentId)]).then(([value, visible]) => { if (!disposed && token === revision.current) { const seen = new Set(); const migrated = value.map(item => ({ ...item, name: item.name === "Part tools" ? "Part Tools" : item.name })) .filter(item => { if (seen.has(item.name) || !hosts.has(item.name)) return false; seen.add(item.name); return true; }); setLayout(migrated); setVisibility(visible); setError(""); setReady(true); } }).catch(cause => { if (!disposed && token === revision.current) setError(String(cause)); }); }; refresh(); const unsubscribe = onToolbarPreferencesChanged(refresh); return () => { disposed = true; ++revision.current; unsubscribe(); }; }, [router, documentId, workbench, defaults, hosts, restoreAttempt]); useLayoutEffect(() => { const node = root.current!; for (const area of areas) { const dock = node.querySelector(`[data-toolbar-area=${area}]`)!; const oldLines = Array.from(dock.children); let line: HTMLDivElement | undefined; for (const item of draft ?? layout) { const host = hosts.get(item.name); if (item.area !== area || !host) continue; if (!line || item.breakBefore) { line = document.createElement("div"); line.className = "toolbar-line"; dock.append(line); } line.append(host); } oldLines.forEach(item => item.remove()); } }, [hosts, layout, draft]); useLayoutEffect(() => { for (const [name, host] of hosts) host.hidden = visibility[name] === false; }, [hosts, visibility]); useEffect(() => { const node = root.current!; const host = hosts.get("3D display controls")!; const attach = () => { const toolbar = node.querySelector(".scene-display-tools"); if (toolbar && toolbar.parentElement !== host) host.append(toolbar); }; attach(); const observer = new MutationObserver(attach); observer.observe(node, { childList: true, subtree: true }); return () => observer.disconnect(); }, [hosts]); useEffect(() => { if (!draft) return; editor.current?.querySelector('select:not(:disabled), button:not(:disabled)')?.focus(); }, [draft !== null]); const cancelDraft = () => { setDraft(null); arrangeButton.current?.focus(); }; useEffect(() => { if (!draft) return; const cancel = (event: KeyboardEvent) => { if (event.key !== "Escape") return; event.preventDefault(); event.stopImmediatePropagation(); if (!busy) cancelDraft(); }; window.addEventListener("keydown", cancel, true); return () => window.removeEventListener("keydown", cancel, true); }, [draft, busy]); const move = (name: string, offset: number) => setDraft(previous => { if (!previous) return previous; const next = previous.map(item => ({ ...item })); const index = next.findIndex(item => item.name === name); const siblings = next.map((item, i) => item.area === next[index].area ? i : -1).filter(i => i >= 0); const target = siblings[siblings.indexOf(index) + offset]; if (target !== undefined) [next[index], next[target]] = [next[target], next[index]]; return next; }); const apply = async () => { if (!draft || busy) return; const value = draft; const token = revision.current; setBusy(true); setError(""); try { await saveToolbars(router, documentId, workbench, value); if (token === revision.current) { setLayout(value); setDraft(null); } } catch (cause) { if (token === revision.current) setError(`Toolbar placement could not be saved: ${String(cause)}`); } finally { setBusy(false); } }; const toggleVisibility = async (name: string, visible: boolean) => { if (!ready || busy || draft) return; const token = revision.current; setBusy(true); setError(""); try { await setToolbarVisibility(router, documentId, name, visible); if (token === revision.current) setVisibility(previous => ({ ...previous, [name]: visible })); } catch (cause) { if (token === revision.current) setError(`Toolbar visibility could not be saved: ${String(cause)}`); } finally { setBusy(false); } }; return
item.name)} visibility={visibility} disabled={!ready || busy || !!draft} toggle={(name, visible) => void toggleVisibility(name, visible)} /> {error && {error}} {error && !ready && } {draft &&
{ if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); if (!busy) cancelDraft(); } }}> {draft.filter(item => hosts.has(item.name)).map(item =>
{item.name}
)}
}
{areas.map(area =>
)}
{children}
; }