Files
FreeCADWasmDev/web/src/persistent-toolbar-workspace.tsx
wangdequan 789e18ca3e
Some checks failed
FreeCAD master CI / Prepare (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Scorecard supply-chain security / Scorecard analysis (push) Has been cancelled
FreeCAD master CI / Pixi (push) Has been cancelled
FreeCAD master CI / Ubuntu (push) Has been cancelled
FreeCAD master CI / Windows (push) Has been cancelled
FreeCAD master CI / Lint (push) Has been cancelled
FreeCAD master CI / WrapUp (push) Has been cancelled
Stale Issues / stale (push) Has been cancelled
CodeQL Advanced (c-cpp) / Analyze (c-cpp) (push) Has been cancelled
Push Crowdin Translations / update-crowdin (push) Has been cancelled
Fetch Crowdin Translations / update-crowdin (push) Has been cancelled
Build Release / upload_src (push) Has been cancelled
Build Release / build (10.13, macos-15-intel, osx-64) (push) Has been cancelled
Build Release / build (11.0, macos-latest, osx-arm64) (push) Has been cancelled
Build Release / build (15.0, macos-latest, osx-arm64) (push) Has been cancelled
Build Release / build (ubuntu-22.04, linux-64) (push) Has been cancelled
Build Release / build (ubuntu-22.04-arm, linux-arm64) (push) Has been cancelled
Build Release / build (windows-latest, win-64) (push) Has been cancelled
Monthly issue metrics / issue metrics (push) Has been cancelled
Continue FreeCAD Web UI parity repairs
2026-09-23 14:03:56 +08:00

174 lines
12 KiB
TypeScript

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<Map<string, HTMLElement>>(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<Placement[]>(() => 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<HTMLDivElement>(null);
const arrangeButton = useRef<HTMLButtonElement>(null);
const editor = useRef<HTMLDivElement>(null);
const [layout, setLayout] = useState<Placement[]>(defaults);
const [visibility, setVisibility] = useState<Record<string, boolean>>({});
const [draft, setDraft] = useState<Placement[] | null>(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<string>();
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<HTMLElement>(`[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<HTMLElement>(".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<HTMLElement>('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 <Hosts.Provider value={hosts}><div ref={root} className="toolbar-workspace">
<style>{`
.toolbar-workspace{display:grid;grid-template-columns:auto minmax(0,1fr) auto;grid-template-rows:auto auto minmax(0,1fr) auto}
.toolbar-placement-controls{grid-column:1/-1;padding:4px 14px;background:#17212b}
.toolbar-dock{display:flex;flex-direction:column;align-content:flex-start;align-items:flex-start;gap:4px;min-width:0;background:#17212b}
.toolbar-dock[data-toolbar-area=Top]{grid-column:1/-1;grid-row:2;flex-wrap:wrap}
.toolbar-dock[data-toolbar-area=Bottom]{grid-column:1/-1;grid-row:4;flex-wrap:wrap}
.toolbar-dock[data-toolbar-area=Left]{grid-column:1;grid-row:3}
.toolbar-dock[data-toolbar-area=Right]{grid-column:3;grid-row:3}
.toolbar-content{grid-column:2;grid-row:3;min-width:0}
.persistent-toolbar{max-width:100%;padding:4px!important;gap:4px!important}
.persistent-toolbar:empty{display:none}
.persistent-toolbar[hidden]{display:none!important}
.toolbar-visibility-menu{min-width:210px;max-width:calc(100vw - 8px);max-height:calc(100vh - 8px);overflow:auto;padding:3px;background:#17212b;color:#e7edf3;border:1px solid #435464;box-shadow:0 4px 12px #0006}
.toolbar-visibility-menu button{display:flex;align-items:center;gap:8px;width:100%;padding:5px 8px;text-align:left;background:transparent;color:inherit;border:0;border-radius:0;font:inherit;font-size:13px}
.toolbar-visibility-menu button span{width:16px;flex-shrink:0}.toolbar-visibility-menu button:hover,.toolbar-visibility-menu button:focus-visible{background:#264b56;outline:1px solid #66c7d5;outline-offset:-1px}
.toolbar-dock .toolbar-break{flex-basis:100%;height:0}
.toolbar-line{display:flex;flex-wrap:wrap;align-items:flex-start;gap:4px}.toolbar-dock[data-toolbar-area=Left],.toolbar-dock[data-toolbar-area=Right]{flex-direction:row;max-width:35vw;overflow:auto}.toolbar-dock[data-toolbar-area=Left] .toolbar-line,.toolbar-dock[data-toolbar-area=Right] .toolbar-line{flex-direction:column;flex-wrap:nowrap}
.toolbar-dock[data-toolbar-area=Left] .persistent-toolbar,.toolbar-dock[data-toolbar-area=Right] .persistent-toolbar{width:150px;flex-direction:column;align-items:stretch}
.toolbar-dock[data-toolbar-area=Left] .toolbar-break,.toolbar-dock[data-toolbar-area=Right] .toolbar-break{width:0;height:100%;flex-basis:100%}
.persistent-toolbar:empty{display:none}
.persistent-toolbar .scene-display-tools{position:static;max-width:100%;border:0;margin:0}
.toolbar-placement-editor{display:flex;flex-wrap:wrap;gap:10px;padding:8px;border:1px solid #435464}
.toolbar-placement-editor label{display:inline-flex;gap:5px;align-items:center}.toolbar-placement-row{display:flex;flex-wrap:wrap;align-items:center;gap:8px;width:100%}
`}</style>
<div className="toolbar-placement-controls">
<ToolbarVisibilityMenu workspace={root} names={defaults.map(item => item.name)} visibility={visibility}
disabled={!ready || busy || !!draft} toggle={(name, visible) => void toggleVisibility(name, visible)} />
<button ref={arrangeButton} disabled={!ready || busy} onClick={() => setDraft(layout.map(item => ({ ...item })))}>Arrange toolbars</button>
{error && <span role="alert">{error}</span>}
{error && !ready && <button disabled={busy} onClick={() => setRestoreAttempt(attempt => attempt + 1)}>Retry toolbar preferences</button>}
{draft && <div ref={editor} className="toolbar-placement-editor" role="dialog" aria-label="Toolbar placement" onKeyDown={event => {
if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); if (!busy) cancelDraft(); }
}}>
{draft.filter(item => hosts.has(item.name)).map(item => <div className="toolbar-placement-row" key={item.name}>
<strong>{item.name}</strong><label>Dock <select disabled={busy} value={item.area} onChange={event => {
const area = event.target.value as Area;
setDraft(previous => previous!.map(entry => entry.name === item.name ? { ...entry, area } : entry));
}}>{areas.map(area => <option key={area}>{area}</option>)}</select></label>
<button disabled={busy} aria-label={`Move ${item.name} earlier`} onClick={() => move(item.name, -1)}>Earlier</button>
<button disabled={busy} aria-label={`Move ${item.name} later`} onClick={() => move(item.name, 1)}>Later</button>
<label><input type="checkbox" disabled={busy} checked={item.breakBefore} onChange={event => {
const breakBefore = event.target.checked;
setDraft(previous => previous!.map(entry => entry.name === item.name ? { ...entry, breakBefore } : entry));
}} />New row / column</label>
</div>)}
<button disabled={busy} onClick={() => void apply()}>Apply placement</button>
<button disabled={busy} onClick={cancelDraft}>Cancel</button>
</div>}
</div>
{areas.map(area => <div key={area} className="toolbar-dock" data-toolbar-area={area} aria-label={`${area} toolbar dock`} />)}
<div className="toolbar-content">{children}</div>
</div></Hosts.Provider>;
}