feat(web): panel scroll contract, layout probe and functional suite
- lock the three-column height chain on workbench/PartDesign pages so each side panel scrolls independently and the centre stage keeps its size - dock module task panels above the layout with their own scrollbar instead of letting them push the stage out of the viewport - add tools/layout-probe.mjs (page scroll, aside bounds, pane scrolling, stage stability) and CLI mode for tools/static-host.mjs with relative --root support - add the P0-P4 browser functional suite, manual scenarios and capture tooling; document it under docs/current/web-functional-suite Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -14,7 +14,7 @@
|
||||
},
|
||||
{
|
||||
"type": "seed",
|
||||
"file": "/home/mes123456/FreeCADWasmDev/working/FreeCAD/web/tools/line-course/checkpoints/E03.FCStd",
|
||||
"file": "/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD/web/tools/line-course/checkpoints/E03.FCStd",
|
||||
"name": "manual-assembly-source.FCStd"
|
||||
},
|
||||
{
|
||||
|
||||
153
web/src/document-tree.tsx
Normal file
153
web/src/document-tree.tsx
Normal file
@@ -0,0 +1,153 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Tree, type NodeApi, type NodeRendererProps, type RowRendererProps } from "react-arborist";
|
||||
|
||||
// Desktop FreeCAD's TreeWidget is a three-column QTreeWidget
|
||||
// (src/Gui/Tree.cpp: `headerItem()->setText(0, "Labels & Attributes")`,
|
||||
// "Description", "Internal name") whose first column carries a visibility
|
||||
// icon (TreeParams::getVisibilityIcon default true) preceded by the object
|
||||
// icon, with error / touched / external overlays composited on top. This
|
||||
// component reproduces that row model so every workbench can share one tree
|
||||
// instead of its own ad-hoc list.
|
||||
|
||||
export interface DocumentTreeNode {
|
||||
id: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
internalName: string;
|
||||
type: string;
|
||||
icon?: string;
|
||||
visible?: boolean;
|
||||
toggleable?: boolean;
|
||||
error?: boolean;
|
||||
touched?: boolean;
|
||||
external?: boolean;
|
||||
children?: DocumentTreeNode[];
|
||||
}
|
||||
|
||||
const ROW_HEIGHT = 24;
|
||||
|
||||
function Row(
|
||||
{ node, data, onSelectObject, onToggleVisibility, busy }: {
|
||||
node: NodeApi<DocumentTreeNode>;
|
||||
data: DocumentTreeNode;
|
||||
onSelectObject: (id: string) => void;
|
||||
onToggleVisibility?: (id: string, visible: boolean) => void;
|
||||
busy: boolean;
|
||||
},
|
||||
) {
|
||||
const arrow = node.isLeaf ? null : (
|
||||
<button type="button" className="fc-tree-arrow" aria-label={node.isOpen ? "Collapse" : "Expand"}
|
||||
onClick={event => { event.stopPropagation(); node.isOpen ? node.close() : node.open(); }}>
|
||||
{node.isOpen ? "▾" : "▸"}
|
||||
</button>
|
||||
);
|
||||
return <>
|
||||
{arrow}
|
||||
<div className="fc-tree-col fc-tree-col-label">
|
||||
{data.toggleable !== false
|
||||
? <input type="checkbox" className="fc-tree-visibility" aria-label={`Visible ${data.label}`}
|
||||
checked={data.visible !== false} disabled={busy}
|
||||
onClick={event => event.stopPropagation()}
|
||||
onChange={event => onToggleVisibility?.(data.id, event.target.checked)} />
|
||||
: <span className="fc-tree-visibility-spacer" aria-hidden="true" />}
|
||||
{data.icon
|
||||
? <img className="fc-tree-icon" src={data.icon} alt="" aria-hidden="true" />
|
||||
: <span className="fc-tree-icon" aria-hidden="true" />}
|
||||
{data.error ? <img className="fc-tree-overlay" src="/icons/tree/overlay_error.svg" alt="" aria-hidden="true" />
|
||||
: data.touched ? <img className="fc-tree-overlay" src="/icons/tree/overlay_recompute.svg" alt="" aria-hidden="true" /> : null}
|
||||
<span className="fc-tree-text">{data.label}</span>
|
||||
{data.external ? <img className="fc-tree-overlay" src="/icons/tree/LinkOverlay.svg" alt="" aria-hidden="true" /> : null}
|
||||
</div>
|
||||
<div className="fc-tree-col fc-tree-col-description">{data.description ?? ""}</div>
|
||||
<div className="fc-tree-col fc-tree-col-internal">{data.internalName}</div>
|
||||
</>;
|
||||
}
|
||||
|
||||
export function DocumentTree({ nodes, selected, onSelect, onToggleVisibility, busy = false, label }: {
|
||||
nodes: DocumentTreeNode[];
|
||||
selected: string;
|
||||
onSelect: (id: string) => void;
|
||||
onToggleVisibility?: (id: string, visible: boolean) => void;
|
||||
busy?: boolean;
|
||||
label: string;
|
||||
}) {
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
const [width, setWidth] = useState(240);
|
||||
useEffect(() => {
|
||||
const element = host.current;
|
||||
if (!element) return;
|
||||
const measure = () => setWidth(Math.max(120, element.clientWidth));
|
||||
measure();
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(element);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
const flat = useMemo(() => {
|
||||
let count = 0;
|
||||
const walk = (rows: DocumentTreeNode[]) => { for (const row of rows) { count++; if (row.children?.length) walk(row.children); } };
|
||||
walk(nodes);
|
||||
return count;
|
||||
}, [nodes]);
|
||||
|
||||
// react-window virtualizes by a fixed pixel height. The tree pane scrolls as a
|
||||
// whole, so the viewport is sized to the content and every row stays mounted;
|
||||
// otherwise row counts and off-screen selections would differ from desktop.
|
||||
const height = Math.max(ROW_HEIGHT * Math.max(flat, 1) + 2, 40);
|
||||
|
||||
// react-arborist treats `renderRow` / `children` as component types. A new
|
||||
// function identity on every render therefore remounts every row, which drops
|
||||
// DOM focus to <body> while the tree still believes that row is focused; the
|
||||
// next re-render (e.g. a debounced property commit) then pulls focus into the
|
||||
// row and steals it from the field being typed in. Keep both renderers stable
|
||||
// and route the live callbacks through a ref instead of new closures.
|
||||
const callbacks = useRef({ onSelect, onToggleVisibility, busy });
|
||||
callbacks.current = { onSelect, onToggleVisibility, busy };
|
||||
const renderRow = useCallback(({ node, attrs, innerRef, children }: RowRendererProps<DocumentTreeNode>) => (
|
||||
<div {...attrs} ref={innerRef} role="treeitem" aria-selected={node.isSelected ? "true" : "false"} data-design-object={node.data.id} onClick={event => { node.handleClick(event); }}>
|
||||
{children}
|
||||
</div>
|
||||
), []);
|
||||
const renderNode = useCallback(({ node }: NodeRendererProps<DocumentTreeNode>) => (
|
||||
<Row node={node} data={node.data} onSelectObject={id => callbacks.current.onSelect(id)}
|
||||
onToggleVisibility={(id, visible) => callbacks.current.onToggleVisibility?.(id, visible)} busy={callbacks.current.busy} />
|
||||
), []);
|
||||
|
||||
return <div ref={host} className="fc-tree" data-tree-rows={flat}>
|
||||
<style>{`.fc-tree{width:100%}.fc-tree-header,.fc-tree [role=treeitem]{display:grid;grid-template-columns:minmax(0,1.6fr) minmax(0,1fr) minmax(0,1fr);align-items:center;box-sizing:border-box;font-size:12px;line-height:${ROW_HEIGHT}px}
|
||||
.fc-tree-header{height:${ROW_HEIGHT}px;padding:0 4px;border-bottom:1px solid #3c4246;color:#a4b2b9;font-weight:600}
|
||||
.fc-tree [role=treeitem]{padding:0 4px;border-left:3px solid transparent;cursor:pointer;color:#fff;white-space:nowrap}
|
||||
.fc-tree [role=treeitem]:hover{background:#3a4348}
|
||||
.fc-tree [role=treeitem][aria-selected=true]{background:#29444b;border-left-color:#8ed4dc}
|
||||
.fc-tree-col{display:flex;align-items:center;gap:5px;min-width:0;overflow:hidden;padding-right:6px}
|
||||
.fc-tree-col-description,.fc-tree-col-internal{color:#9fb0ba}
|
||||
.fc-tree-text{overflow:hidden;text-overflow:ellipsis}
|
||||
.fc-tree-icon{width:16px;height:16px;flex:none;object-fit:contain}
|
||||
.fc-tree-overlay{width:10px;height:10px;flex:none}
|
||||
.fc-tree-visibility{margin:0;width:13px;height:13px;flex:none;accent-color:#8ed4dc}
|
||||
.fc-tree-visibility-spacer{display:inline-block;width:13px;flex:none}
|
||||
.fc-tree-arrow{all:unset;cursor:pointer;width:12px;position:absolute;transform:translateX(-12px);color:#b1b9bf}
|
||||
.fc-tree [role=treeitem]{position:relative}`}</style>
|
||||
<div className="fc-tree-header" role="row">
|
||||
<div>Labels & Attributes</div><div>Description</div><div>Internal name</div>
|
||||
</div>
|
||||
<Tree<DocumentTreeNode>
|
||||
data={nodes}
|
||||
aria-label={label}
|
||||
width={width}
|
||||
height={height}
|
||||
rowHeight={ROW_HEIGHT}
|
||||
indent={14}
|
||||
openByDefault
|
||||
disableDrag
|
||||
disableDrop
|
||||
disableEdit
|
||||
selection={selected || undefined}
|
||||
onSelect={rows => { const first = rows[0]; if (first) onSelect(first.id); }}
|
||||
onActivate={node => onSelect(node.id)}
|
||||
renderRow={renderRow}
|
||||
>
|
||||
{renderNode}
|
||||
</Tree>
|
||||
</div>;
|
||||
}
|
||||
30
web/src/export-service.ts
Normal file
30
web/src/export-service.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { downloadBytes, type AppServiceResult } from "./app-services.js";
|
||||
import { readExportFile, writeExportFile } from "./storage.js";
|
||||
import { ProjectSessionStore } from "./project-session.js";
|
||||
|
||||
const EXTENSIONS = new Set([".csg", ".scad", ".fcstd", ".step", ".stp", ".brep", ".brp", ".iges", ".igs", ".stl", ".gltf", ".glb", ".obj", ".ply", ".svg", ".dxf", ".csv"]);
|
||||
|
||||
export interface NativeByteResult { module: string; format: string; fileName: string; bytes: ArrayBuffer; }
|
||||
|
||||
function extension(fileName: string): string { const index = fileName.lastIndexOf("."); return index >= 0 ? fileName.slice(index).toLowerCase() : ""; }
|
||||
|
||||
export class ExportService {
|
||||
constructor(private readonly project?: ProjectSessionStore) {}
|
||||
|
||||
async downloadToLocal(fileName: string, mime = "application/octet-stream"): Promise<AppServiceResult<{ fileName: string; bytes: number }>> {
|
||||
const bytes = await readExportFile(fileName);
|
||||
return downloadBytes(fileName, bytes, mime);
|
||||
}
|
||||
|
||||
download(native: Partial<NativeByteResult>): AppServiceResult<{ fileName: string; bytes: number }> {
|
||||
const fileName = native.fileName ?? "FreeCAD-export";
|
||||
const bytes = native.bytes;
|
||||
const ext = extension(fileName);
|
||||
if (!bytes || !(bytes instanceof ArrayBuffer)) return { schema: "freecad-web-app-service-result/v1", service: "file.download", status: "error", error: { code: "native_bytes_unavailable", message: "Native Worker response did not include export bytes" } };
|
||||
if (!EXTENSIONS.has(ext)) return { schema: "freecad-web-app-service-result/v1", service: "file.download", status: "error", error: { code: "unsupported_extension", message: `Unsupported CAD export extension ${ext || "(none)"}` } };
|
||||
// Web FreeCAD works entirely inside OPFS; downloadBytes runs only through
|
||||
// download() below, which the UI calls when the user explicitly asks.
|
||||
void writeExportFile(fileName, bytes).then(() => this.project?.touchFile({ path: fileName, module: native.module ?? "", format: native.format ?? ext, updatedAt: new Date().toISOString() }));
|
||||
return { schema: "freecad-web-app-service-result/v1", service: "file.download", status: "ok", value: { fileName, bytes: bytes.byteLength } };
|
||||
}
|
||||
}
|
||||
@@ -162,6 +162,10 @@ export class ImportRenderBridge {
|
||||
private gizmoMeshId: string | null = null;
|
||||
private gizmoTargetBase: THREE.Matrix4 | null = null;
|
||||
private gizmoHandleBase: THREE.Matrix4 | null = null;
|
||||
// Placement editors preview a not-yet-committed transform by writing only the
|
||||
// mesh matrix. The base matrix is captured on the first preview call so the
|
||||
// kernel-republished mesh (identity today) is never assumed.
|
||||
private transformPreview: { key: string; object: THREE.Object3D; base: THREE.Matrix4 } | null = null;
|
||||
// A committed placement rebuilds the mesh, so the object captured at drag
|
||||
// start can be replaced mid-flight. Look the target up by document id at the
|
||||
// moment of use instead of trusting a cached reference.
|
||||
@@ -530,6 +534,47 @@ export class ImportRenderBridge {
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
// Placement editors call this while the user types: the mesh takes the world
|
||||
// delta between the committed placement (`from`) and the typed one (`to`)
|
||||
// without re-meshing the shape or involving the kernel. The kernel commit that
|
||||
// follows republishes the authoritative geometry and clears the preview.
|
||||
previewTransform(documentId: string, object: string, to: { position: number[]; axis?: number[]; angle?: number },
|
||||
from: { position: number[]; axis?: number[]; angle?: number }, meshId?: string): void {
|
||||
const entry = this.scenes.objects(documentId).find(item => item.id === (meshId ?? object));
|
||||
const target = entry?.object;
|
||||
if (!target) return;
|
||||
const key = `${documentId}:${meshId ?? object}`;
|
||||
if (!this.transformPreview || this.transformPreview.key !== key || this.transformPreview.object !== target)
|
||||
this.transformPreview = { key, object: target, base: target.matrix.clone() };
|
||||
const deltaPosition = new THREE.Vector3().fromArray(to.position).sub(new THREE.Vector3().fromArray(from.position));
|
||||
const deltaQuaternion = this.orientationFrom(to.axis, to.angle).multiply(this.orientationFrom(from.axis, from.angle).invert());
|
||||
const delta = new THREE.Matrix4().compose(deltaPosition, deltaQuaternion, new THREE.Vector3(1, 1, 1));
|
||||
target.matrix.copy(delta).multiply(this.transformPreview.base);
|
||||
target.matrixAutoUpdate = false;
|
||||
target.matrixWorldNeedsUpdate = true;
|
||||
target.updateMatrixWorld(true);
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
clearTransformPreview(): void {
|
||||
const preview = this.transformPreview;
|
||||
if (!preview) return;
|
||||
preview.object.matrix.copy(preview.base);
|
||||
preview.object.matrixAutoUpdate = true;
|
||||
preview.object.matrixWorldNeedsUpdate = true;
|
||||
this.transformPreview = null;
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
private orientationFrom(axis?: number[], angle?: number): THREE.Quaternion {
|
||||
const orientation = new THREE.Quaternion();
|
||||
if (!axis || axis.length !== 3 || !Number.isFinite(angle)) return orientation;
|
||||
const length = Math.hypot(axis[0], axis[1], axis[2]);
|
||||
if (length > 0) orientation.setFromAxisAngle(new THREE.Vector3(axis[0] / length, axis[1] / length, axis[2] / length),
|
||||
THREE.MathUtils.degToRad(angle ?? 0));
|
||||
return orientation;
|
||||
}
|
||||
|
||||
// SolidWorks-style selection display: the triad and focus box come from the
|
||||
// shared SelectionDecoration; this wrapper only feeds it the camera frame.
|
||||
private updateSelectionAxes(): void {
|
||||
|
||||
@@ -332,6 +332,7 @@ export function getWebModuleWorkerForCommand(module: string, command: string): s
|
||||
case "TechDraw:techdraw.pythonApi": return "techdraw-python.worker.ts";
|
||||
case "TechDraw:techdraw.pythonFamilyBatch": return "techdraw-python.worker.ts";
|
||||
case "TechDraw:techdraw.pythonMethod": return "techdraw-python.worker.ts";
|
||||
case "TemplatePyMod:templatepymod.inspectSourceInventory": return "templatepymod.worker.ts";
|
||||
case "TemplatePyMod:templatepymod.pythonApi": return "templatepymod-python.worker.ts";
|
||||
case "Web:web.dockOverlay": return "web-dock-overlay.worker.ts";
|
||||
case "Web:web.saveReopenBoundary": return "web-persistence.worker.ts";
|
||||
|
||||
212
web/src/panel-scroll.css
Normal file
212
web/src/panel-scroll.css
Normal file
@@ -0,0 +1,212 @@
|
||||
/* Shared three-column scroll contract for the standalone workbench and
|
||||
PartDesign pages. Each page adds a root class (stage-lock / stage-lock-pd) to
|
||||
<html> from its entry module; the rules below then lock the document to the
|
||||
viewport so every side panel owns its own scrollbar and the centre stage
|
||||
keeps its size. Narrow widths are deliberately excluded: below the
|
||||
three-column breakpoints the page falls back to normal document scrolling.
|
||||
|
||||
The same .pane-scroll contract already drives /project.html (see
|
||||
project-shell.tsx), so panels look and behave identically everywhere. */
|
||||
|
||||
/* --- Workbench page (/workbench.html) — three columns from 721px up ------- */
|
||||
@media (min-width: 721px) {
|
||||
html.stage-lock,
|
||||
html.stage-lock body {
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
html.stage-lock body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
html.stage-lock body > #app,
|
||||
html.stage-lock body > .fc-workbench-embed {
|
||||
flex: 1 1 0%;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
/* The shell mounts its three-column layout inside a root div plus a
|
||||
display:contents wrapper, so both boxes must pass the height down. */
|
||||
html.stage-lock #app > div {
|
||||
flex: 1 1 0%;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
/* flex-basis:0 keeps the grid height independent of panel content, so
|
||||
injecting or removing panel rows never nudges the centre stage. */
|
||||
html.stage-lock .layout {
|
||||
flex: 1 1 0%;
|
||||
height: auto;
|
||||
min-height: 0;
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
}
|
||||
html.stage-lock .layout > aside {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
html.stage-lock .layout > aside > h2,
|
||||
html.stage-lock .layout > aside > .heading {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
html.stage-lock .layout > aside > .pane-scroll {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
/* Module task panels (Robot joints, Assembly, Draft …) are docked above the
|
||||
layout. Cap them so their own scrollbar absorbs tall content instead of
|
||||
pushing the three-column layout past the viewport. */
|
||||
html.stage-lock .module-task-dock {
|
||||
flex: 0 1 auto;
|
||||
min-height: 0;
|
||||
max-height: 42dvh;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
html.stage-lock .layout > main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
/* Centre stage: keep its size, scroll its own content if a task panel is tall. */
|
||||
html.stage-lock .layout > main.stage {
|
||||
overflow: auto;
|
||||
}
|
||||
html.stage-lock .layout.dock-workbench {
|
||||
grid-template-rows: auto minmax(0, 1fr) auto;
|
||||
}
|
||||
html.stage-lock .layout.dock-workbench > [data-dock-side="left"],
|
||||
html.stage-lock .layout.dock-workbench > [data-dock-side="right"] {
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- PartDesign page (/partdesign.html) — three columns from 1051px up ---- */
|
||||
@media (min-width: 1051px) {
|
||||
html.stage-lock-pd,
|
||||
html.stage-lock-pd body {
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
html.stage-lock-pd body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
html.stage-lock-pd body > #app {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
html.stage-lock-pd .design-app {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
html.stage-lock-pd .design-layout {
|
||||
flex: 1 1 auto;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
}
|
||||
html.stage-lock-pd .design-layout > aside {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
html.stage-lock-pd .design-layout > aside > h2 {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
html.stage-lock-pd .design-layout > aside > .pane-scroll {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
html.stage-lock-pd .design-layout > main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- Embeds --------------------------------------------------------------- */
|
||||
/* Embedded workbenches live inside an already-locked host document, so the
|
||||
embed itself must clip and let the inner .pane-scroll elements scroll. */
|
||||
.fc-workbench-embed {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
.fc-workbench-embed > .module-task-dock {
|
||||
flex: 0 1 auto;
|
||||
min-height: 0;
|
||||
max-height: 42dvh;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
.fc-workbench-embed > .layout {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
}
|
||||
.fc-workbench-embed > .layout > aside {
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.fc-workbench-embed > .layout > aside > .pane-scroll {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
/* PartDesign embedded in the workbench stage: give the nested three-column
|
||||
layout a bounded height so its panels scroll instead of the whole stage. */
|
||||
.stage .partdesign-stage {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: min(760px, calc(100dvh - 220px));
|
||||
min-height: 520px;
|
||||
}
|
||||
.stage .partdesign-stage .design-app {
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.stage .partdesign-stage .design-layout {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
}
|
||||
.stage .partdesign-stage .design-layout > aside {
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.stage .partdesign-stage .design-layout > aside > .pane-scroll {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
}
|
||||
1305
web/src/partdesign-workspace-component.tsx
Normal file
1305
web/src/partdesign-workspace-component.tsx
Normal file
File diff suppressed because it is too large
Load Diff
4
web/src/partdesign-workspace.css
Normal file
4
web/src/partdesign-workspace.css
Normal file
@@ -0,0 +1,4 @@
|
||||
:root{font-family:system-ui,sans-serif;color:#e7ebed;background:#171a1d;color-scheme:dark;font-synthesis:none;letter-spacing:0}*{box-sizing:border-box}body{margin:0}button,input,select{font:inherit}button,a,input,select{outline-offset:3px}button{cursor:pointer}button:disabled{opacity:.4;cursor:default}header{height:58px;display:flex;align-items:center;gap:14px;padding:0 18px;border-bottom:1px solid #3c4246;background:#212629}header a{display:grid;place-items:center;color:#e7ebed;width:32px;height:32px}header strong{color:#8ed4dc;font-size:18px}h1{font-size:20px;font-weight:600;margin:0}.active-name{margin-left:auto;font-size:13px;color:#b1b9bf;overflow-wrap:anywhere}.toolbar{display:flex;flex-wrap:wrap;align-items:center;gap:5px;padding:7px 16px;border-bottom:1px solid #3c4246}.icon-button{display:inline-grid;place-items:center;width:34px;height:34px;flex:none;padding:0;border:1px solid #4a5156;border-radius:4px;background:#272d31;color:#e7ebed;position:relative}.icon-button:hover{background:#384348}.icon-button[aria-pressed=true]{border-color:#8ed4dc;background:#294950}.icon-button input[type=file]{position:absolute;inset:0;width:100%;opacity:0;cursor:pointer}.separator{height:22px;width:1px;margin:0 6px;background:#4a5156}.design-layout{display:grid;grid-template-columns:220px minmax(0,1fr)290px;min-height:0;height:100%}.design-layout>*{min-width:0}.tree-pane,.property-pane{padding:0;display:flex;flex-direction:column;min-height:0;overflow:hidden;background:#202528}.tree-pane>.pane-scroll,.property-pane>.pane-scroll{flex:1 1 auto;min-height:0;overflow-y:auto;overflow-x:hidden;padding:16px}.design-layout>main{display:flex;flex-direction:column;min-height:0;overflow:hidden}.tree-pane{border-right:1px solid #3c4246}.property-pane{border-left:1px solid #3c4246}h2{font-size:15px;line-height:1.4;margin:5px 0 12px;font-weight:600;overflow-wrap:anywhere}.tree-pane h2:not(:first-child){margin-top:26px}select,input:not([type=checkbox],[type=file]){width:100%;min-width:0;border:1px solid #4a5156;border-radius:4px;background:#171b1e;color:#e7ebed;padding:7px 8px}label{display:grid;gap:6px;margin:12px 0;font-size:13px}fieldset{min-width:0;border:0;border-top:1px solid #3c4246;padding:14px 0 0;margin:18px 0 0}legend{font-size:14px;padding:0 8px 0 0}.segmented{display:flex;gap:4px}.coordinates{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:7px}.actions{display:flex;flex-wrap:wrap;gap:6px;margin-top:14px}.actions button,.text-command{display:flex;align-items:center;justify-content:center;gap:7px;font-size:13px;border:1px solid #4a5156;border-radius:4px;padding:8px;background:#2b353a;color:#e7ebed;min-height:35px}.text-command{margin:10px 0;width:100%}.check{display:flex;align-items:center;gap:8px}.object-summary{display:grid;grid-template-columns:54px minmax(0,1fr);gap:8px;font-size:12px;margin:0 0 14px}.object-summary dt{color:#b1b9bf}.object-summary dd{margin:0;overflow-wrap:anywhere}.design-viewport{flex:1 1 auto;height:auto;min-height:0;max-height:none;width:100%}.design-viewport canvas{display:block;max-width:100%;touch-action:none}.document-status{padding:12px 16px;min-height:46px;font-size:13px;color:#a9cec1;overflow-wrap:anywhere;border-top:1px solid #3c4246}.document-status[data-error=true]{color:#f4aaaa}ul[role=tree]{list-style:none;margin:0;padding:0}li[role=treeitem]{display:flex;align-items:center;gap:8px;min-height:44px;padding:7px;border-left:3px solid transparent;cursor:pointer;font-size:13px}li[role=treeitem][aria-selected=true]{background:#29444b;border-left-color:#8ed4dc}li[role=treeitem] input,li[role=treeitem] svg{flex:none}li[role=treeitem] span{min-width:0;overflow-wrap:anywhere}li[role=treeitem] small{display:block;color:#a4b2b9;font-size:11px;margin-top:3px}li.feature-node{padding-left:20px}@media(max-width:1050px){.design-layout{grid-template-columns:190px minmax(0,1fr);height:auto;min-height:calc(100vh - 107px)}.property-pane{grid-column:1/-1;border-left:0;border-top:1px solid #3c4246;max-height:45vh}.property-pane>.pane-scroll{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0 22px}.property-pane>.pane-scroll>.object-summary{grid-column:1/-1}.design-viewport{height:520px;min-height:320px;flex:none}}@media(max-width:600px){header{gap:8px;padding:0 12px}header strong{font-size:15px}h1{font-size:18px}.active-name{font-size:11px}.toolbar{padding:7px 10px}.separator{margin:0 3px}.design-layout{grid-template-columns:minmax(0,1fr)}.tree-pane{border-right:0;border-bottom:1px solid #3c4246}.property-pane{grid-column:auto}.property-pane>.pane-scroll{display:block}.design-viewport{height:360px;min-height:300px}.tree-pane h2:not(:first-child){margin-top:16px}}
|
||||
:root .edge-selection{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0 8px;max-height:180px;overflow:auto;margin-top:10px}.edge-selection .check{margin:4px 0;min-height:24px}
|
||||
:root .toolbar .export-format{width:90px;height:34px;flex:none;padding:4px}
|
||||
:root .segmented{flex-wrap:wrap}
|
||||
9
web/src/partdesign-workspace.tsx
Normal file
9
web/src/partdesign-workspace.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import React from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { PartDesignWorkspace } from "./partdesign-workspace-component.js";
|
||||
import "./panel-scroll.css";
|
||||
|
||||
// Lock the page to the viewport so the tree and property panes scroll on their
|
||||
// own and the 3D viewport keeps its size (see panel-scroll.css).
|
||||
document.documentElement.classList.add("stage-lock-pd");
|
||||
createRoot(document.querySelector<HTMLDivElement>("#app")!).render(<PartDesignWorkspace />);
|
||||
@@ -23,7 +23,7 @@ import type { MeasureSelection } from "./measure-document-adapter.js";
|
||||
import { SurfaceFillingTask } from "./surface-filling-task.js";
|
||||
import { SurfaceGeomFillTask } from "./surface-geomfill-task.js";
|
||||
import { SpreadsheetCsvPanel } from "./spreadsheet-csv-panel.js";
|
||||
import { SpreadsheetSheetEditor, type SheetCell, type SheetStructure, sheetColumn, sheetCoordinate } from "./spreadsheet-sheet-editor.js";
|
||||
import { type SheetCell, type SheetStructure, sheetColumn, sheetCoordinate } from "./spreadsheet-sheet-editor.js";
|
||||
import { PersistentToolbarWorkspace, ToolbarGroup } from "./persistent-toolbar-workspace.js";
|
||||
import { StartLaunchPanel } from "./start-launch-panel.js";
|
||||
import { startParameters } from "./start-preferences.js";
|
||||
@@ -68,9 +68,9 @@ import { installUiAccessibility } from "./ui-accessibility.js";
|
||||
import type { FacadeResponse } from "./facade-envelope.js";
|
||||
import { documentSessionReducer } from "./document-session.js";
|
||||
import { PART_DOCUMENT_COMMAND, PART_DOCUMENT_SCHEMA, PART_PRIMITIVE_FIELDS, documentObjectMesh, type PartPrimitive, type PartBoolean, type PartDocumentAction, type PartDocumentPayload, type PartDocumentResult } from "./part-document-facade.js";
|
||||
import { isOpfsSupported, listDocumentFiles, listExportFiles, readDocumentFile, readExportFile, writeDocumentFile } from "./storage.js";
|
||||
import { isOpfsSupported, listDocumentFiles, listExportFiles, readDocumentFile, readExportFile, writeDocumentFile, writeExportFile } from "./storage.js";
|
||||
import { ExportService } from "./export-service.js";
|
||||
import { DeltaReferencePanel, LineReferencePanel } from "./delta-reference-panel.js";
|
||||
import { Abb120ReferencePanel, DeltaReferencePanel, LineReferencePanel } from "./delta-reference-panel.js";
|
||||
import type { MeshPayload } from "./worker-protocol.js";
|
||||
import { ImportRenderBridge } from "./import-render-bridge.js";
|
||||
import { registerTestMdiHost } from "./test-desktop-adapter.js";
|
||||
@@ -89,10 +89,12 @@ import { formatLength, formatVolume, unitInfo } from "./shell/units.js";
|
||||
import { ShortcutEditor, ShortcutManager } from "./shell/shortcut-manager.js";
|
||||
import { BottomDock } from "./shell/bottom-dock.js";
|
||||
import { WorkbenchFrame, isExternalWorkbench } from "./shell/workbench-frame.js";
|
||||
import { SpreadsheetPanel, SpreadsheetEditorPanel as SpreadsheetSheetEditor } from "./workbenches/Spreadsheet/index.js";
|
||||
import { CommandPalette } from "./shell/command-palette.js";
|
||||
import { DesktopCommandDispatcher } from "./desktop-command-dispatcher.js";
|
||||
import type { WorkbenchCommandRecord } from "./workbench-command-facade.js";
|
||||
import { DocumentTree, type DocumentTreeNode } from "./document-tree.js";
|
||||
import { useDebouncedCommit } from "./use-debounced-commit.js";
|
||||
import { PARTDESIGN_DOCUMENT_COMMAND, PARTDESIGN_DOCUMENT_SCHEMA, type DesignAction, type DesignPayload, type DesignResult } from "./partdesign-document-facade.js";
|
||||
|
||||
const css = `:root{color-scheme:dark;font-family:Inter,system-ui,sans-serif;background:#10161d;color:#e7edf3}*{box-sizing:border-box}html{overflow-x:hidden}body{margin:0;min-width:320px;overflow-x:hidden}.top{align-items:center;background:#17212b;border-bottom:1px solid #2c3b48;display:flex;gap:14px;padding:14px 20px}.brand{background:#3b9db0;border-radius:5px;color:#071219;font-weight:800;padding:7px}.title{margin-left:auto}.layout{display:grid;grid-template-columns:260px minmax(0,1fr) 300px;min-height:calc(100vh - 56px)}aside{background:#17212b;padding:18px;overflow:auto}aside:first-child{border-right:1px solid #2c3b48}aside:last-child{border-left:1px solid #2c3b48}.stage{background:#0d1319;padding:24px}.viewport{background:#0d1319;border:1px solid #334854;height:330px;margin:12px 0}.viewport canvas{display:block;height:100%;width:100%}.tab,.action{background:#1d2a35;border:1px solid #435464;border-radius:5px;color:#e7edf3;cursor:pointer;display:block;font:inherit;margin:7px 0;padding:9px 11px;text-align:left;width:100%}.tab.active{background:#264b56;border-color:#66c7d5}.action:hover{border-color:#66b7c8}.action:disabled{opacity:.45}.status{color:#9cb6c2;line-height:1.5}.status.ok{color:#9ce0bd}.status.error{color:#ff9e9e}.stat{border-bottom:1px solid #2c3b48;padding:10px 0}.stat small{color:#8ea2ae;display:block;margin-top:4px}.result{font:12px ui-monospace,monospace;line-height:1.5;max-height:60vh;overflow:auto;white-space:pre-wrap;word-break:break-word}`;
|
||||
@@ -117,8 +119,13 @@ function App() {
|
||||
const navigationContext = useMemo(() => readNavigationContext(), []);
|
||||
const initialDocumentId = navigationContext.documentId ?? "project-document-1";
|
||||
const requestedWorkbench = new URLSearchParams(window.location.search).get("workbench");
|
||||
const initialWorkbench = ["Part", "Sketcher", "PartDesign", "Spreadsheet", "Surface", "Assembly", "Draft", "Architecture", "TechDraw", "CAM"].includes(requestedWorkbench ?? "")
|
||||
? requestedWorkbench as "Part" | "Sketcher" | "PartDesign" | "Spreadsheet" | "Surface" | "Assembly" | "Draft" | "Architecture" | "TechDraw" | "CAM" : undefined;
|
||||
// External workbenches mount in-process through <WorkbenchShell> by default.
|
||||
// ?nativeWorkbench=0 keeps the legacy /workbench.html iframe as a fallback.
|
||||
const nativeWorkbench = new URLSearchParams(window.location.search).get("nativeWorkbench") !== "0";
|
||||
// "Architecture" is the legacy start-page label; the module id is BIM.
|
||||
const requestedWorkbenchId = requestedWorkbench === "Architecture" ? "BIM" : requestedWorkbench;
|
||||
const initialWorkbench = ["Part", "Sketcher", "PartDesign", "Spreadsheet", "Surface", "Assembly", "Draft", "BIM", "TechDraw", "CAM", "Plot", "Show", "Web"].includes(requestedWorkbenchId ?? "")
|
||||
? requestedWorkbenchId as "Part" | "Sketcher" | "PartDesign" | "Spreadsheet" | "Surface" | "Assembly" | "Draft" | "BIM" | "TechDraw" | "CAM" | "Plot" | "Show" | "Web" : undefined;
|
||||
const store = useMemo(() => { const value = new ProjectSessionStore(); value.open(initialDocumentId, initialDocumentId); value.open("project-document-2", "Project Document 2"); value.switchTo(initialDocumentId); return value; }, [initialDocumentId]);
|
||||
const checkpoint = useMemo(() => new ProjectCheckpointStore("freecad-web-project-ui-checkpoint"), []);
|
||||
const recovery = useMemo(() => new RecoveryController(), []);
|
||||
@@ -230,6 +237,7 @@ function App() {
|
||||
const [exportFormat, setExportFormat] = useState("stl");
|
||||
const [referenceOpen, setReferenceOpen] = useState(false);
|
||||
const [lineReferenceOpen, setLineReferenceOpen] = useState(false);
|
||||
const [abbReferenceOpen, setAbbReferenceOpen] = useState(false);
|
||||
// SolidWorks-style direct manipulation: picking an object arms the translate
|
||||
// controller together with the local triad and selection focus. The toolbar
|
||||
// still lets the user switch to rotate or turn the handles off entirely.
|
||||
@@ -296,12 +304,16 @@ function App() {
|
||||
const designDocuments = useRef(new Set<string>());
|
||||
const [partSnapshots, setPartSnapshots] = useState<Record<string, PartDocumentResult>>({});
|
||||
const [designSnapshots, setDesignSnapshots] = useState<Record<string, DesignResult>>({});
|
||||
const [workbenches, setWorkbenches] = useState<Record<string, "Part" | "Sketcher" | "PartDesign" | "Spreadsheet" | "Surface" | "Assembly" | "Draft" | "Architecture" | "TechDraw" | "CAM">>(() => initialWorkbench ? { [initialDocumentId]: initialWorkbench } : {});
|
||||
const [workbenches, setWorkbenches] = useState<Record<string, "Part" | "Sketcher" | "PartDesign" | "Spreadsheet" | "Surface" | "Assembly" | "Draft" | "BIM" | "TechDraw" | "CAM" | "Plot" | "Show" | "Web">>(() => initialWorkbench ? { [initialDocumentId]: initialWorkbench } : {});
|
||||
const workbench = workbenches[active] ?? "Part";
|
||||
useEffect(() => { if (status) setReportLog(previous => previous[0] === status ? previous : [status, ...previous].slice(0, 50)); }, [status]);
|
||||
useEffect(() => {
|
||||
const palette = (event: KeyboardEvent) => {
|
||||
if ((event.ctrlKey || event.metaKey) && event.shiftKey && event.key.toLowerCase() === "p") {
|
||||
// Manual chapter 15 documents Ctrl+K; Ctrl+Shift+P is the menu-labelled
|
||||
// alias. Both open the same palette.
|
||||
const accel = (event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "k" && !event.shiftKey && !event.altKey;
|
||||
const alias = (event.ctrlKey || event.metaKey) && event.shiftKey && event.key.toLowerCase() === "p";
|
||||
if (accel || alias) {
|
||||
event.preventDefault(); setPaletteOpen(true);
|
||||
}
|
||||
};
|
||||
@@ -352,6 +364,12 @@ function App() {
|
||||
useEffect(() => { setImportCommand(null); setImportFile(null); setReplaceImport(false); }, [active]);
|
||||
const [treeWidth, setTreeWidth] = useState(240);
|
||||
const [propertyWidth, setPropertyWidth] = useState(300);
|
||||
// Typing in a property field commits ~250 ms after the last keystroke so the
|
||||
// 3D view follows along, instead of waiting for blur like desktop FreeCAD.
|
||||
const propertyCommit = useDebouncedCommit();
|
||||
const propertyCommitSeq = useRef(0);
|
||||
// Placement editors coalesce live previews to one matrix write per frame.
|
||||
const placementPreviewFrame = useRef(0);
|
||||
const [propertyColumnWidth, setPropertyColumnWidth] = useState<number | null>(() => {
|
||||
try {
|
||||
const value = Number(window.localStorage.getItem("freecad.propertyEditor.firstColumnWidth"));
|
||||
@@ -388,9 +406,10 @@ function App() {
|
||||
const objects = Object.values(currentDocument?.objects ?? {});
|
||||
const treeNodes = useMemo<DocumentTreeNode[]>(() => objects.map(object => {
|
||||
const label = String(object.properties.Label ?? object.id);
|
||||
const iconSlug = object.type.startsWith("PartDesign::") ? `PartDesign_${object.type.replace("PartDesign::", "")}`
|
||||
: object.type === "Sketcher::SketchObject" ? "" : "Part_3D_object";
|
||||
const icon = object.type === "Sketcher::SketchObject" ? "/icons/part/Sketcher_NewSketch.svg" : `/icons/partdesign/${iconSlug}.svg`;
|
||||
// PartDesign icons live under icons/partdesign; the generic 3D-object icon
|
||||
// belongs to the Part icon set, which is where it actually ships.
|
||||
const icon = object.type.startsWith("PartDesign::") ? `/icons/partdesign/PartDesign_${object.type.replace("PartDesign::", "")}.svg`
|
||||
: object.type === "Sketcher::SketchObject" ? "/icons/part/Sketcher_NewSketch.svg" : "/icons/part/Part_3D_object.svg";
|
||||
return {
|
||||
id: object.id,
|
||||
label,
|
||||
@@ -935,21 +954,34 @@ function App() {
|
||||
window.parent.postMessage({ type: "freecad-project-ready" }, location.origin);
|
||||
return () => window.removeEventListener("message", receive);
|
||||
}, [active, importing, csvPanel, objects, workspaceTask, viewCommand]);
|
||||
const createOrEditBox = async (edit: boolean) => {
|
||||
const createOrEditBox = async (edit: boolean, options: { live?: boolean; dimensions?: [number, number, number] } = {}) => {
|
||||
if (!active || importing) return;
|
||||
setImporting(true);
|
||||
const dimensions = options.dimensions ?? boxDimensions;
|
||||
const token = options.live ? ++propertyCommitSeq.current : 0;
|
||||
if (token) {
|
||||
// Typing rarely changes the value it started from: a duplicate live commit
|
||||
// (blur right after the debounce fired) would cost a full re-mesh.
|
||||
const committed = selectedObject?.properties.dimensions;
|
||||
if (Array.isArray(committed) && committed.length === 3
|
||||
&& committed.every((value, index) => Number(value) === dimensions[index])) return;
|
||||
}
|
||||
if (!options.live) setImporting(true);
|
||||
try {
|
||||
if (!nativeDocuments.current.has(active)) await nativeRequest(active, "create");
|
||||
let name = edit ? String(selectedObject?.properties.NativeName ?? "") : "Box1";
|
||||
if (!edit) { let index = 1; while (currentDocument?.objects[`native:${name}`]) name = `Box${++index}`; }
|
||||
const result = await nativeRequest(active, "setBox", { object: name, dimensions: boxDimensions });
|
||||
const result = await nativeRequest(active, "setBox", { object: name, dimensions });
|
||||
// A newer keystroke already started its own commit: keep the fresher reply.
|
||||
if (token && token !== propertyCommitSeq.current) return;
|
||||
applyNativeDocument(active, result);
|
||||
setCommittedBoxDimensions([...boxDimensions]);
|
||||
setCommittedBoxDimensions([...dimensions]);
|
||||
setSelectedObjects(previous => ({ ...previous, [active]: `native:${name}` }));
|
||||
renderBridge.activateDocument(active); renderBridge.fitDocument();
|
||||
setStatus(`${name}: ${boxDimensions.join(" × ")}`);
|
||||
renderBridge.activateDocument(active);
|
||||
// Live commits must not reframe the camera on every keystroke.
|
||||
if (!token) renderBridge.fitDocument();
|
||||
setStatus(`${name}: ${dimensions.join(" × ")}`);
|
||||
} catch (error) { setStatus(String(error)); }
|
||||
finally { setImporting(false); }
|
||||
finally { if (!options.live) setImporting(false); }
|
||||
};
|
||||
const commitNativeLabel = async (labelValue?: string) => {
|
||||
if (!selectedObject?.properties.NativeName) return;
|
||||
@@ -970,21 +1002,55 @@ function App() {
|
||||
} catch (error) { setStatus(String(error)); }
|
||||
finally { setImporting(false); }
|
||||
};
|
||||
const createOrEditPrimitive = async (edit: boolean) => {
|
||||
const createOrEditPrimitive = async (edit: boolean, options: { live?: boolean; parameters?: Record<string, number> } = {}) => {
|
||||
if (!active || importing) return;
|
||||
const documentId = active;
|
||||
setImporting(true);
|
||||
const parameters = options.parameters ?? primitiveParameters;
|
||||
const token = options.live ? ++propertyCommitSeq.current : 0;
|
||||
if (token) {
|
||||
const committed = selectedObject?.properties.parameters as Record<string, unknown> | undefined;
|
||||
const fields = Object.keys(parameters);
|
||||
if (committed && fields.length === Object.keys(committed).length
|
||||
&& fields.every(field => Number(committed[field]) === parameters[field])) return;
|
||||
}
|
||||
if (!options.live) setImporting(true);
|
||||
try {
|
||||
if (!nativeDocuments.current.has(documentId)) await nativeRequest(documentId, "create");
|
||||
let name = edit ? String(selectedObject?.properties.NativeName ?? "") : `${primitive}1`;
|
||||
if (!edit) { let index = 1; while (currentDocument?.objects[`native:${name}`]) name = `${primitive}${++index}`; }
|
||||
const result = await nativeRequest(documentId, "setPrimitive", { object: name, primitive, parameters: primitiveParameters });
|
||||
const result = await nativeRequest(documentId, "setPrimitive", { object: name, primitive, parameters });
|
||||
// A newer keystroke already started its own commit: keep the fresher reply.
|
||||
if (token && token !== propertyCommitSeq.current) return;
|
||||
applyNativeDocument(documentId, result);
|
||||
setSelectedObjects(previous => ({ ...previous, [documentId]: `native:${name}` }));
|
||||
renderBridge.activateDocument(documentId); renderBridge.fitDocument();
|
||||
setStatus(`${name}: ${Object.entries(primitiveParameters).map(([key, value]) => `${key}=${value}`).join(", ")}`);
|
||||
renderBridge.activateDocument(documentId);
|
||||
if (!token) renderBridge.fitDocument();
|
||||
setStatus(`${name}: ${Object.entries(parameters).map(([key, value]) => `${key}=${value}`).join(", ")}`);
|
||||
} catch (error) { setStatus(String(error)); }
|
||||
finally { setImporting(false); }
|
||||
finally { if (!options.live) setImporting(false); }
|
||||
};
|
||||
// Committed placement of the selected object in the same shape the kernel
|
||||
// snapshot reports: primitives keep it on primitivePlacement, everything else
|
||||
// on rotation. Live previews diff the typed placement against this one.
|
||||
const selectedPlacement = () => {
|
||||
const rotation = selectedObject?.properties.rotation as { axis?: number[]; angle?: number } | undefined;
|
||||
const primitive = selectedObject?.properties.primitivePlacement as { position?: number[]; axis?: number[]; angle?: number } | undefined;
|
||||
const position = [primitive?.position, selectedObject?.properties.position].find(value => Array.isArray(value) && value.length === 3) as number[] | undefined;
|
||||
const axis = [rotation?.axis, primitive?.axis].find(value => Array.isArray(value) && value.length === 3) as number[] | undefined;
|
||||
const angle = typeof rotation?.angle === "number" ? rotation.angle : primitive?.angle;
|
||||
return { position: position ? [...position] : [0, 0, 0], axis: axis ? [...axis] : [0, 0, 1], angle: typeof angle === "number" ? angle : 0 };
|
||||
};
|
||||
const schedulePlacementPreview = (to: { position: number[]; axis?: number[]; angle?: number }) => {
|
||||
const object = String(selectedObject?.properties.NativeName ?? "");
|
||||
if (!active || !object || jtDocuments.current.has(active)) { renderBridge.clearTransformPreview(); return; }
|
||||
const from = selectedPlacement();
|
||||
window.cancelAnimationFrame(placementPreviewFrame.current);
|
||||
placementPreviewFrame.current = window.requestAnimationFrame(() => renderBridge.previewTransform(active, object, to, from));
|
||||
};
|
||||
const cancelPlacementPreview = () => {
|
||||
window.cancelAnimationFrame(placementPreviewFrame.current);
|
||||
placementPreviewFrame.current = 0;
|
||||
renderBridge.clearTransformPreview();
|
||||
};
|
||||
const editNative = async (action: PartDocumentAction, details: Partial<PartDocumentPayload> = {}) => {
|
||||
if (!active || importing) return;
|
||||
@@ -1311,8 +1377,9 @@ function App() {
|
||||
const document = store.currentDocumentId;
|
||||
if (!document) throw new Error(`${kind} launch created no active document`);
|
||||
if (window.parent === window) {
|
||||
setWorkbenches(previous => ({ ...previous, [document]: kind }));
|
||||
await startParameters(router, { LastModule: `${kind}Workbench` }, true);
|
||||
const launchedWorkbench = kind === "Architecture" ? "BIM" : kind;
|
||||
setWorkbenches(previous => ({ ...previous, [document]: launchedWorkbench }));
|
||||
await startParameters(router, { LastModule: `${launchedWorkbench}Workbench` }, true);
|
||||
setStartVisible(!preferences.closeStart);
|
||||
return true;
|
||||
}
|
||||
@@ -1486,7 +1553,22 @@ function App() {
|
||||
}
|
||||
setStartVisible(!preferences.closeStart);
|
||||
};
|
||||
const downloadFcstd = () => { if (!nativeBytes) return; const result = exporter.download({ module: "Part", format: "application/octet-stream", fileName: `${jtDocuments.current.has(active) ? "JtReader_" : ""}${nativeName(active)}.FCStd`, bytes: nativeBytes }); setStatus(result.status === "ok" ? "FCStd 已写入 OPFS" : result.error?.message || "FCStd OPFS write failed"); };
|
||||
// "下载 native FCStd" is the one explicit local download in the shell: the
|
||||
// OPFS copy is written first (the default contract), then the same bytes are
|
||||
// handed to the browser download. export/download() alone only writes OPFS.
|
||||
const downloadFcstd = async () => {
|
||||
if (!nativeBytes) return;
|
||||
const fileName = `${jtDocuments.current.has(active) ? "JtReader_" : ""}${nativeName(active)}.FCStd`;
|
||||
const written = exporter.download({ module: "Part", format: "application/octet-stream", fileName, bytes: nativeBytes });
|
||||
if (written.status !== "ok") { setStatus(written.error?.message || "FCStd OPFS write failed"); return; }
|
||||
try {
|
||||
await writeExportFile(fileName, nativeBytes);
|
||||
const result = await exporter.downloadToLocal(fileName);
|
||||
setStatus(result.status === "ok"
|
||||
? `已下载 ${fileName}(${result.value?.bytes ?? nativeBytes.byteLength} bytes),副本已写入 OPFS`
|
||||
: result.error?.message || "FCStd 本地下载失败");
|
||||
} catch (error) { setStatus(String(error)); }
|
||||
};
|
||||
const exportDependencyGraph = async () => {
|
||||
if (importing || !active || !nativeDocuments.current.has(active)) return;
|
||||
const documentId = nativeName(active);
|
||||
@@ -1681,6 +1763,7 @@ function App() {
|
||||
if (["tube", "tolerance", "primitives", "shape-from-mesh", "points-from-mesh", "edit-attachment"].includes(item.task)) void runRetainedPartCommand(item.command, { action: "read" });
|
||||
};
|
||||
const cancelWorkspaceTask = () => {
|
||||
cancelPlacementPreview();
|
||||
setPartTaskMode(undefined);
|
||||
if (workspaceTask === "measure-mass-properties") {
|
||||
void nativeRequest(active, "clearMassGeometry", {}).then(result => applyNativeDocument(active, result, true)).catch(error => setStatus(String(error)));
|
||||
@@ -1770,20 +1853,35 @@ function App() {
|
||||
(side === "tree" ? setTreeWidth : setPropertyWidth)(previous => event.key === "Home" ? 180 : event.key === "End" ? 420 : Math.max(180, Math.min(420, previous + (event.key === "ArrowRight" ? 20 : -20)))); }} />;
|
||||
return <div className="desktop-workspace"><style>{css}{partUiCss}{`
|
||||
.layout > *{min-width:0}.top{flex-wrap:wrap}.stage{min-width:0}.tab small{display:block}.tab,.action{overflow-wrap:anywhere}.desktop-status-bar{position:sticky;bottom:0;z-index:6;display:flex;align-items:center;min-height:22px;padding:0 8px;background:var(--fc-primary);border:0}.desktop-status-bar .status{flex:1;min-width:0;margin:0;padding:2px 0;line-height:1.35;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
@media(min-width:801px){
|
||||
.desktop-workspace{display:flex;flex-direction:column;height:100%;min-height:0;overflow:hidden}
|
||||
body:has(.desktop-workspace){display:flex;flex-direction:column;height:100vh;height:100dvh;overflow:hidden}
|
||||
body:has(.desktop-workspace)>:not(#app){flex:0 0 auto}
|
||||
body:has(.desktop-workspace)>#app{flex:1 1 auto;min-height:0;overflow:hidden}
|
||||
.desktop-workspace .toolbar-workspace{flex:1 1 auto;min-height:0}
|
||||
.desktop-workspace .toolbar-content{display:flex;flex-direction:column;min-height:0;overflow:hidden}
|
||||
.desktop-workspace .toolbar-content>.layout{flex:1 1 auto;min-height:0}
|
||||
.desktop-workspace .desktop-status-bar{position:static;flex:0 0 auto}
|
||||
.desktop-workspace .layout>aside{display:flex;flex-direction:column;min-height:0;overflow:hidden;padding:0}
|
||||
.desktop-workspace .layout>aside>.pane-scroll{flex:1 1 auto;min-height:0;overflow-y:auto;overflow-x:hidden;padding:0 18px 12px}
|
||||
.desktop-workspace .layout>main.stage{display:flex;flex-direction:column;min-height:0;overflow-y:auto;overflow-x:hidden}
|
||||
.desktop-workspace .layout>main.stage>*{flex:0 0 auto}
|
||||
.desktop-workspace .layout>main.stage>.viewport{flex:1 1 260px;min-height:220px;height:auto;max-height:none}
|
||||
}
|
||||
.viewport{position:relative;border:0;height:440px;max-height:65vh}
|
||||
.properties label{display:grid;gap:6px;margin:12px 0}.properties>label{grid-template-columns:minmax(72px,.72fr) minmax(0,1fr);align-items:center;border-bottom:1px solid var(--fc-border);padding:5px 0;margin:0}.properties>label:focus-within{background:var(--fc-accent);border-bottom-color:var(--fc-accent)}.properties>label>span{color:#b5b5b5}.properties input:not([type=checkbox]),.properties select,.saved-documents{box-sizing:border-box;width:100%;min-width:0;min-height:22px;padding:2px 4px;background:var(--fc-primary);color:var(--fc-text);border:1px solid var(--fc-border);border-radius:3px}.properties select{padding-right:18px;background:linear-gradient(to bottom,var(--fc-panel),var(--fc-primary))}.properties input:not([type=checkbox]):hover,.properties select:hover{border-color:var(--fc-border-hover)}.properties select:hover{background:var(--fc-accent-hover)}.properties input:not([type=checkbox]):focus,.properties select:focus{border-color:var(--fc-accent);outline:none}.properties input:not([type=checkbox]):disabled,.properties select:disabled,.saved-documents:disabled{background:var(--fc-menu);color:var(--fc-disabled);border-color:var(--fc-border)}.properties input[type=color]{height:32px;padding:3px}.properties>dl{position:relative;display:grid;grid-template-columns:var(--property-first-column,minmax(72px,.72fr)) minmax(0,1fr);margin:8px 0 12px;border-top:1px solid var(--fc-border)}.properties>dl dt,.properties>dl dd{margin:0;padding:5px 4px;border-right:1px solid var(--fc-border);border-bottom:1px solid var(--fc-border);overflow-wrap:anywhere}.properties>dl dt{color:#b5b5b5}.properties>dl dd{color:var(--fc-disabled)}.property-column-resizer{position:absolute;z-index:1;top:0;bottom:0;left:calc(var(--property-first-column,50%) - 3px);width:6px;cursor:col-resize;touch-action:none}.property-column-resizer:focus-visible{outline:1px solid var(--fc-accent);outline-offset:-1px}.properties>h2{font-size:14px;letter-spacing:.04em;text-transform:uppercase;border-bottom:1px solid var(--fc-border);padding-bottom:8px;margin:0 0 8px;background:linear-gradient(to bottom,var(--fc-panel),var(--fc-primary))}.properties .property-group-title{font-size:12px;line-height:1.3;font-weight:700;color:var(--fc-text);background:var(--fc-primary);border-bottom:1px solid var(--fc-border);margin:10px 0 0;padding:5px 6px}.status{overflow-wrap:anywhere}.position-fields{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px}.properties fieldset{min-width:0}.primitive-actions{flex-wrap:wrap}.task-box{border:1px solid var(--fc-border);margin:8px 0}.task-box>summary{cursor:pointer;background:var(--fc-panel);padding:7px 9px;border-bottom:1px solid var(--fc-border);color:#e7edf3}.task-box>summary:focus-visible{outline:1px solid var(--fc-accent);outline-offset:-1px}.task-box-content{max-height:48vh;overflow:auto;padding:8px}.task-dialog-actions{display:flex;justify-content:flex-end;gap:8px;border-top:1px solid var(--fc-border);padding-top:10px;margin-top:10px}.task-dialog-actions button{width:auto;margin:0}.task-dialog-actions .run{order:0}
|
||||
.properties label{display:grid;gap:6px;margin:12px 0}.properties>.pane-scroll>label{grid-template-columns:minmax(72px,.72fr) minmax(0,1fr);align-items:center;border-bottom:1px solid var(--fc-border);padding:5px 0;margin:0}.properties>.pane-scroll>label:focus-within{background:var(--fc-accent);border-bottom-color:var(--fc-accent)}.properties>.pane-scroll>label>span{color:#b5b5b5}.properties input:not([type=checkbox]),.properties select,.saved-documents{box-sizing:border-box;width:100%;min-width:0;min-height:22px;padding:2px 4px;background:var(--fc-primary);color:var(--fc-text);border:1px solid var(--fc-border);border-radius:3px}.properties select{padding-right:18px;background:linear-gradient(to bottom,var(--fc-panel),var(--fc-primary))}.properties input:not([type=checkbox]):hover,.properties select:hover{border-color:var(--fc-border-hover)}.properties select:hover{background:var(--fc-accent-hover)}.properties input:not([type=checkbox]):focus,.properties select:focus{border-color:var(--fc-accent);outline:none}.properties input:not([type=checkbox]):disabled,.properties select:disabled,.saved-documents:disabled{background:var(--fc-menu);color:var(--fc-disabled);border-color:var(--fc-border)}.properties input[type=color]{height:32px;padding:3px}.properties>.pane-scroll>dl{position:relative;display:grid;grid-template-columns:var(--property-first-column,minmax(72px,.72fr)) minmax(0,1fr);margin:8px 0 12px;border-top:1px solid var(--fc-border)}.properties>.pane-scroll>dl dt,.properties>.pane-scroll>dl dd{margin:0;padding:5px 4px;border-right:1px solid var(--fc-border);border-bottom:1px solid var(--fc-border);overflow-wrap:anywhere}.properties>.pane-scroll>dl dt{color:#b5b5b5}.properties>.pane-scroll>dl dd{color:var(--fc-disabled)}.property-column-resizer{position:absolute;z-index:1;top:0;bottom:0;left:calc(var(--property-first-column,50%) - 3px);width:6px;cursor:col-resize;touch-action:none}.property-column-resizer:focus-visible{outline:1px solid var(--fc-accent);outline-offset:-1px}.properties>h2{font-size:14px;letter-spacing:.04em;text-transform:uppercase;border-bottom:1px solid var(--fc-border);padding-bottom:8px;margin:0 0 8px;background:linear-gradient(to bottom,var(--fc-panel),var(--fc-primary))}.properties .property-group-title{font-size:12px;line-height:1.3;font-weight:700;color:var(--fc-text);background:var(--fc-primary);border-bottom:1px solid var(--fc-border);margin:10px 0 0;padding:5px 6px}.status{overflow-wrap:anywhere}.position-fields{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px}.properties fieldset{min-width:0}.primitive-actions{flex-wrap:wrap}.task-box{border:1px solid var(--fc-border);margin:8px 0}.task-box>summary{cursor:pointer;background:var(--fc-panel);padding:7px 9px;border-bottom:1px solid var(--fc-border);color:#e7edf3}.task-box>summary:focus-visible{outline:1px solid var(--fc-accent);outline-offset:-1px}.task-box-content{max-height:48vh;overflow:auto;padding:8px}.task-dialog-actions{display:flex;justify-content:flex-end;gap:8px;border-top:1px solid var(--fc-border);padding-top:10px;margin-top:10px}.task-dialog-actions button{width:auto;margin:0}.task-dialog-actions .run{order:0}
|
||||
.properties input[type=color]{width:32px;height:22px;min-height:22px;padding:3px;border:1px solid var(--fc-border);border-radius:3px;background:linear-gradient(to bottom,var(--fc-panel),var(--fc-primary));cursor:pointer}.properties input[type=color]:hover{border-color:var(--fc-border-hover)}.properties input[type=color]:focus-visible{outline:1px solid var(--fc-accent);outline-offset:1px}.properties input[type=color]:disabled{opacity:.45}.properties input[type=file]::file-selector-button{margin-right:6px;padding:3px 12px;border:1px solid var(--fc-border);border-radius:3px;background:linear-gradient(to bottom,var(--fc-panel),var(--fc-primary));color:var(--fc-text);font:inherit;cursor:pointer}.properties input[type=file]::file-selector-button:hover{background:var(--fc-accent-hover);border-color:var(--fc-border-hover)}.properties input[type=file]:focus-visible{outline:1px solid var(--fc-accent);outline-offset:1px}.properties input[type=file]:disabled{opacity:.45}
|
||||
.properties input::selection,.properties select::selection{background:var(--fc-border-hover);color:var(--fc-text)}
|
||||
.properties>label>.property-link-name{color:#20aa20}.properties>label>.property-expression{color:#0095ff}.properties>label>input.property-expression-value{color:#0095ff}.properties>label>input.property-expression-value:read-only{cursor:default}.properties>label>input.property-expression-value::-webkit-inner-spin-button,.properties>label>input.property-expression-value::-webkit-outer-spin-button{display:none}
|
||||
.properties>dl dt:nth-of-type(even),.properties>dl dd:nth-of-type(even){background:var(--fc-panel)}
|
||||
.properties>.pane-scroll>label>.property-link-name{color:#20aa20}.properties>.pane-scroll>label>.property-expression{color:#0095ff}.properties>.pane-scroll>label>input.property-expression-value{color:#0095ff}.properties>.pane-scroll>label>input.property-expression-value:read-only{cursor:default}.properties>.pane-scroll>label>input.property-expression-value::-webkit-inner-spin-button,.properties>.pane-scroll>label>input.property-expression-value::-webkit-outer-spin-button{display:none}
|
||||
.properties>.pane-scroll>dl dt:nth-of-type(even),.properties>.pane-scroll>dl dd:nth-of-type(even){background:var(--fc-panel)}
|
||||
.properties input[type=checkbox]{width:14px;height:14px;margin:2px 0;accent-color:var(--fc-accent);color-scheme:dark}.properties input[type=checkbox]:focus-visible{outline:1px solid var(--fc-accent);outline-offset:1px}.properties input[type=checkbox]:disabled{opacity:.45}
|
||||
.properties input[type=number]{color-scheme:dark}.properties input[type=number]::-webkit-inner-spin-button,.properties input[type=number]::-webkit-outer-spin-button{opacity:1;filter:grayscale(1) brightness(1.35)}.properties input[type=number]:hover::-webkit-inner-spin-button,.properties input[type=number]:hover::-webkit-outer-spin-button{filter:grayscale(1) brightness(1.7)}.properties input[type=number]:disabled::-webkit-inner-spin-button,.properties input[type=number]:disabled::-webkit-outer-spin-button{opacity:.45}
|
||||
.property-link-editor{display:flex;align-items:center;min-width:0;border:1px solid var(--fc-border);background:var(--fc-primary);border-radius:3px;min-height:22px}.property-link-summary{min-width:0;flex:1;padding:2px 4px;color:var(--fc-accent);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.property-link-button{width:22px;height:20px;flex:none;margin:0;padding:0;border:0;border-left:1px solid var(--fc-border);border-radius:0;background:linear-gradient(to bottom,var(--fc-panel),var(--fc-primary));color:var(--fc-text);line-height:1;cursor:pointer}.property-link-button:hover,.property-link-button:focus-visible{background:var(--fc-accent-hover);border-color:var(--fc-accent);outline:1px solid var(--fc-accent);outline-offset:-1px}.property-link-list{grid-template-columns:minmax(72px,.72fr) minmax(0,1fr)!important}.property-link-list select{width:100%;min-height:66px!important}.primitive-tools{display:flex;gap:4px;margin:8px 0}.tool{display:grid;place-items:center;width:38px;height:36px;flex:none;border:1px solid #435464;border-radius:4px;background:#17212b;color:#e7edf3;cursor:pointer}.tool[aria-pressed=true]{background:#264b56;border-color:#66c7d5}.tool:disabled{opacity:.45;cursor:default}.primitive-actions{display:flex;gap:8px;margin-top:12px}.primitive-actions button{display:flex;align-items:center;gap:8px;font:inherit;padding:8px;background:#1d2a35;color:#e7edf3;border:1px solid #435464;border-radius:4px}.primitive-editor{margin-top:14px;border:0;border-top:1px solid #435464;padding:14px 0 0}.primitive-editor legend{padding:0 6px 0 0}
|
||||
@media(max-width:1100px){.layout{grid-template-columns:210px minmax(0,1fr)}.properties{grid-column:1/-1;border-top:1px solid #2c3b48}}
|
||||
@media(max-width:650px){.layout{grid-template-columns:minmax(0,1fr)}.stage,aside{padding:14px}.viewport{height:340px}.top{gap:8px;padding:12px}.title{font-size:14px}.properties{grid-column:auto}}
|
||||
.desktop-workspace .layout{grid-template-columns:var(--tree-width) 5px var(--property-width) 5px minmax(0,1fr);min-height:calc(100vh - 160px)}
|
||||
.desktop-workspace .layout>aside[aria-label="Model tree"]{grid-column:1;grid-row:1}.desktop-workspace .layout>aside.properties{grid-column:3;grid-row:1;border-left:0;border-right:1px solid var(--fc-border)}.desktop-workspace .layout>main.stage{grid-column:5;grid-row:1}.desktop-workspace .layout>.panel-separator[aria-label="Resize tree panel"]{grid-column:2;grid-row:1}.desktop-workspace .layout>.panel-separator[aria-label="Resize properties panel"]{grid-column:4;grid-row:1}
|
||||
.desktop-workspace .layout>aside[aria-label="Model tree"],.desktop-workspace .layout>aside.properties{border:1px solid var(--fc-border);padding-top:0}.desktop-workspace .layout>aside[aria-label="Model tree"]>h2,.desktop-workspace .layout>aside.properties>h2{margin:0 -18px 12px;padding:3px 18px;text-align:center;font-size:14px;line-height:1.3;font-weight:700;background:linear-gradient(to bottom,var(--fc-panel),var(--fc-primary));border-bottom:1px solid var(--fc-border)}
|
||||
@media(max-width:650px){.layout{grid-template-columns:minmax(0,1fr)}.layout>main.stage{order:-1}.layout>aside[aria-label="Model tree"],.layout>aside.properties{order:0}.panel-separator{display:none}.application-menus{flex-wrap:nowrap;overflow-x:auto}.stage,aside{padding:14px}.viewport{height:340px}.top{gap:8px;padding:12px}.title{font-size:14px}.properties{grid-column:auto}}
|
||||
.desktop-workspace .layout{grid-template-columns:var(--tree-width) 5px minmax(0,1fr) 5px var(--property-width);grid-template-rows:minmax(0,1fr)}
|
||||
.desktop-workspace .layout>aside[aria-label="Model tree"]{grid-column:1;grid-row:1}.desktop-workspace .layout>aside.properties{grid-column:5;grid-row:1;border-right:0;border-left:1px solid var(--fc-border)}.desktop-workspace .layout>main.stage{grid-column:3;grid-row:1}.desktop-workspace .layout>.panel-separator[aria-label="Resize tree panel"]{grid-column:2;grid-row:1}.desktop-workspace .layout>.panel-separator[aria-label="Resize properties panel"]{grid-column:4;grid-row:1}
|
||||
.desktop-workspace .layout>aside[aria-label="Model tree"],.desktop-workspace .layout>aside.properties{border:1px solid var(--fc-border);padding:0}.desktop-workspace .layout>aside[aria-label="Model tree"]>h2,.desktop-workspace .layout>aside.properties>h2{margin:0 0 12px;padding:3px 18px;text-align:center;font-size:14px;line-height:1.3;font-weight:700;background:linear-gradient(to bottom,var(--fc-panel),var(--fc-primary));border-bottom:1px solid var(--fc-border);flex:0 0 auto}
|
||||
.stage-sketch-task{margin-top:12px;border:1px solid var(--fc-border);background:var(--fc-primary);padding:10px 12px;max-height:60vh;overflow:auto}
|
||||
.stage-sketch-task .task-panel>fieldset:first-of-type{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(230px,100%),1fr));gap:6px 18px;align-items:start}
|
||||
.stage-sketch-task .task-panel>fieldset{min-width:0;border:1px solid var(--fc-border);padding:10px 12px;margin:10px 0}
|
||||
@@ -1800,10 +1898,10 @@ function App() {
|
||||
.desktop-workspace .stage{background:var(--fc-primary)}.desktop-workspace .viewport{background:transparent}.application-menus,.workbench-toolbar,.document-tabs{display:flex;align-items:center;gap:4px;padding:4px 10px;background:var(--fc-menu);border-bottom:1px solid var(--fc-border);flex-wrap:wrap}.application-menus:focus-visible{border:1px solid var(--fc-accent);outline:none}
|
||||
.application-menus details,.workbench-parity-menu{position:relative}.application-menus summary,.workbench-parity-menu>summary{cursor:pointer;padding:2px 8px 3px 8px}.application-menus summary:hover,.application-menus summary:focus-visible,.application-menus details[open]>summary,.workbench-parity-menu>summary:hover,.workbench-parity-menu>summary:focus-visible{background:var(--fc-accent-bg);outline:1px solid var(--fc-accent);outline-offset:-1px}.menu-items,.workbench-parity-items{position:absolute;z-index:10;background:var(--fc-menu);padding:4px;min-width:230px;border:1px solid var(--fc-border);box-shadow:0 8px 20px #0008}.menu-items .action,.workbench-parity-subitems button{border-radius:0;margin:0;padding:4px 23px 4px 5px;background:transparent}.menu-items .action:disabled,.workbench-parity-subitems button:disabled{color:var(--fc-disabled);opacity:1;cursor:default}.menu-items .action:disabled:hover,.menu-items .action:disabled:focus-visible,.workbench-parity-subitems button:disabled:hover,.workbench-parity-subitems button:disabled:focus-visible{background:transparent;border-color:transparent}.menu-items .action:not(:disabled):hover,.menu-items .action:not(:disabled):focus-visible,.workbench-parity-subitems button:not(:disabled):hover,.workbench-parity-subitems button:not(:disabled):focus-visible{background:var(--fc-accent-bg);border-color:var(--fc-accent)}.workbench-parity-group{position:relative}.workbench-parity-group>summary{display:flex;align-items:center;justify-content:space-between;gap:12px;cursor:pointer;padding:4px 8px;white-space:nowrap}.workbench-menu-arrow{box-sizing:content-box;flex:0 0 8px;width:8px;height:8px;margin:5px;padding-left:12px;color:var(--fc-text);background:transparent}.workbench-parity-subitems{display:none;position:absolute;left:100%;top:-4px;z-index:11;min-width:260px;background:var(--fc-menu);padding:4px;border:1px solid var(--fc-border);box-shadow:0 8px 20px #0008}.workbench-parity-group[open]>.workbench-parity-subitems{display:grid;gap:1px}.workbench-parity-subitems button{display:flex;align-items:center;justify-content:space-between;gap:16px;width:100%;color:var(--fc-text);text-align:left}.workbench-parity-subitems kbd{color:#b5b5b5;font:12px ui-monospace,monospace}
|
||||
.document-tabs-viewport{display:flex;align-items:stretch;min-width:0;border-top:1px solid var(--fc-border);border-bottom:0;margin-top:12px;padding:4px 0 0;background:var(--fc-menu)}.document-tabs{flex:1 1 auto;min-width:0;gap:0;flex-wrap:nowrap;overflow-x:auto;overflow-y:hidden}.document-tabs-scroll{display:inline-flex;align-items:center;justify-content:center;flex:0 0 24px;width:24px;min-height:26px;margin:0;padding:2px;border:1px solid transparent;border-radius:0;background:var(--fc-menu);color:#888;cursor:pointer}.document-tabs-scroll:hover,.document-tabs-scroll:focus-visible{background:var(--fc-accent-hover);border-color:var(--fc-accent);color:var(--fc-text);outline:none}.document-tabs-scroll:disabled{color:var(--fc-disabled);cursor:default;opacity:.65}.document-tabs-scroll svg{width:14px;height:14px}.document-tabs .tab{display:flex;align-items:center;flex:0 0 auto;gap:6px;width:auto;margin:0;font-size:13px;border:1px solid var(--fc-border);border-radius:3px 3px 0 0;padding:4px;background:var(--fc-tab-inactive);border-bottom-color:var(--fc-border);cursor:grab}.document-tabs .tab:active{cursor:grabbing}.document-tabs .tab:hover{background:var(--fc-border-hover)}.document-tabs .tab.active{background:var(--fc-tab-active);border-color:var(--fc-border);border-bottom-color:var(--fc-tab-active);font-weight:700}.document-tabs .tab-label{min-width:0;overflow-wrap:anywhere}.document-tabs .tab-close{display:inline-flex;align-items:center;justify-content:center;flex:0 0 16px;width:16px;height:16px;margin:0;padding:0;border:1px solid transparent;border-radius:3px;background:transparent;color:#888;cursor:pointer}.document-tabs .tab-close:hover,.document-tabs .tab-close:focus-visible{background:var(--fc-accent-hover);border-color:var(--fc-accent);color:#d30000;outline:none}.document-tabs .tab-close:active{background:var(--fc-accent-hover);color:#780000}.document-tabs .tab-close:disabled{opacity:.45;cursor:default}.document-tabs .tab-close svg{width:12px;height:12px}.workbench-toolbar button{width:auto;margin:0;padding:2px 6px;border-radius:3px}.desktop-workspace .tab,.desktop-workspace .action,.desktop-workspace .actions button,.desktop-workspace .text-command{border-radius:3px}.panel-separator{position:relative;background:transparent;cursor:col-resize;touch-action:none;width:5px}.panel-separator::before{position:absolute;top:2px;bottom:2px;left:50%;width:1px;background:var(--fc-border);content:"";transform:translateX(-50%)}.panel-separator:hover::before{background:var(--fc-border-hover)}.panel-separator:focus-visible{outline:1px solid var(--fc-accent);outline-offset:-1px}.stage{padding:12px}.stage>h2{font-size:16px}.workspace-task-controls{min-width:210px;background:var(--fc-primary);border-top:1px solid var(--fc-border);margin-top:18px;padding:12px 0 0}.workspace-task-controls h2{font-size:14px;line-height:1.3;margin:0 0 10px;padding:7px 0;border-bottom:1px solid var(--fc-border)}.workspace-task-controls button{margin-right:6px}.developer-panel{border:1px dashed var(--fc-border);padding:12px}.properties{font-size:14px}
|
||||
@media(max-width:1100px){.desktop-workspace .layout{grid-template-columns:210px 5px 270px 5px minmax(0,1fr)}.desktop-workspace .layout>aside.properties{grid-column:3;grid-row:1}.desktop-workspace .layout>main.stage{grid-column:5;grid-row:1}.panel-separator[aria-label="Resize properties panel"]{display:block}}
|
||||
@media(max-width:800px){.desktop-workspace .layout{display:flex;flex-direction:column}.panel-separator{display:none}.desktop-workspace aside{max-height:45vh}.viewport{height:340px}}
|
||||
@media(max-width:1100px){.desktop-workspace .layout{grid-template-columns:210px 5px minmax(0,1fr) 5px 270px}.desktop-workspace .layout>aside.properties{grid-column:5;grid-row:1}.desktop-workspace .layout>main.stage{grid-column:3;grid-row:1}.panel-separator[aria-label="Resize properties panel"]{display:block}}
|
||||
@media(max-width:800px){.desktop-workspace .layout{display:flex;flex-direction:column;overflow:visible}.desktop-workspace .layout>main.stage{order:-1}.panel-separator{display:none}.desktop-workspace aside{max-height:45vh}.viewport{height:340px}}
|
||||
.application-menus .menu-items>label{display:flex;align-items:center;gap:2px;min-height:22px;padding:4px 23px 4px 5px;color:var(--fc-text);cursor:pointer;white-space:nowrap}.application-menus .menu-items>label:hover{background:var(--fc-accent-hover)}.application-menus .menu-items>label input[type=checkbox]{appearance:none;box-sizing:border-box;width:12px;height:12px;flex:0 0 12px;margin:2px;border:1px solid var(--fc-border);border-radius:3px;background:var(--fc-primary);color-scheme:dark}.application-menus .menu-items>label input[type=checkbox]:hover{border-color:var(--fc-border-hover)}.application-menus .menu-items>label input[type=checkbox]:focus-visible{outline:1px solid var(--fc-accent);outline-offset:1px}.application-menus .menu-items>label input[type=checkbox]:checked{background:linear-gradient(135deg,transparent 42%,#fff 42% 56%,transparent 56%) 0 4px/6px 6px no-repeat,linear-gradient(45deg,transparent 41%,#fff 41% 56%,transparent 56%) 5px 1px/6px 8px no-repeat,var(--fc-primary)}.application-menus .menu-items>label input[type=checkbox]:disabled{background:var(--fc-menu);border-color:var(--fc-border);opacity:.65}
|
||||
@media(max-width:650px){.desktop-workspace .layout>aside[aria-label="Model tree"]>h2,.desktop-workspace .layout>aside.properties>h2{margin-right:-14px;margin-left:-14px;padding-right:14px;padding-left:14px}.menu-items,.workbench-parity-items{position:fixed;left:12px;right:12px;min-width:0;max-width:calc(100vw - 24px);box-sizing:border-box}.workbench-parity-subitems{left:auto;right:0;top:100%;width:100%;min-width:0;max-height:calc(100vh - 120px);overflow:auto}.document-tabs{flex-wrap:nowrap;overflow:auto}.document-tabs .tab{flex-shrink:0}.document-tabs-scroll{flex-basis:22px;width:22px}}
|
||||
@media(max-width:650px){.desktop-workspace .layout>aside[aria-label="Model tree"]>h2,.desktop-workspace .layout>aside.properties>h2{margin:0 0 12px;padding:3px 14px}.menu-items,.workbench-parity-items{position:fixed;left:12px;right:12px;min-width:0;max-width:calc(100vw - 24px);box-sizing:border-box}.workbench-parity-subitems{left:auto;right:0;top:100%;width:100%;min-width:0;max-height:calc(100vh - 120px);overflow:auto}.document-tabs{flex-wrap:nowrap;overflow:auto}.document-tabs .tab{flex-shrink:0}.document-tabs-scroll{flex-basis:22px;width:22px}}
|
||||
`}</style><style>{`.start-dialog{box-sizing:border-box;width:min(1100px,94vw);max-height:88vh;padding:0;border:1px solid var(--fc-border);border-radius:6px;background:var(--fc-panel);color:var(--fc-text);overflow:auto}.viewport-hint{margin:2px 0 0;font-size:11px;line-height:1.4;color:var(--fc-text-muted,#8a949e)}@media(max-width:650px){.viewport-hint{font-size:10px}}.viewport-transform-bar{display:flex;flex-wrap:wrap;align-items:center;gap:4px;margin-top:2px}.viewport-transform-bar .tool{min-width:52px}.placement-readout{font-size:11px;color:var(--fc-text-muted,#8a949e);font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.frame-dialog{box-sizing:border-box;width:min(520px,94vw);padding:16px;border:1px solid var(--fc-border);border-radius:6px;background:var(--fc-panel);color:var(--fc-text)}.frame-dialog h3{margin:0 0 6px;font-size:14px}.frame-dialog-note{margin:0 0 10px;font-size:11px;color:var(--fc-text-muted,#8a949e)}.frame-dialog fieldset{margin:0 0 10px;padding:6px 8px;border:1px solid var(--fc-border);border-radius:4px}.frame-dialog .position-fields{display:flex;gap:6px}.frame-dialog .position-fields input{width:100%}.frame-dialog-actions{display:flex;flex-wrap:wrap;gap:6px;justify-content:flex-end}.frame-dialog::backdrop{background:rgba(0,0,0,.55)}@media(max-width:650px){.placement-readout{width:100%;white-space:normal}}.start-dialog::backdrop{background:rgba(0,0,0,.55)}.start-dialog section[aria-label="Start"][data-start-view]{margin:0}.menu-items hr,.workbench-parity-items hr{height:1px;margin:4px 0;border:0;background:var(--fc-border)}.desktop-workspace .action{box-sizing:border-box;min-width:80px;padding:3px 12px;background:linear-gradient(to bottom,#2b2b2b,#191919);border:1px solid #3f3f3f;color:#fff}.desktop-workspace .action:hover:not(:disabled){background:#575757;border-color:#3f3f3f}.desktop-workspace .action:focus-visible{border-color:#66c7d5;outline:none}.desktop-workspace .action:active:not(:disabled){background:linear-gradient(to bottom,#191919,#2b2b2b);border-color:#575757}.desktop-workspace .action:disabled{background:#0f0f0f;color:#858585;border-color:#3f3f3f;opacity:1}.desktop-workspace [role="toolbar"][aria-label="Cell text style"] button[aria-pressed="true"]{appearance:none;box-sizing:border-box;min-width:80px;padding:3px 12px;background:linear-gradient(to bottom,#242424,#191919);border:1px solid #575757;border-radius:3px;color:#fff}.desktop-workspace [role="toolbar"][aria-label="Cell text style"] button[aria-pressed="true"]:hover:not(:disabled){background:#575757;border-color:#66c7d5}.desktop-workspace [role="toolbar"][aria-label="Cell text style"] button[aria-pressed="true"]:active:not(:disabled){background:#2b2b2b;border-color:#3f3f3f}.desktop-workspace [role="toolbar"][aria-label="Cell text style"] button[aria-pressed="true"]:disabled{background:#0f0f0f;color:#858585;border-color:#3f3f3f;opacity:1}`}</style><header className="top"><span className="brand">FC</span><span>FreeCAD 1.2 Web</span><strong className="title">{active || "Workspace"}</strong></header>
|
||||
{startVisible && <dialog className="start-dialog" aria-label="Start dialog"
|
||||
ref={node => { if (node && !node.open) node.showModal(); }}
|
||||
@@ -1882,7 +1980,7 @@ function App() {
|
||||
}
|
||||
setWorkspaceTask(""); setViewCommand(""); setWorkbenches(previous => ({ ...previous, [active]: next }));
|
||||
void startParameters(router, { LastModule: `${next}Workbench` }, true).catch(error => setStatus(String(error)));
|
||||
}}><option>Part</option><option>Sketcher</option><option>PartDesign</option><option>Spreadsheet</option><option>Surface</option><option>Assembly</option><option>Draft</option><option>Architecture</option><option>BIM</option><option>CAM</option><option>Cloud</option><option>Fem</option><option>Help</option><option>Import</option><option>Inspection</option><option>JtReader</option><option>Material</option><option>Measure</option><option>Mesh</option><option>MeshPart</option><option>Points</option><option>ReverseEngineering</option><option>Robot</option><option>Sandbox</option><option>Start</option><option>TechDraw</option><option>Test</option><option>Tux</option><option disabled={!nativeDocuments.current.has(active)}>TemplatePyMod</option></select></label>
|
||||
}}><option>Part</option><option>Sketcher</option><option>PartDesign</option><option>Spreadsheet</option><option>Surface</option><option>Assembly</option><option>Draft</option><option>BIM</option><option>CAM</option><option>Cloud</option><option>Fem</option><option>Help</option><option>Import</option><option>Inspection</option><option>JtReader</option><option>Material</option><option>Measure</option><option>Mesh</option><option>MeshPart</option><option>Plot</option><option>Points</option><option>ReverseEngineering</option><option>Robot</option><option>Sandbox</option><option>Show</option><option>Start</option><option>TechDraw</option><option>Test</option><option>Tux</option><option>Web</option><option disabled={!nativeDocuments.current.has(active)}>TemplatePyMod</option></select></label>
|
||||
</ToolbarGroup>
|
||||
<ParityWorkbenchToolbars workbench={workbench} onCommand={executeManifestCommand} />
|
||||
{csvPanel && <SpreadsheetCsvPanel mode={csvPanel.mode} selected={csvPanel.selected}
|
||||
@@ -1922,13 +2020,18 @@ function App() {
|
||||
} finally { setImporting(false); }
|
||||
}} />}
|
||||
<ToolbarGroup name="Spreadsheet tools">
|
||||
{workbench === "Spreadsheet" && <><button disabled={importing || !!csvPanel || !active} onClick={() => void createSheet(undefined, undefined, "Spreadsheet_Import").catch(error => setStatus(String(error)))}>Import CSV…</button>
|
||||
<button disabled={importing || !!csvPanel || !active} onClick={() => void createSheet(undefined, undefined, "Spreadsheet_Export").catch(error => setStatus(String(error)))}>Export CSV…</button></>}
|
||||
{workbench === "Spreadsheet" && <button disabled={importing || !active} onClick={() => void createSheet().catch(error => setStatus(String(error)))}>Create spreadsheet</button>}
|
||||
{workbench === "Spreadsheet" && <SpreadsheetPanel
|
||||
busy={importing}
|
||||
csvOpen={Boolean(csvPanel)}
|
||||
hasDocument={Boolean(active)}
|
||||
onImportCsv={() => void createSheet(undefined, undefined, "Spreadsheet_Import").catch(error => setStatus(String(error)))}
|
||||
onExportCsv={() => void createSheet(undefined, undefined, "Spreadsheet_Export").catch(error => setStatus(String(error)))}
|
||||
onCreateSheet={() => void createSheet().catch(error => setStatus(String(error)))}
|
||||
/>}
|
||||
</ToolbarGroup>
|
||||
{workbench === "Part" && <PartWorkbenchToolbars disabled={partActionDisabled} activate={activatePartAction} currentTask={workspaceTask} />}
|
||||
<div className="layout" style={{ "--tree-width": `${treeWidth}px`, "--property-width": `${propertyWidth}px` } as React.CSSProperties}><aside aria-label="Model tree">
|
||||
<h2>Objects</h2><DocumentTree nodes={treeNodes} selected={String(selectedObjects[active] ?? "")} label="Document objects" busy={importing} onSelect={id => selectPrimaryObject(id)} onToggleVisibility={(id, visible) => updateProperty(id, "Visibility", visible)} />{!objects.length ? <p className="status">No objects</p> : null}
|
||||
<h2>Objects</h2><div className="pane-scroll" aria-label="Model tree objects"><DocumentTree nodes={treeNodes} selected={String(selectedObjects[active] ?? "")} label="Document objects" busy={importing} onSelect={id => selectPrimaryObject(id)} onToggleVisibility={(id, visible) => updateProperty(id, "Visibility", visible)} />{!objects.length ? <p className="status">No objects</p> : null}
|
||||
{active && !designDocuments.current.has(active) && <details><summary>New Group</summary>
|
||||
<WebGroupTask key={active} router={router} documentId={nativeName(active)} runtimeOwner="DocumentProbe"
|
||||
disabled={importing} onBusyChange={setImporting}
|
||||
@@ -1940,7 +2043,7 @@ function App() {
|
||||
setStatus(`Created ${value.createdObject}`);
|
||||
}}
|
||||
onSelect={object => setSelectedObjects(previous => ({ ...previous, [active]: `native:${object}` }))} />
|
||||
</details>}
|
||||
</details>}</div>
|
||||
</aside>{panelSeparator("tree")}<main className="stage"><h2>{active || "Workspace"}</h2>
|
||||
{workbench === "Spreadsheet" && (selectedObject?.type === "Spreadsheet::Sheet" ? <SpreadsheetSheetEditor
|
||||
key={`${active}:${selectedObject.id}`} sheet={String(selectedObject.properties.Label)}
|
||||
@@ -2052,6 +2155,8 @@ function App() {
|
||||
onClick={() => setReferenceOpen(open => !open)}>参考模型 GLB</button>
|
||||
<button type="button" className="action" aria-pressed={lineReferenceOpen} aria-label="Toggle line reference viewer"
|
||||
onClick={() => setLineReferenceOpen(open => !open)}>产线参考模型</button>
|
||||
<button type="button" className="action" aria-pressed={abbReferenceOpen} aria-label="Toggle ABB IRB 120 reference viewer"
|
||||
onClick={() => setAbbReferenceOpen(open => !open)}>ABB 参考模型</button>
|
||||
{viewCommand && <WebViewTask key={active} router={router} command={viewCommand} documentId={nativeName(active)}
|
||||
runtimeOwner="DocumentProbe" disabled={importing}
|
||||
selection={compoundSelection.map(object => ({ documentId: nativeName(active), object }))}
|
||||
@@ -2082,7 +2187,9 @@ function App() {
|
||||
if (result.file) void listDocumentFiles().then(files => { setSavedDocuments(files); window.dispatchEvent(new Event("freecad-document-persistence")); }).catch(error => setStatus(String(error)));
|
||||
}} />
|
||||
</>}
|
||||
<div ref={viewportRef} style={testDocuments.current.has(active) || isExternalWorkbench(workbench) ? { display: "none" } : undefined} className="viewport" aria-label="Imported native 3D view" />
|
||||
{/* Spreadsheet has no 3D scene; keeping the empty viewport only pushes the
|
||||
grid down on narrow screens (UI-GAP-14). */}
|
||||
<div ref={viewportRef} style={testDocuments.current.has(active) || isExternalWorkbench(workbench) || workbench === "Spreadsheet" ? { display: "none" } : undefined} className="viewport" aria-label="Imported native 3D view" />
|
||||
{workbench === "Part" && active && workspaceTask === "sketcher-new-sketch" && <div className="stage-sketch-task">
|
||||
<PartNewSketchTask
|
||||
key={active} documentId={nativeName(active)} snapshot={partSnapshots[active]} selected={compoundSelection}
|
||||
@@ -2102,7 +2209,8 @@ function App() {
|
||||
return result;
|
||||
}} />
|
||||
</div>}
|
||||
{isExternalWorkbench(workbench) && <WorkbenchFrame workbench={workbench} />}
|
||||
{isExternalWorkbench(workbench) && <WorkbenchFrame workbench={workbench} native={nativeWorkbench}
|
||||
router={nativeWorkbench ? router : undefined} documentId={nativeWorkbench ? nativeName(active) : undefined} />}
|
||||
<div className="viewport-transform-bar" role="toolbar" aria-label="Object transform">
|
||||
{([["translate", "移动"], ["rotate", "旋转"], ["off", "关闭"]] as const).map(([mode, label]) => (
|
||||
<button key={mode} className="tool" title={`${label}控制器`} aria-label={`${label}控制器`} aria-pressed={transformMode === mode}
|
||||
@@ -2134,28 +2242,41 @@ function App() {
|
||||
<p className="viewport-hint" aria-label="Navigation hints">中键按住平移 · 滚轮缩放 · 中键加左键(或右键加 Shift)旋转 · 局部坐标默认锁定,改写请用「局部坐标…」</p>
|
||||
{frameEditor && <dialog className="frame-dialog" aria-label="Local frame editor"
|
||||
ref={node => { if (node && !node.open) node.showModal(); }}
|
||||
onClose={() => setFrameEditor(null)} onCancel={() => setFrameEditor(null)}>
|
||||
onClose={() => { cancelPlacementPreview(); setFrameEditor(null); }} onCancel={() => { cancelPlacementPreview(); setFrameEditor(null); }}>
|
||||
<h3>局部坐标:{frameEditor.object}</h3>
|
||||
<p className="frame-dialog-note">原点与欧拉角(XYZ°,先绕 X 再 Y 再 Z)。应用后写入模型 Placement,控制器姿态同步刷新。</p>
|
||||
<fieldset><legend>原点</legend><div className="position-fields">{["X", "Y", "Z"].map((axis, index) => (
|
||||
<label key={axis}>{axis}<input type="number" step="1" aria-label={`Frame origin ${axis}`} value={frameEditor.position[index]}
|
||||
onChange={event => setFrameEditor(current => current ? { ...current, position: current.position.map((value, i) => i === index ? Number(event.target.value) : value) as [number, number, number] } : current)} /></label>))}</div></fieldset>
|
||||
onChange={event => { if (!frameEditor) return;
|
||||
const next = { ...frameEditor, position: frameEditor.position.map((value, i) => i === index ? Number(event.target.value) : value) as [number, number, number] };
|
||||
setFrameEditor(next); schedulePlacementPreview({ position: next.position, ...axisAngleFromEuler(next.euler) }); }} /></label>))}</div></fieldset>
|
||||
<fieldset><legend>欧拉角</legend><div className="position-fields">{["X", "Y", "Z"].map((axis, index) => (
|
||||
<label key={axis}>{axis}<input type="number" step="15" aria-label={`Frame euler ${axis}`} value={frameEditor.euler[index]}
|
||||
onChange={event => setFrameEditor(current => current ? { ...current, euler: current.euler.map((value, i) => i === index ? Number(event.target.value) : value) as [number, number, number] } : current)} /></label>))}</div></fieldset>
|
||||
onChange={event => { if (!frameEditor) return;
|
||||
const next = { ...frameEditor, euler: frameEditor.euler.map((value, i) => i === index ? Number(event.target.value) : value) as [number, number, number] };
|
||||
setFrameEditor(next); schedulePlacementPreview({ position: next.position, ...axisAngleFromEuler(next.euler) }); }} /></label>))}</div></fieldset>
|
||||
<div className="frame-dialog-actions">
|
||||
<button className="action" aria-label="应用局部坐标" onClick={() => {
|
||||
const editor = frameEditor;
|
||||
const { axis, angle } = axisAngleFromEuler(editor.euler);
|
||||
setFrameEditor(null);
|
||||
cancelPlacementPreview();
|
||||
void editNative("setPlacement", { object: editor.object, position: editor.position, axis, angle } as never);
|
||||
}}>应用到模型</button>
|
||||
<button className="action" aria-label="还原局部坐标" onClick={() => setFrameEditor({
|
||||
object: frameEditor.object,
|
||||
position: [placementXyz[0], placementXyz[1], placementXyz[2]],
|
||||
euler: [placementEuler[0], placementEuler[1], placementEuler[2]],
|
||||
})}>还原</button>
|
||||
<button className="action" aria-label="旋转归零" onClick={() => setFrameEditor(current => current ? { ...current, euler: [0, 0, 0] } : current)}>旋转归零</button>
|
||||
<button className="action" aria-label="还原局部坐标" onClick={() => {
|
||||
cancelPlacementPreview();
|
||||
setFrameEditor({
|
||||
object: frameEditor.object,
|
||||
position: [placementXyz[0], placementXyz[1], placementXyz[2]],
|
||||
euler: [placementEuler[0], placementEuler[1], placementEuler[2]],
|
||||
});
|
||||
}}>还原</button>
|
||||
<button className="action" aria-label="旋转归零" onClick={() => {
|
||||
if (!frameEditor) return;
|
||||
const next = { ...frameEditor, euler: [0, 0, 0] as [number, number, number] };
|
||||
setFrameEditor(next);
|
||||
schedulePlacementPreview({ position: next.position, ...axisAngleFromEuler(next.euler) });
|
||||
}}>旋转归零</button>
|
||||
<button className="action" aria-label="关闭局部坐标编辑器" onClick={() => setFrameEditor(null)}>关闭</button>
|
||||
</div>
|
||||
</dialog>}
|
||||
@@ -2185,7 +2306,7 @@ function App() {
|
||||
onClick={() => void exportSelectedShape()}><ToolIcon nodes={Download} /></button>
|
||||
<button className="action" disabled={!objects.length} onClick={() => renderBridge.fitDocument()}>适合全部对象</button>
|
||||
<button className="action" disabled={!active || importing} onClick={() => void saveFcstd()}>保存 FCStd 到 OPFS</button>
|
||||
<button className="action" disabled={!nativeBytes} onClick={downloadFcstd}>下载 native FCStd</button>
|
||||
<button className="action" disabled={!nativeBytes} onClick={() => void downloadFcstd()}>下载 native FCStd</button>
|
||||
<label>OPFS 导出件<select className="saved-documents" aria-label="OPFS export"
|
||||
value={opfsExportName} onChange={event => setOpfsExportName(event.target.value)}>
|
||||
<option value="">选择导出件</option>{opfsExports.map(name => <option key={name} value={name}>{name}</option>)}
|
||||
@@ -2234,7 +2355,7 @@ function App() {
|
||||
{documentTabsOverflow && <button type="button" className="document-tabs-scroll" aria-label="Scroll document tabs right" title="Scroll document tabs right"
|
||||
disabled={!documentTabsCanScrollRight} onClick={() => documentTabsRef.current?.scrollBy({ left: Math.max(120, documentTabsRef.current.clientWidth * 0.75), behavior: "smooth" })}><ToolIcon nodes={ChevronRight} /></button>}
|
||||
</div>
|
||||
</main>{panelSeparator("properties")}<aside className="properties" aria-label="Object Properties"><h2>Properties</h2>
|
||||
</main>{panelSeparator("properties")}<aside className="properties" aria-label="Object Properties"><h2>Properties</h2><div className="pane-scroll" aria-label="Object properties body">
|
||||
{selectedObject ? <>
|
||||
{(nativeDocuments.current.has(active) || jtDocuments.current.has(active)) && !!selectedObject.properties.NativeName && <button disabled={importing || !!workspaceTask} onClick={() => { setWorkspaceTask("position"); setStatus("Edit object position"); }}>Position</button>}
|
||||
<h3 className="property-group-title">View</h3><label><span>Label</span><input aria-label="Object Label" name="Label" disabled={designDocuments.current.has(active)} value={String(selectedObject.properties.Label ?? selectedObject.id)} onChange={event => updateProperty(selectedObject.id, "Label", event.target.value)} onBlur={event => void commitNativeLabel(event.currentTarget.value)} /></label>
|
||||
@@ -2255,8 +2376,13 @@ function App() {
|
||||
{selectedObject.type === "Part::Box" && <>
|
||||
<h3 className="property-group-title">Data</h3>
|
||||
{(["Length", "Width", "Height"] as const).map((name, index) => { const expression = (selectedObject.properties.primitiveExpressions as Record<string, unknown> | undefined)?.[name]; return <label key={name} data-property-editor-row={name}><span>{name}</span><input className={expression ? "property-expression-value" : undefined} aria-label={`Property ${name}`} aria-readonly={expression ? "true" : undefined} title={expression ? `Expression: ${String(expression)}` : undefined} type="number" readOnly={Boolean(expression)} min="0.001" step="any" value={boxDimensions[index]}
|
||||
onChange={event => setBoxDimensions(previous => previous.map((value, position) => position === index ? Number(event.target.value) : value) as [number, number, number])}
|
||||
onBlur={() => { if (!expression && !importing && selectedObject.properties.NativeName) void createOrEditBox(true); }} /></label>; })}
|
||||
onChange={event => {
|
||||
const next = boxDimensions.map((value, position) => position === index ? Number(event.target.value) : value) as [number, number, number];
|
||||
setBoxDimensions(next);
|
||||
if (!expression) propertyCommit.schedule("box", () => void createOrEditBox(true, { live: true, dimensions: next }));
|
||||
}}
|
||||
onKeyDown={event => { if (event.key === "Enter" && !expression) { event.preventDefault(); propertyCommit.flush("box"); } }}
|
||||
onBlur={() => { if (!expression && !importing && selectedObject.properties.NativeName) propertyCommit.flush("box"); }} /></label>; })}
|
||||
</>}
|
||||
{selectedPrimitiveDefinition && selectedObject.type !== "Part::Box" && <>
|
||||
<h3 className="property-group-title">Data</h3>
|
||||
@@ -2264,8 +2390,13 @@ function App() {
|
||||
<input className={expression ? "property-expression-value" : undefined} aria-label={`Property ${field}`} aria-readonly={expression ? "true" : undefined} title={expression ? `Expression: ${String(expression)}` : undefined} type="number" readOnly={Boolean(expression)} min={field === "Angle1" || field === "Angle2" ? (selectedPrimitive === "Sphere" ? -90 : -180) : selectedPrimitive === "Cone" && field.startsWith("Radius") ? 0 : 0.001}
|
||||
max={field === "Angle1" || field === "Angle2" ? (selectedPrimitive === "Sphere" ? 90 : 180) : field.startsWith("Angle") ? 360 : undefined}
|
||||
step={field.startsWith("Angle") ? 1 : 0.5} value={primitiveParameters[field] ?? selectedPrimitiveDefinition.defaults[field]}
|
||||
onChange={event => setPrimitiveParameters(previous => ({ ...previous, [field]: Number(event.target.value) }))}
|
||||
onBlur={() => { if (!importing && selectedObject.properties.NativeName) void createOrEditPrimitive(true); }} /></label>; })}
|
||||
onChange={event => {
|
||||
const next = { ...primitiveParameters, [field]: Number(event.target.value) };
|
||||
setPrimitiveParameters(next);
|
||||
if (!expression) propertyCommit.schedule("primitive", () => void createOrEditPrimitive(true, { live: true, parameters: next }));
|
||||
}}
|
||||
onKeyDown={event => { if (event.key === "Enter" && !expression) { event.preventDefault(); propertyCommit.flush("primitive"); } }}
|
||||
onBlur={() => { if (!expression && !importing && selectedObject.properties.NativeName) propertyCommit.flush("primitive"); }} /></label>; })}
|
||||
</>}
|
||||
{["Part::Fuse", "Part::Cut", "Part::Common"].includes(selectedObject.type) && <>
|
||||
<h3 className="property-group-title">Data</h3>
|
||||
@@ -2957,12 +3088,19 @@ function App() {
|
||||
})()} />}
|
||||
{workspaceTask === "position" && <fieldset className="primitive-editor" disabled={importing || !selectedObject?.properties.NativeName}><legend>Placement</legend>
|
||||
<div className="position-fields">{["X", "Y", "Z"].map((axis, index) => <label key={axis}>{axis}<input type="number" step="1" aria-label={`Position ${axis}`} value={position[index]}
|
||||
onChange={event => setPosition(previous => previous.map((value, i) => i === index ? Number(event.target.value) : value) as [number, number, number])} /></label>)}</div>
|
||||
onChange={event => {
|
||||
const next = position.map((value, i) => i === index ? Number(event.target.value) : value) as [number, number, number];
|
||||
setPosition(next); schedulePlacementPreview({ position: next, axis: rotationAxis, angle: rotationAngle });
|
||||
}} /></label>)}</div>
|
||||
<div className="position-fields">{["X", "Y", "Z"].map((axisName, index) => <label key={axisName}>轴 {axisName}<input type="number" step="0.5" aria-label={`Rotation axis ${axisName}`} value={rotationAxis[index]}
|
||||
onChange={event => setRotationAxis(previous => previous.map((value, i) => i === index ? Number(event.target.value) : value) as [number, number, number])} /></label>)}</div>
|
||||
onChange={event => {
|
||||
const next = rotationAxis.map((value, i) => i === index ? Number(event.target.value) : value) as [number, number, number];
|
||||
setRotationAxis(next); schedulePlacementPreview({ position, axis: next, angle: rotationAngle });
|
||||
}} /></label>)}</div>
|
||||
<label>角度°<input type="number" step="1" aria-label="Rotation angle" value={rotationAngle}
|
||||
onChange={event => setRotationAngle(Number(event.target.value))} /></label>
|
||||
onChange={event => { const next = Number(event.target.value); setRotationAngle(next); schedulePlacementPreview({ position, axis: rotationAxis, angle: next }); }} /></label>
|
||||
<button className="tool" title="应用位置与旋转" aria-label="应用位置与旋转" onClick={() => {
|
||||
cancelPlacementPreview();
|
||||
const object = String(selectedObject?.properties.NativeName);
|
||||
if (jtDocuments.current.has(active)) {
|
||||
const names = (compoundSelections[active]?.length ? compoundSelections[active] : [object]).map(value => value.replace(/^native:/, ""));
|
||||
@@ -3051,8 +3189,9 @@ function App() {
|
||||
<div className="stat"><strong>{active || "none"}</strong><small>{objects.length} objects</small></div>
|
||||
<div className="stat"><strong>Recent files</strong><small>{store.recent().length}</small></div>
|
||||
{developerMode && <div className="stat"><strong>Checkpoint</strong><small>localStorage metadata only</small></div>}
|
||||
</aside>{referenceOpen && <DeltaReferencePanel onClose={() => setReferenceOpen(false)} />}
|
||||
</div></aside>{referenceOpen && <DeltaReferencePanel onClose={() => setReferenceOpen(false)} />}
|
||||
{parityTask && <TaskFrame module={parityTask.module} command={parityTask.command}
|
||||
router={router} documentId={nativeName(active || initialDocumentId)}
|
||||
onClose={() => setParityTask(null)} />}
|
||||
{preferencesOpen && <PreferencesDialog onClose={() => setPreferencesOpen(false)} onApply={async preferences => {
|
||||
if (!active) return;
|
||||
@@ -3074,7 +3213,8 @@ function App() {
|
||||
selection={compoundSelection.map(name => String(objects.find(object => String(object.properties.NativeName) === name)?.properties.Label ?? name))}
|
||||
onClose={() => setBottomDockOpen(false)} />}
|
||||
<ShortcutManager onCommand={executeManifestCommand} />
|
||||
{lineReferenceOpen && <LineReferencePanel onClose={() => setLineReferenceOpen(false)} />}</div><footer className="desktop-status-bar" aria-label="Status bar"><p role="status" data-import-phase={importPhase} className={`status ${response?.kind === "error" ? "error" : response?.kind === "result" ? "ok" : ""}`}>{status}</p></footer></PersistentToolbarWorkspace></div>;
|
||||
{lineReferenceOpen && <LineReferencePanel onClose={() => setLineReferenceOpen(false)} />}
|
||||
{abbReferenceOpen && <Abb120ReferencePanel onClose={() => setAbbReferenceOpen(false)} />}</div><footer className="desktop-status-bar" aria-label="Status bar"><p role="status" data-import-phase={importPhase} className={`status ${response?.kind === "error" ? "error" : response?.kind === "result" ? "ok" : ""}`}>{status}</p></footer></PersistentToolbarWorkspace></div>;
|
||||
}
|
||||
|
||||
installNavigation("project", readNavigationContext());
|
||||
|
||||
@@ -1,24 +1,48 @@
|
||||
import React from "react";
|
||||
import React, { useEffect, useRef } from "react";
|
||||
import { WorkbenchShell } from "../workbench-shell.js";
|
||||
import type { WebModuleRouter } from "../module-router.js";
|
||||
|
||||
export function TaskFrame({ module, command, onClose }: {
|
||||
export function TaskFrame({ module, command, router, documentId, onClose }: {
|
||||
module: string;
|
||||
command: string;
|
||||
/** Shared router from the host shell; omitted means the task frame owns one. */
|
||||
router?: WebModuleRouter;
|
||||
/** Active document handed to the embedded workbench. */
|
||||
documentId?: string;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const src = `/workbench.html?module=${encodeURIComponent(module)}&command=${encodeURIComponent(command)}`;
|
||||
return <div className="parity-task-frame" role="dialog" aria-label={`${module} task: ${command}`}>
|
||||
const dialogRef = useRef<HTMLDivElement | null>(null);
|
||||
const closeRef = useRef(onClose);
|
||||
closeRef.current = onClose;
|
||||
// Escape closes the task the same way it closes a desktop task panel, and the
|
||||
// frame takes focus so keyboard events do not stay with the shell behind it.
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== "Escape") return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
closeRef.current();
|
||||
};
|
||||
document.addEventListener("keydown", onKeyDown, true);
|
||||
dialogRef.current?.focus();
|
||||
return () => document.removeEventListener("keydown", onKeyDown, true);
|
||||
}, [module, command]);
|
||||
return <div ref={dialogRef} className="parity-task-frame" role="dialog" aria-modal="true"
|
||||
tabIndex={-1} aria-label={`${module} task: ${command}`}>
|
||||
<style>{`
|
||||
.parity-task-frame{position:fixed;inset:0;background:#000b;z-index:80;display:flex;align-items:center;justify-content:center;padding:20px}
|
||||
.parity-task-frame:focus{outline:none}
|
||||
.parity-task-frame>section{width:min(1280px,96vw);height:min(860px,92vh);background:#0f1419;border:1px solid #3f3f3f;border-radius:8px;display:flex;flex-direction:column;overflow:hidden}
|
||||
.parity-task-frame header{display:flex;align-items:center;gap:10px;padding:8px 12px;background:#1b242c;border-bottom:1px solid #3f3f3f;color:#dbe6ee;font:13px system-ui,"Noto Sans SC",sans-serif}
|
||||
.parity-task-frame header strong{font-size:13px}
|
||||
.parity-task-frame header button{margin-left:auto;background:#2b2b2b;color:#dbe6ee;border:1px solid #555;border-radius:4px;padding:3px 10px;cursor:pointer}
|
||||
.parity-task-frame iframe{flex:1;width:100%;border:0;background:#0f1419}
|
||||
.parity-task-frame .fc-workbench-embed{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;overflow:hidden}
|
||||
`}</style>
|
||||
<section>
|
||||
<header><strong>{module} · {command}</strong><span style={{ color: "#93a6b3" }}>任务桥(复用工作台任务面板)</span>
|
||||
<button type="button" aria-label="Close task frame" onClick={onClose}>关闭</button></header>
|
||||
<iframe title={`${module} ${command} task`} src={src} />
|
||||
<WorkbenchShell module={module} command={command} router={router} documentId={documentId} standalone={false} />
|
||||
</section>
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,28 @@
|
||||
import React from "react";
|
||||
import { WorkbenchShell } from "../workbench-shell.js";
|
||||
import { LOCAL_WORKBENCHES } from "../workbenches/registry.js";
|
||||
import type { WebModuleRouter } from "../module-router.js";
|
||||
|
||||
const LOCAL_WORKBENCHES = new Set(["Part", "Sketcher", "PartDesign", "Spreadsheet"]);
|
||||
export const isExternalWorkbench = (workbench: string) => !LOCAL_WORKBENCHES.has(workbench);
|
||||
|
||||
export function WorkbenchFrame({ workbench }: { workbench: string }) {
|
||||
return <div className="workbench-frame" aria-label={`${workbench} workbench workspace`}>
|
||||
export function WorkbenchFrame({ workbench, native, router, documentId, onModuleChange }: {
|
||||
workbench: string;
|
||||
/** Render the workbench in-process instead of embedding /workbench.html in an iframe. */
|
||||
native?: boolean;
|
||||
/** Shared router for the native path; omitted means the shell owns its own. */
|
||||
router?: WebModuleRouter;
|
||||
/** Active document handed to the native workbench. */
|
||||
documentId?: string;
|
||||
onModuleChange?: (module: string) => void;
|
||||
}) {
|
||||
return <div className="workbench-frame" data-native={native ? "1" : "0"} aria-label={`${workbench} workbench workspace`}>
|
||||
<style>{`
|
||||
.workbench-frame{flex:1;min-height:0;display:flex;border-top:1px solid #2a3a45;background:#0f1419}
|
||||
.workbench-frame iframe{flex:1;width:100%;border:0;background:#0f1419}
|
||||
.workbench-frame .fc-workbench-embed{flex:1 1 auto;min-width:0;min-height:0;display:flex;flex-direction:column;overflow:hidden}
|
||||
`}</style>
|
||||
<iframe title={`${workbench} workbench`} src={`/workbench.html?module=${encodeURIComponent(workbench)}`} />
|
||||
{native
|
||||
? <WorkbenchShell module={workbench} documentId={documentId} router={router} standalone={false} onModuleChange={onModuleChange} />
|
||||
: <iframe title={`${workbench} workbench`} src={`/workbench.html?module=${encodeURIComponent(workbench)}`} />}
|
||||
</div>;
|
||||
}
|
||||
|
||||
52
web/src/use-debounced-commit.ts
Normal file
52
web/src/use-debounced-commit.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
type Entry = { timer: number; run: () => unknown };
|
||||
|
||||
/**
|
||||
* Debounces commits that are triggered by typing.
|
||||
*
|
||||
* Desktop FreeCAD applies a property as soon as the spin box loses focus, so the
|
||||
* user sees the model change only after leaving the field. Here the same commit
|
||||
* is scheduled ~250 ms after the last keystroke, and `flush` runs it immediately
|
||||
* on Enter/blur. Keys are scoped (e.g. `box:<doc>:<object>`) so a pending timer
|
||||
* for one object can never commit into another.
|
||||
*/
|
||||
export function useDebouncedCommit(defaultDelay = 250) {
|
||||
const entries = useRef(new Map<string, Entry>());
|
||||
|
||||
const cancel = (key: string) => {
|
||||
const entry = entries.current.get(key);
|
||||
if (!entry) return;
|
||||
window.clearTimeout(entry.timer);
|
||||
entries.current.delete(key);
|
||||
};
|
||||
|
||||
const cancelAll = () => {
|
||||
for (const key of [...entries.current.keys()]) cancel(key);
|
||||
};
|
||||
|
||||
const flush = (key: string) => {
|
||||
const entry = entries.current.get(key);
|
||||
if (!entry) return;
|
||||
window.clearTimeout(entry.timer);
|
||||
entries.current.delete(key);
|
||||
void entry.run();
|
||||
};
|
||||
|
||||
const flushPrefix = (prefix: string) => {
|
||||
for (const key of [...entries.current.keys()]) if (key.startsWith(prefix)) flush(key);
|
||||
};
|
||||
|
||||
const schedule = (key: string, run: () => unknown, delay = defaultDelay) => {
|
||||
cancel(key);
|
||||
const timer = window.setTimeout(() => {
|
||||
entries.current.delete(key);
|
||||
void run();
|
||||
}, delay);
|
||||
entries.current.set(key, { timer, run });
|
||||
};
|
||||
|
||||
useEffect(() => cancelAll, []);
|
||||
|
||||
return { schedule, flush, flushPrefix, cancel, cancelAll };
|
||||
}
|
||||
1209
web/src/web-desktop-adapter.ts
Normal file
1209
web/src/web-desktop-adapter.ts
Normal file
File diff suppressed because it is too large
Load Diff
19
web/src/workbench-entry.tsx
Normal file
19
web/src/workbench-entry.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
// Standalone entry for /workbench.html.
|
||||
//
|
||||
// The shell itself is a pure component: everything that touches document.body or
|
||||
// the URL at import time lives here, so that project-shell can import and render
|
||||
// <WorkbenchShell /> without side effects on its own document.
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { installNavigation, readNavigationContext } from "./navigation.js";
|
||||
import { installUiAccessibility } from "./ui-accessibility.js";
|
||||
import { WorkbenchShell } from "./workbench-shell.js";
|
||||
|
||||
installNavigation("workbench", readNavigationContext());
|
||||
installUiAccessibility();
|
||||
|
||||
const container = document.querySelector<HTMLDivElement>("#app");
|
||||
if (!container) throw new Error("workbench entry: #app container is missing");
|
||||
// Lock the page to the viewport so the three-column layout can hand its own
|
||||
// scrollbars to the left and right panels (see panel-scroll.css).
|
||||
document.documentElement.classList.add("stage-lock");
|
||||
createRoot(container).render(<WorkbenchShell standalone />);
|
||||
@@ -1,3 +1,6 @@
|
||||
// Shared side-panel scroll contract; also styles the embedded (.fc-workbench-embed)
|
||||
// variant that project.html renders in-process.
|
||||
import "./panel-scroll.css";
|
||||
import { selectedMeshState } from "./mesh-desktop-adapter.js";
|
||||
import { SandboxTaskPanelView } from "./sandbox-task-panel-view.js";
|
||||
import { requestOwnerParameters } from "./view-navigation-preferences.js";
|
||||
@@ -2524,6 +2527,12 @@ export function WorkbenchShell({
|
||||
startWorkspaceFrame.current?.contentWindow?.postMessage({ type: "freecad-show-start" }, window.location.origin);
|
||||
startWorkspaceFrame.current?.focus();
|
||||
}}>Show Start</button>}
|
||||
{/* Every module task panel (Mesh regular solid, Robot joints, Assembly,
|
||||
Part tools …) renders above the three-column layout, as it did before the
|
||||
scroll lock. The dock wrapper keeps that region out of the layout's
|
||||
height budget: under html.stage-lock it caps and scrolls itself, so a
|
||||
tall task panel can no longer push the centre stage below the viewport. */}
|
||||
<div className="module-task-dock">
|
||||
{(module === "Show" || (module === "Std" && command?.replace(/^Std:desktop:/, "") === "Std_ToggleClipPlane")) && <button type="button" disabled={busy} onClick={() => {
|
||||
const documentId = documentSelection.documentId;
|
||||
const owner = projectDocumentOwners.current.get(documentId);
|
||||
@@ -4297,6 +4306,7 @@ export function WorkbenchShell({
|
||||
</table>
|
||||
</div>
|
||||
</section>}
|
||||
</div>
|
||||
<AssemblyComponentContextMenu enabled={module === "Assembly"} dispatcher={desktopCommands}
|
||||
documentId={documentSelection.documentId} selection={documentSelection.selection} busy={assemblyContextBlocked} onBusy={setBusy}
|
||||
activateObject={(documentId, object, linked) => void activateAssemblyObject(documentId, object, linked)}
|
||||
@@ -4317,11 +4327,13 @@ export function WorkbenchShell({
|
||||
onSelection={(documentId, selection) => setDocumentSelection({ documentId, selection })}>
|
||||
<aside>
|
||||
<h2 className="heading">模块</h2>
|
||||
<div className="pane-scroll" aria-label="Workbench modules">
|
||||
<input className="search" value={query} onChange={(event) => setQuery(event.target.value)} placeholder="搜索模块" />
|
||||
{modules.map((item) => <button className={`module ${item.module === module ? "selected" : ""}`} key={item.module} onClick={() => { if (busy || workbenchSwitch.current) return; activateModule(item.module); setResponse(null); }}><strong>{item.module}</strong><small>{item.objectTypeCount} objects · {item.pythonApiCount} Python APIs</small></button>)}
|
||||
</aside>
|
||||
</div></aside>
|
||||
<aside>
|
||||
<h2 className="heading">{module} commands</h2>
|
||||
<div className="pane-scroll" aria-label="Workbench commands">
|
||||
<details className="workbench-document-picker">
|
||||
<summary>文档 · 打开 OPFS FCStd</summary>
|
||||
<label>OPFS 文档
|
||||
@@ -4965,7 +4977,7 @@ export function WorkbenchShell({
|
||||
<button id="cancel" className="run secondary" disabled={busy} onClick={() => void validateCommandMatrix("cancel")}>取消核验</button>
|
||||
<button id="reset" className="run secondary" disabled={busy} onClick={() => void resetCommandMatrix()}>重置 Worker</button>
|
||||
{moduleMatrixRecords.length > 0 ? <div className="matrix-list"><h2 className="heading">GUI / Web matrix</h2>{moduleMatrixRecords.map((item) => <button data-help-page={item.kind === "desktop-gui" ? item.command : undefined} className={`command ${item.id === selectedMatrixRecord?.id ? "selected" : ""}`} key={item.id} onClick={() => { setSelectedMatrixId(item.id); if (item.command === "Std_TestTaskBox" || (module === "Assembly" && item.command === "Assembly_CreateBom")) setTaskPanelGeneration(value => value + 1); if (item.kind === "desktop-gui" || item.kind === "web-command") { if (module === "Part" && item.command === "Part_SectionCut") setSectionCutOpen(true); setCommand(item.command); setPayloadText(item.kind === "web-command" ? commandPayload(module, item.command) : "{}"); setResponse(null); setStatus("输入命令参数后执行"); } }}><span>{item.command}</span><small>{item.kind} · {item.disposition}</small></button>)}</div> : null}
|
||||
</aside>
|
||||
</div></aside>
|
||||
<main className="stage"><section>
|
||||
{/* Sketcher editing belongs on the stage: in the narrow command column the
|
||||
drawing fieldset and constraint rows were cut off and required scrolling. */}
|
||||
|
||||
110
web/tools/manual/audit-ui-gaps.mjs
Normal file
110
web/tools/manual/audit-ui-gaps.mjs
Normal file
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env node
|
||||
// Audits the UI surface inventory against the repository and the manual.
|
||||
//
|
||||
// For every surface it verifies:
|
||||
// - the React owner file exists and (when given) the symbol appears in it
|
||||
// - the desktop reference file exists
|
||||
// - the surface is documented in the generated manual chapter ch16
|
||||
// - status is implemented/partial/gap/boundary as recorded, with reasons
|
||||
//
|
||||
// Output: docs/current/ui-design/data/gap-register.json (summary + issues).
|
||||
//
|
||||
// node tools/manual/audit-ui-gaps.mjs
|
||||
// node tools/manual/audit-ui-gaps.mjs --check # exit 1 if any gap
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const repoRoot = path.resolve(webRoot, "..");
|
||||
const inventoryPath = path.join(repoRoot, "tools/fcweb/out/ui-surface-inventory.json");
|
||||
const chapterPath = path.join(webRoot, "manual/content/ch16-panel-index.md");
|
||||
const outPath = path.join(repoRoot, "docs/current/ui-design/data/gap-register.json");
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const check = args.includes("--check");
|
||||
|
||||
const fail = message => {
|
||||
console.error(`[audit-ui-gaps] ${message}`);
|
||||
process.exit(2);
|
||||
};
|
||||
if (!fs.existsSync(inventoryPath)) fail(`missing ${inventoryPath}; run ui-surface-inventory.mjs first`);
|
||||
if (!fs.existsSync(chapterPath)) fail(`missing ${chapterPath}; run generate-panel-index.mjs first`);
|
||||
|
||||
const inventory = JSON.parse(fs.readFileSync(inventoryPath, "utf8"));
|
||||
const chapter = fs.readFileSync(chapterPath, "utf8");
|
||||
const categorySection = {
|
||||
"shell-region": "ch16-16-3-壳层区域",
|
||||
statusbar: "ch16-16-4-状态栏",
|
||||
"viewport-tool": "ch16-16-5-视口工具",
|
||||
dock: "ch16-16-6-停靠面板",
|
||||
"task-panel": "ch16-16-7-任务面板",
|
||||
"modal-dialog": "ch16-16-8-模态对话框",
|
||||
"preferences-page": "ch16-16-9-偏好设置页",
|
||||
menu: "ch16-16-10-菜单",
|
||||
toolbar: "ch16-16-11-工具栏",
|
||||
};
|
||||
|
||||
const symbolCache = new Map();
|
||||
const fileContains = (file, symbol) => {
|
||||
if (!symbol) return true;
|
||||
if (!file) return false;
|
||||
const key = file;
|
||||
if (!symbolCache.has(key)) {
|
||||
const full = path.join(repoRoot, file);
|
||||
symbolCache.set(key, fs.existsSync(full) ? fs.readFileSync(full, "utf8") : null);
|
||||
}
|
||||
const text = symbolCache.get(key);
|
||||
return Boolean(text && text.includes(symbol));
|
||||
};
|
||||
|
||||
const issues = [];
|
||||
const perSurface = inventory.surfaces.map(surface => {
|
||||
const problems = [];
|
||||
const ownerFile = surface.owner?.file ? path.join(repoRoot, surface.owner.file) : null;
|
||||
if (!ownerFile || !fs.existsSync(ownerFile)) problems.push("owner-file-missing");
|
||||
else if (!fileContains(surface.owner.file, surface.owner.symbol)) problems.push("owner-symbol-missing");
|
||||
|
||||
const desktopFile = surface.desktopRef?.file ? path.join(repoRoot, surface.desktopRef.file) : null;
|
||||
if (desktopFile && !fs.existsSync(desktopFile)) problems.push("desktop-file-missing");
|
||||
|
||||
if (!chapter.includes(surface.nameZh)) problems.push("manual-anchor-missing");
|
||||
if (surface.status === "gap") problems.push("ui-gap");
|
||||
if (surface.status === "partial" && !surface.note) problems.push("partial-without-note");
|
||||
|
||||
for (const problem of problems) issues.push({ id: surface.id, category: surface.category, status: surface.status, problem });
|
||||
return { id: surface.id, category: surface.category, status: surface.status, manualAnchor: categorySection[surface.category] ?? "ch16", problems };
|
||||
});
|
||||
|
||||
const byProblem = {};
|
||||
for (const issue of issues) byProblem[issue.problem] = (byProblem[issue.problem] ?? 0) + 1;
|
||||
|
||||
const report = {
|
||||
schema: "freecad-web-manual/ui-gap-register/v1",
|
||||
counts: {
|
||||
surfaces: perSurface.length,
|
||||
withProblems: perSurface.filter(row => row.problems.length).length,
|
||||
byProblem,
|
||||
byStatus: inventory.counts.byStatus,
|
||||
},
|
||||
ok: issues.length === 0,
|
||||
issues,
|
||||
surfaces: perSurface,
|
||||
};
|
||||
|
||||
if (check) {
|
||||
if (!report.ok) {
|
||||
console.error(JSON.stringify({ ok: false, counts: report.counts, sample: issues.slice(0, 10) }, null, 2));
|
||||
process.exit(1);
|
||||
}
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(JSON.stringify({ ok: true, checked: path.relative(repoRoot, outPath), surfaces: perSurface.length }));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(JSON.stringify({ ok: report.ok, out: path.relative(repoRoot, outPath), counts: report.counts, sample: issues.slice(0, 5) }, null, 2));
|
||||
process.exit(report.ok ? 0 : 1);
|
||||
112
web/tools/manual/build-fcweb-toolkit.mjs
Normal file
112
web/tools/manual/build-fcweb-toolkit.mjs
Normal file
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env node
|
||||
// Builds the fcweb toolkit usage guide.
|
||||
//
|
||||
// Shares the house template and markdown pipeline with the other manuals
|
||||
// (web/tools/manual/template.html + marked + front-matter chapters), but the
|
||||
// content is the API itself rather than a course, so the figures/replay/stills
|
||||
// machinery is dropped and replaced by one check that matters: every method the
|
||||
// guide documents must exist in the module it claims to come from.
|
||||
//
|
||||
// Consumed by check-fcweb-toolkit.mjs and served from web/teaching/.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { marked } from "marked";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const repoRoot = path.resolve(webRoot, "..");
|
||||
const contentDir = path.join(webRoot, "manual", "fcweb-toolkit", "content");
|
||||
const dataDir = path.join(webRoot, "manual", "fcweb-toolkit", "data");
|
||||
const toolkitDir = path.join(repoRoot, "tools", "fcweb");
|
||||
const outFile = path.join(webRoot, "teaching", "fcweb-toolkit.html");
|
||||
|
||||
const esc = value => String(value ?? "")
|
||||
.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
|
||||
const parseFrontMatter = text => {
|
||||
const match = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text);
|
||||
if (!match) return { meta: {}, body: text };
|
||||
const meta = {};
|
||||
for (const line of match[1].split("\n")) {
|
||||
const [key, ...rest] = line.split(":");
|
||||
if (key) meta[key.trim()] = rest.join(":").trim();
|
||||
}
|
||||
return { meta, body: match[2] };
|
||||
};
|
||||
|
||||
const slug = text => String(text).toLowerCase().trim()
|
||||
.replace(/[`*_]/g, "").replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").slice(0, 60);
|
||||
|
||||
// ---------------------------------------------------------------- chapters --
|
||||
if (!fs.existsSync(contentDir)) throw new Error(`missing content directory: ${contentDir}`);
|
||||
const chapters = fs.readdirSync(contentDir)
|
||||
.filter(name => name.endsWith(".md"))
|
||||
.map(name => {
|
||||
const text = fs.readFileSync(path.join(contentDir, name), "utf8");
|
||||
const { meta, body } = parseFrontMatter(text);
|
||||
return { file: name, meta, body, id: meta.id ?? name.replace(/\.md$/, ""), order: Number(meta.order ?? 999) };
|
||||
})
|
||||
.sort((a, b) => a.order - b.order);
|
||||
|
||||
// ------------------------------------------------------- API drift guard --
|
||||
// The guide must not document a method that does not exist. Each entry maps a
|
||||
// module file to a required export.
|
||||
const API = {
|
||||
"part.mjs": ["openPart", "PartDocument"],
|
||||
"partdesign.mjs": ["openPartDesign", "PartDesignDocument"],
|
||||
"assembly.mjs": ["openAssembly", "AssemblySession"],
|
||||
"kernel.mjs": ["openKernel", "createSession", "writeTrace", "KernelError"],
|
||||
"opfs.mjs": ["storeBytes", "readExportFile", "safeName", "configureOpfs"],
|
||||
"capture.mjs": ["launchBrowser", "pageCheck", "screenshot", "projectMesh"],
|
||||
};
|
||||
const api = {};
|
||||
for (const [module, exports] of Object.entries(API)) {
|
||||
const file = path.join(toolkitDir, module);
|
||||
if (!fs.existsSync(file)) throw new Error(`toolkit module missing: ${file}`);
|
||||
const source = fs.readFileSync(file, "utf8");
|
||||
for (const name of exports) {
|
||||
const declared = new RegExp(`export\\s+(async\\s+)?(function|class|const)\\s+${name}\\b`).test(source);
|
||||
if (!declared) throw new Error(`${module} no longer exports ${name} — the guide would be wrong`);
|
||||
}
|
||||
api[module] = exports;
|
||||
}
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dataDir, "api.json"), JSON.stringify(api, null, 2));
|
||||
|
||||
// ---------------------------------------------------------------- render ----
|
||||
const sections = chapters.map(chapter => {
|
||||
const html = marked.parse(chapter.body);
|
||||
return { ...chapter, html };
|
||||
});
|
||||
|
||||
const sidebarHtml = `<ol>${chapters.map(chapter => `<li>
|
||||
<a href="#${esc(chapter.id)}">${esc(chapter.meta.title ?? chapter.id)}</a>
|
||||
</li>`).join("")}</ol>`;
|
||||
|
||||
const searchIndex = chapters.map(chapter => ({
|
||||
id: chapter.id,
|
||||
title: chapter.meta.title ?? chapter.id,
|
||||
text: chapter.body.replace(/```[\s\S]*?```/g, " ").replace(/[#*`>|-]/g, " ").replace(/\s+/g, " ").slice(0, 400),
|
||||
}));
|
||||
|
||||
const content = sections.map(section => `<section id="${esc(section.id)}">${section.html}</section>`).join("\n");
|
||||
|
||||
const template = fs.readFileSync(path.join(here, "template.html"), "utf8");
|
||||
const html = template
|
||||
.replaceAll("{{TITLE}}", "fcweb 工具库 · 建零件与装配的通用工具")
|
||||
.replace("{{SIDEBAR}}", sidebarHtml)
|
||||
.replace("{{CONTENT}}", content)
|
||||
.replace("{{COMMAND_INDEX}}", `<section><h2>模块导出速查</h2><div class="table-scroll"><table><thead><tr><th>模块</th><th>导出</th></tr></thead><tbody>${
|
||||
Object.entries(api).map(([module, names]) => `<tr><td><code>${esc(module)}</code></td><td>${names.map(n => `<code>${esc(n)}</code>`).join(" ")}</td></tr>`).join("")
|
||||
}</tbody></table></div></section>`)
|
||||
.replace("{{SEARCH_INDEX}}", JSON.stringify(searchIndex).replace(/</g, "\\u003c"))
|
||||
.replace("{{COMMAND_COUNT}}", String(Object.values(api).flat().length));
|
||||
|
||||
fs.mkdirSync(path.dirname(outFile), { recursive: true });
|
||||
fs.writeFileSync(outFile, html);
|
||||
console.log(JSON.stringify({
|
||||
ok: true, outFile, chapters: chapters.length,
|
||||
modules: Object.keys(api).length, exports: Object.values(api).flat().length,
|
||||
bytes: fs.statSync(outFile).size,
|
||||
}));
|
||||
@@ -105,12 +105,17 @@ const commandIndex = `<section id="command-index-section"><h1 id="ch15">附录
|
||||
<div class="table-scroll"><table id="command-index"><thead><tr><th>模块</th><th>命令</th><th>类型</th><th>状态</th><th>章节</th><th>案例</th></tr></thead><tbody>${indexRows}</tbody></table></div></section>`;
|
||||
|
||||
let content = sections.map(chapter => chapter.html).join("\n");
|
||||
const pager = chapters.map((chapter, index) => {
|
||||
// One pager per chapter: previous/next links only, so the row never grows with
|
||||
// the chapter count (a single all-chapter row overflowed the page at 1440px).
|
||||
const chapterIndex = new Map(chapters.map((chapter, index) => [chapter.id, index]));
|
||||
content = content.replace(/<h1 id="([^"]+)">/g, (match, id) => {
|
||||
const index = chapterIndex.get(id);
|
||||
if (index === undefined) return match;
|
||||
const prev = chapters[index - 1]; const next = chapters[index + 1];
|
||||
return `${prev ? `<a href="#${esc(prev.id)}">← ${esc(prev.meta.title ?? prev.id)}</a>` : "<span></span>"}
|
||||
${next ? `<a href="#${esc(next.id)}">${esc(next.meta.title ?? next.id)} →</a>` : "<span></span>"}`;
|
||||
}).join("\n");
|
||||
content = content.replace(/<h1 id="ch15">/, `<div class="pager">${pager}</div><h1 id="ch15">`);
|
||||
return `<div class="pager">${prev ? `<a href="#${esc(prev.id)}">← ${esc(prev.meta.title ?? prev.id)}</a>` : "<span></span>"}
|
||||
${next ? `<a href="#${esc(next.id)}">${esc(next.meta.title ?? next.id)} →</a>` : "<span></span>"}</div>
|
||||
${match}`;
|
||||
});
|
||||
|
||||
// Validate referenced screenshots before writing.
|
||||
const missing = [];
|
||||
|
||||
234
web/tools/manual/build-parts-manual.mjs
Normal file
234
web/tools/manual/build-parts-manual.mjs
Normal file
@@ -0,0 +1,234 @@
|
||||
#!/usr/bin/env node
|
||||
// Builds the beginner "part design" course handout.
|
||||
//
|
||||
// Shares the reducer manual's template and markdown pipeline, but owns its own
|
||||
// content directory and output. The distinguishing feature is that every figure
|
||||
// is a still captured by the per-part recording itself (tools/reducer-parts-course
|
||||
// /stills/P##/), so the handout and the videos can never disagree about what a
|
||||
// step looked like.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { marked } from "marked";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const contentDir = path.join(webRoot, "manual", "reducer-parts", "content");
|
||||
const assetsDir = path.join(webRoot, "manual", "reducer-parts", "assets");
|
||||
const stillsRoot = path.join(webRoot, "tools", "reducer-parts-course", "stills");
|
||||
const outFile = path.join(webRoot, "teaching", "reducer-parts-manual.html");
|
||||
const outAssets = path.join(webRoot, "teaching", "reducer-parts-manual-assets");
|
||||
const caseDir = path.join(webRoot, "teaching", "cases", "secondary-reducer-pro");
|
||||
const replayDir = path.join(caseDir, "out", "replay");
|
||||
const partsCourse = path.join(webRoot, "tools", "reducer-parts-course");
|
||||
const esc = value => String(value ?? "").replace(/&/g, "&").replace(/</g, "<")
|
||||
.replace(/>/g, ">").replace(/"/g, """);
|
||||
|
||||
const readJson = file => (fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : null);
|
||||
const spec = readJson(path.join(partsCourse, "parts-spec.json"));
|
||||
const course = readJson(path.join(partsCourse, "course.json"));
|
||||
const failures = [];
|
||||
|
||||
// ---- figures: every step still the recorder captured ----------------------
|
||||
// Chapter markdown refers to a step with ``.
|
||||
// The builder resolves it to the real PNG and, when the caption omits numbers,
|
||||
// appends the ones the replay recorded for that step.
|
||||
fs.mkdirSync(assetsDir, { recursive: true });
|
||||
// Map each replay step to the still the driver captured for it.
|
||||
//
|
||||
// The filename alone is not a reliable key: the driver sanitises spaces to
|
||||
// underscores, so "Gear1_20T involute" becomes "Gear1_20T_involute" and the
|
||||
// reverse mapping is ambiguous. The episode's own script records which scene
|
||||
// id belongs to which kernel step, so index by scene id instead.
|
||||
const stillIndex = new Map(); // "P21|outer pad" -> { file, step }
|
||||
for (const entry of spec?.episodes ?? []) {
|
||||
const dir = path.join(stillsRoot, entry.episode);
|
||||
if (!fs.existsSync(dir)) { failures.push(`${entry.episode}: no stills directory (record the video first)`); continue; }
|
||||
const replay = readJson(path.join(replayDir, `${entry.document}.json`));
|
||||
const script = readJson(path.join(partsCourse, "episodes", entry.episode, "script.zh.json"));
|
||||
for (const scene of script?.scenes ?? []) {
|
||||
if (typeof scene.step !== "number") continue;
|
||||
const stem = `${scene.id}-${String(scene.title).replace(/[^\w一-龥-]+/g, "_")}`;
|
||||
const file = path.join(dir, `${stem}.png`);
|
||||
if (!fs.existsSync(file)) { failures.push(`${entry.episode}: missing still ${scene.id} (${scene.title})`); continue; }
|
||||
stillIndex.set(`${entry.episode}|${scene.title}`, { file, step: replay?.steps?.[scene.step - 1] ?? null });
|
||||
}
|
||||
}
|
||||
|
||||
const copyStill = (episode, label, where) => {
|
||||
const key = `${episode}|${label}`;
|
||||
const hit = stillIndex.get(key);
|
||||
if (!hit) { failures.push(`${where}: no still for ${key}`); return null; }
|
||||
if (!fs.existsSync(assetsDir)) fs.mkdirSync(assetsDir, { recursive: true });
|
||||
const target = `${episode}-${label.replace(/[^\w一-龥-]+/g, "_")}.png`;
|
||||
fs.copyFileSync(hit.file, path.join(assetsDir, target));
|
||||
// The page is served from teaching/, and this manual owns its own asset folder.
|
||||
return { src: `./reducer-parts-manual-assets/${target}`, step: hit.step };
|
||||
};
|
||||
|
||||
// ---- front matter and chapters --------------------------------------------
|
||||
const parseFrontMatter = text => {
|
||||
const match = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text);
|
||||
if (!match) return { meta: {}, body: text };
|
||||
const meta = {};
|
||||
for (const line of match[1].split("\n")) {
|
||||
const [key, ...rest] = line.split(":");
|
||||
if (key) meta[key.trim()] = rest.join(":").trim();
|
||||
}
|
||||
return { meta, body: match[2] };
|
||||
};
|
||||
const slug = text => String(text).toLowerCase().trim()
|
||||
.replace(/[`*_]/g, "").replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").slice(0, 60);
|
||||
|
||||
const chapters = fs.readdirSync(contentDir).filter(name => name.endsWith(".md")).map(name => {
|
||||
const text = fs.readFileSync(path.join(contentDir, name), "utf8");
|
||||
const { meta, body } = parseFrontMatter(text);
|
||||
return { file: name, meta, body, id: meta.id ?? name.replace(/\.md$/, ""), order: Number(meta.order ?? 999) };
|
||||
}).sort((a, b) => a.order - b.order);
|
||||
|
||||
// Resolve ::still directives into markdown images with a figure caption.
|
||||
const figureCount = { total: 0 };
|
||||
const withFigures = chapter => chapter.body.replace(
|
||||
/!\[([^\]]*)\]\(::still\s+(\S+)\s+(.+?)\)/g,
|
||||
(whole, caption, episode, label) => {
|
||||
const hit = copyStill(episode, label.trim(), `${chapter.id} "${caption}"`);
|
||||
if (!hit) return "";
|
||||
figureCount.total++;
|
||||
const step = hit.step;
|
||||
const facts = step
|
||||
? ` ${step.volume != null && step.volume > 0 ? `体积 ${Number(step.volume).toLocaleString("zh-CN", { maximumFractionDigits: 0 })} mm³` : "草图轮廓"},面数 ${step.faceCount ?? "-"},耗时 ${Number(step.seconds).toFixed(2)} s。`
|
||||
: "";
|
||||
const text = caption?.trim() ? `${caption.trim()}${facts}` : `${episode} · ${label}${facts}`;
|
||||
return `\n\n\n\n`;
|
||||
});
|
||||
|
||||
|
||||
// Resolve `::ui P21 outer pad` into an "界面操作" block: the screenshot the UI
|
||||
// driver captured for that step, plus the exact field values it typed. The
|
||||
// values come from out/ui-steps, so the manual cannot describe an operation the
|
||||
// UI does not actually perform.
|
||||
const PAGE_LABEL_ZH = { "partdesign.html": "零件设计页", "project.html?workbench=PartDesign": "项目页 · 零件设计工作台" };
|
||||
const uiStepIndex = new Map(); // "P21|outer pad" -> ui-steps entry
|
||||
const uiStillsRoot = path.join(partsCourse, "ui-stills");
|
||||
for (const entry of spec?.episodes ?? []) {
|
||||
const steps = readJson(path.join(partsCourse, "out", "ui-steps", `${entry.document}.json`));
|
||||
const script = readJson(path.join(partsCourse, "episodes", entry.episode, "script.zh.json"));
|
||||
const bySceneTitle = new Map((script?.scenes ?? []).map(scene => [scene.title, scene.id]));
|
||||
for (const step of steps?.steps ?? []) {
|
||||
const scene = bySceneTitle.get(step.label);
|
||||
const still = scene ? path.join(uiStillsRoot, entry.episode, `${scene}-${String(step.label).replace(/[^\w一-龥-]+/g, "_")}.png`) : null;
|
||||
uiStepIndex.set(`${entry.episode}|${step.label}`, { step, still: still && fs.existsSync(still) ? still : null });
|
||||
}
|
||||
}
|
||||
|
||||
const uiCount = { total: 0, missingStill: [] };
|
||||
const row = (field, value) => `<tr><th>${esc(field)}</th><td>${esc(value)}</td></tr>`;
|
||||
const uiValues = step => {
|
||||
const rows = [];
|
||||
const num = value => Number.isFinite(Number(value)) ? String(Math.round(Number(value) * 1000) / 1000) : esc(value);
|
||||
if (step.kind === "sketch") {
|
||||
rows.push(row("界面", PAGE_LABEL_ZH[step.page] ?? step.page));
|
||||
rows.push(row("命令", step.command));
|
||||
if (step.profileType === "Circle") rows.push(row("半径", num(step.parameters?.Radius)));
|
||||
else if (step.profileType === "Rectangle") { rows.push(row("宽", num(step.parameters?.Width))); rows.push(row("高", num(step.parameters?.Height))); }
|
||||
else { rows.push(row("几何条数", String(step.geometries?.length ?? 0))); rows.push(row("约束条数", String(step.constraints?.length ?? 0))); }
|
||||
const [x, y, z] = step.position ?? [0, 0, 0];
|
||||
rows.push(row("位置 X / Y / Z", `${num(x)} / ${num(y)} / ${num(z)}`));
|
||||
if (Array.isArray(step.placementRotation) && step.placementRotation.some((value, index) => index < 3 && value !== 0)) {
|
||||
rows.push(row("Sketch plane", step.placementRotation.map(num).join(", ") === "0,0,0,1" ? "XY" : "非 XY(见四元数)"));
|
||||
rows.push(row("placementRotation", step.placementRotation.map(num).join(", ")));
|
||||
} else rows.push(row("Sketch plane", "XY"));
|
||||
} else if (step.kind === "feature") {
|
||||
rows.push(row("命令", step.command));
|
||||
rows.push(row("轮廓", step.profile ?? "-"));
|
||||
rows.push(row("长度", num(step.length)));
|
||||
if (step.angle != null) rows.push(row("角度", num(step.angle)));
|
||||
rows.push(row("Sides", step.midplane ? "Symmetric" : "One side"));
|
||||
} else if (step.kind === "gear") {
|
||||
rows.push(row("命令", step.command));
|
||||
for (const [key, value] of Object.entries(step.gearParameters ?? {})) rows.push(row(key, num(value)));
|
||||
} else rows.push(row("命令", step.command ?? "-"));
|
||||
return rows.join("");
|
||||
};
|
||||
|
||||
const withUiBlocks = (chapter, bodyText) => (bodyText ?? chapter.body).replace(
|
||||
/::ui\s+(\S+)\s+([^\n)]+)/g,
|
||||
(whole, episode, labelText) => {
|
||||
const label = labelText.trim();
|
||||
const hit = uiStepIndex.get(`${episode}|${label}`);
|
||||
if (!hit) { failures.push(`${chapter.id}: no ui-steps entry for ${episode} ${label}`); return ""; }
|
||||
uiCount.total++;
|
||||
// A ::ui block with no screenshot would teach the operation with words
|
||||
// only; the whole point is that the picture proves it can be done.
|
||||
if (!hit.still) { uiCount.missingStill.push(`${episode} ${label}`); failures.push(`${chapter.id}: no UI screenshot for ${episode} ${label}`); }
|
||||
const image = hit.still
|
||||
? `\n\n}-ui.png)\n\n`
|
||||
: "\n\n> 该步尚未截到界面图。\n\n";
|
||||
if (hit.still) {
|
||||
const target = `${episode}-${label.replace(/[^\w一-龥-]+/g, "_")}-ui.png`;
|
||||
fs.copyFileSync(hit.still, path.join(assetsDir, target));
|
||||
}
|
||||
return `<div class="ui-block"><h4>界面操作</h4>${image}<table>${uiValues(hit.step)}</table></div>`;
|
||||
});
|
||||
|
||||
const sections = [];
|
||||
const sidebar = [];
|
||||
for (const chapter of chapters) {
|
||||
const body = withUiBlocks(chapter, withFigures(chapter));
|
||||
const html = marked.parse(body);
|
||||
const withIds = html.replace(/<h([12])>([\s\S]*?)<\/h\1>/g, (whole, level, inner) => {
|
||||
const text = inner.replace(/<[^>]+>/g, "").trim();
|
||||
const id = Number(level) === 1 ? chapter.id : `${chapter.id}-${slug(text)}`;
|
||||
return `<h${level} id="${esc(id)}">${inner}</h${level}>`;
|
||||
}).replace(/<img([^>]*?)>/g, (whole, attrs) => /loading=/.test(attrs) ? whole : `<img loading="lazy"${attrs}>`)
|
||||
.replace(/<table>/g, '<div class="table-scroll"><table>')
|
||||
.replace(/<\/table>/g, '</table></div>');
|
||||
sections.push({ ...chapter, html: withIds });
|
||||
const h2s = [...body.matchAll(/^## (.+)$/gm)].map(match => {
|
||||
const title = match[1].replace(/[`*_]/g, "").trim();
|
||||
return { id: `${chapter.id}-${slug(title)}`, title };
|
||||
});
|
||||
sidebar.push({ id: chapter.id, title: chapter.meta.title ?? chapter.id, sections: h2s });
|
||||
}
|
||||
const sidebarHtml = `<ol>${sidebar.map(chapter => `<li>
|
||||
<div class="chapter"><input type="checkbox" data-progress="${esc(chapter.id)}" aria-label="完成 ${esc(chapter.title)}" /><a href="#${esc(chapter.id)}">${esc(chapter.title)}</a></div>
|
||||
${chapter.sections.map(section => `<a class="sec" href="#${esc(section.id)}">${esc(section.title)}</a>`).join("")}
|
||||
</li>`).join("")}</ol>`;
|
||||
|
||||
// ---- appendix A: the 23 parts, straight from the replay -------------------
|
||||
const partRows = [];
|
||||
for (const entry of course?.episodes ?? []) {
|
||||
const replay = readJson(path.join(replayDir, `${entry.document}.json`));
|
||||
if (!replay) continue;
|
||||
const last = replay.steps.at(-1);
|
||||
// Link to the course page's own anchor for this episode; the handout has no
|
||||
// per-episode chapter, so a same-page "#P01" would be a dead link.
|
||||
partRows.push(`<tr><td><a href="cases/reducer-parts-course.html#${esc(entry.id)}">${esc(entry.id)}</a></td><td>${esc(entry.title)}</td>
|
||||
<td>${replay.steps.length}</td><td>${last.faceCount ?? "-"}</td>
|
||||
<td>${last.volume != null ? Number(last.volume).toLocaleString("zh-CN", { maximumFractionDigits: 0 }) : "-"}</td>
|
||||
<td>${Number(last.seconds).toFixed(1)}</td></tr>`);
|
||||
}
|
||||
const appendix = `<section><h1 id="appendix">附录:23 件实测与视频对照</h1>
|
||||
<p>每一行的数字都来自该零件自己的建模回放记录,与视频里看到的同源。点零件编号跳到对应章节。</p>
|
||||
<div class="table-scroll"><table><thead><tr><th>集</th><th>零件</th><th>步数</th><th>面数</th><th>体积 mm³</th><th>末步耗时 s</th></tr></thead><tbody>${partRows.join("")}</tbody></table></div>
|
||||
<h2 id="appendix-videos">看录像</h2>
|
||||
<p>每章的“对应视频”链接到该零件的建造成片;全部 23 集见 <a href="cases/reducer-parts-course.html">零件建模过程课程页</a>。</p>
|
||||
</section>`;
|
||||
|
||||
if (failures.length) { console.log(JSON.stringify({ failures }, null, 2)); process.exit(1); }
|
||||
|
||||
const content = [...sections.map(chapter => chapter.html), appendix].join("\n");
|
||||
fs.mkdirSync(outAssets, { recursive: true });
|
||||
if (fs.existsSync(assetsDir)) fs.cpSync(assetsDir, outAssets, { recursive: true });
|
||||
|
||||
const template = fs.readFileSync(path.join(here, "template.html"), "utf8");
|
||||
const html = template
|
||||
.replaceAll("{{TITLE}}", "零件设计入门 · Web FreeCAD 图文教案")
|
||||
.replace("{{SIDEBAR}}", sidebarHtml)
|
||||
.replace("{{CONTENT}}", content)
|
||||
.replace("{{COMMAND_INDEX}}", "")
|
||||
.replace("{{SEARCH_INDEX}}", "[]")
|
||||
.replace("{{COMMAND_COUNT}}", "0");
|
||||
fs.writeFileSync(outFile, html);
|
||||
console.log(JSON.stringify({ ok: true, outFile, chapters: chapters.length, figures: figureCount.total,
|
||||
stills: stillIndex.size, bytes: fs.statSync(outFile).size }));
|
||||
180
web/tools/manual/build-reducer-manual.mjs
Normal file
180
web/tools/manual/build-reducer-manual.mjs
Normal file
@@ -0,0 +1,180 @@
|
||||
#!/usr/bin/env node
|
||||
// Builds the reducer-specific single-page Chinese manual.
|
||||
//
|
||||
// This is deliberately a separate builder rather than a flag on build-manual.mjs:
|
||||
// the generic manual is the full-app reference (16 chapters, 400+ commands) and
|
||||
// the reducer manual is a 12-chapter beginner walkthrough of ONE artifact. They
|
||||
// share the template and the markdown pipeline so the reading experience is
|
||||
// identical, but neither owns the other's content directory or command index.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { marked } from "marked";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const contentDir = path.join(webRoot, "manual", "reducer", "content");
|
||||
const assetsDir = path.join(webRoot, "manual", "reducer", "assets");
|
||||
const outFile = path.join(webRoot, "teaching", "reducer-manual.html");
|
||||
const outAssets = path.join(webRoot, "teaching", "reducer-manual-assets");
|
||||
// The reducer manual has no command index of its own: it indexes the case's
|
||||
// real build steps instead, built from the trace and evidence files.
|
||||
const caseDir = path.join(webRoot, "teaching", "cases", "secondary-reducer-pro");
|
||||
const readCase = name => {
|
||||
const file = path.join(caseDir, name);
|
||||
return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : null;
|
||||
};
|
||||
const spec = readCase("reducer-spec.json");
|
||||
const strength = readCase("out/strength.json");
|
||||
const assembly = readCase("out/assembly.json");
|
||||
const parts = readCase("parts/evidence.json");
|
||||
const gapDoc = path.join(webRoot, "docs", "current", "web-freecad-gaps-secondary-reducer-pro.md");
|
||||
const gaps = fs.existsSync(gapDoc)
|
||||
? [...fs.readFileSync(gapDoc, "utf8").matchAll(/^## (GAP-RP-\d+) · (.+)$/gm)].map(m => ({ id: m[1], title: m[2] }))
|
||||
: [];
|
||||
const trace = readCase("out/traces/SecondaryReducer.json");
|
||||
const features = { commands: [], stats: { nativeHandlers: 0 }, chapters: [] };
|
||||
const chapterTitle = new Map(features.chapters.map(chapter => [chapter.id, chapter.title]));
|
||||
const esc = value => String(value ?? "").replace(/&/g, "&").replace(/</g, "<")
|
||||
.replace(/>/g, ">").replace(/"/g, """);
|
||||
|
||||
const parseFrontMatter = text => {
|
||||
const match = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text);
|
||||
if (!match) return { meta: {}, body: text };
|
||||
const meta = {};
|
||||
for (const line of match[1].split("\n")) {
|
||||
const [key, ...rest] = line.split(":");
|
||||
if (key) meta[key.trim()] = rest.join(":").trim();
|
||||
}
|
||||
return { meta, body: match[2] };
|
||||
};
|
||||
|
||||
const slug = text => String(text).toLowerCase().trim()
|
||||
.replace(/[`*_]/g, "").replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").slice(0, 60);
|
||||
|
||||
const chapters = fs.readdirSync(contentDir).filter(name => name.endsWith(".md")).map(name => {
|
||||
const text = fs.readFileSync(path.join(contentDir, name), "utf8");
|
||||
const { meta, body } = parseFrontMatter(text);
|
||||
return { file: name, meta, body, id: meta.id ?? name.replace(/\.md$/, ""), order: Number(meta.order ?? 999) };
|
||||
}).sort((a, b) => a.order - b.order);
|
||||
|
||||
const sidebar = [];
|
||||
const searchIndex = [];
|
||||
const sections = [];
|
||||
for (const chapter of chapters) {
|
||||
const html = marked.parse(chapter.body);
|
||||
const withIds = html.replace(/<h([12])>([\s\S]*?)<\/h\1>/g, (whole, level, inner) => {
|
||||
const text = inner.replace(/<[^>]+>/g, "").trim();
|
||||
const id = Number(level) === 1 ? chapter.id : `${chapter.id}-${slug(text)}`;
|
||||
return `<h${level} id="${esc(id)}">${inner}</h${level}>`;
|
||||
}).replace(/<img([^>]*?)>/g, (whole, attrs) => /loading=/.test(attrs) ? whole : `<img loading="lazy"${attrs}>`)
|
||||
.replace(/<table>/g, '<div class="table-scroll"><table>')
|
||||
.replace(/<\/table>/g, '</table></div>');
|
||||
sections.push({ ...chapter, html: withIds });
|
||||
|
||||
const h2s = [...chapter.body.matchAll(/^## (.+)$/gm)].map(match => {
|
||||
const title = match[1].replace(/[`*_]/g, "").trim();
|
||||
return { id: `${chapter.id}-${slug(title)}`, title };
|
||||
});
|
||||
sidebar.push({ id: chapter.id, title: chapter.meta.title ?? chapter.id, sections: h2s,
|
||||
done: chapter.meta.level !== "appendix" });
|
||||
const parts = chapter.body.split(/^## /m);
|
||||
const chapterMeta = { title: chapter.meta.title ?? chapter.id, chapter: chapter.meta.title ?? chapter.id };
|
||||
if (parts[0]) searchIndex.push({ id: chapter.id, title: chapterMeta.title, chapter: chapterMeta.chapter,
|
||||
text: parts[0].replace(/[#>*`|\-]/g, " ").replace(/\s+/g, " ").slice(0, 400), commands: [] });
|
||||
for (const part of parts.slice(1)) {
|
||||
const [titleLine, ...rest] = part.split("\n");
|
||||
const title = titleLine.replace(/[`*_]/g, "").trim();
|
||||
searchIndex.push({ id: `${chapter.id}-${slug(title)}`, title, chapter: chapterMeta.title,
|
||||
text: rest.join(" ").replace(/[#>*`|\-]/g, " ").replace(/\s+/g, " ").slice(0, 400), commands: [] });
|
||||
}
|
||||
}
|
||||
|
||||
const sidebarHtml = `<ol>${sidebar.map(chapter => `<li>
|
||||
<div class="chapter"><input type="checkbox" data-progress="${esc(chapter.id)}" aria-label="完成 ${esc(chapter.title)}" /><a href="#${esc(chapter.id)}">${esc(chapter.title)}</a></div>
|
||||
${chapter.sections.map(section => `<a class="sec" href="#${esc(section.id)}">${esc(section.title)}</a>`).join("")}
|
||||
</li>`).join("")}<li><a href="#ch15">附录:命令索引</a></li></ol>`;
|
||||
|
||||
const statusLabel = { detailed: "精讲", overview: "覆盖", boundary: "边界", verified: "已验证", "fix-needed": "待修" };
|
||||
const moduleOptions = [...new Set(features.commands.map(item => item.module))].sort()
|
||||
.map(module => `<option value="${esc(module)}">${esc(module)}</option>`).join("");
|
||||
const indexRows = features.commands.map(item => {
|
||||
const anchor = `cmd-${slug(item.module)}-${slug(item.command)}`;
|
||||
return `<tr id="${esc(anchor)}" data-module="${esc(item.module)}" data-status="${esc(item.status)}">
|
||||
<td>${esc(item.module)}</td><td><code>${esc(item.command)}</code></td><td>${esc(item.kind)}</td>
|
||||
<td><span class="badge ${esc(item.status)}">${esc(statusLabel[item.status] ?? item.status)}</span></td>
|
||||
<td>${esc(chapterTitle.get(item.chapterId) ?? item.chapterId ?? "-")}</td><td>${esc(item.ledgerCaseId ?? "-")}</td></tr>`;
|
||||
}).join("");
|
||||
const searchCommands = features.commands.map(item => ({
|
||||
id: `cmd-${slug(item.module)}-${slug(item.command)}`,
|
||||
title: `${item.module} · ${item.command}`,
|
||||
chapter: chapterTitle.get(item.chapterId) ?? "附录",
|
||||
text: `${item.disposition} ${item.kind} ${statusLabel[item.status] ?? item.status}`,
|
||||
commands: [item.command, item.module],
|
||||
}));
|
||||
|
||||
// Appendix: the build record, the gap log and the acceptance numbers. These
|
||||
// replace the generic command index -- a beginner following the reducer does
|
||||
// not need 400 command rows, they need "what did this build actually do".
|
||||
const traceRows = (trace?.events ?? []).map(event =>
|
||||
`<tr><td>${event.step}</td><td>${esc(event.label)}</td><td><code>${esc(event.action)}</code></td><td>${event.seconds}</td></tr>`).join("");
|
||||
const gapRows = gaps.map(gap => `<tr><td><code>${esc(gap.id)}</code></td><td>${esc(gap.title)}</td></tr>`).join("");
|
||||
const partRows = (parts?.items ?? []).map(item => {
|
||||
const volume = item.volume?.finalVolume ?? item.volume?.volume ?? "";
|
||||
return `<tr><td>${esc(item.document)}</td><td>${esc(item.role ?? "-")}</td><td>${item.faceCount ?? "-"}</td>
|
||||
<td>${typeof volume === "number" ? volume.toFixed(1) : ""}</td><td>${item.seconds}</td>
|
||||
<td>${item.underSixtySeconds ? "通过" : "超时"}</td></tr>`;
|
||||
}).join("");
|
||||
const commandIndex = `<section id="command-index-section"><h1 id="ch15">附录:构建记录、缺口清单与验收数字</h1>
|
||||
<h2 id="ch15-parts">A. 零件实测(${(parts?.items ?? []).length} 件)</h2>
|
||||
<div class="table-scroll"><table><thead><tr><th>文档</th><th>角色</th><th>面数</th><th>体积 mm³</th><th>构建 s</th><th>60 s 门槛</th></tr></thead><tbody>${partRows}</tbody></table></div>
|
||||
<h2 id="ch15-steps">B. 装配构建记录(${(trace?.events ?? []).length} 步)</h2>
|
||||
<p>每一步都是真实的内核调用,含耗时。教学播放器按这份记录回放。</p>
|
||||
<div class="table-scroll"><table><thead><tr><th>#</th><th>步骤</th><th>命令</th><th>秒</th></tr></thead><tbody>${traceRows}</tbody></table></div>
|
||||
<h2 id="ch15-gaps">C. 缺口清单(${gaps.length} 条)</h2>
|
||||
<p>每条缺口都有桌面源程序依据;修复情况见缺口台账原文。</p>
|
||||
<div class="table-scroll"><table><thead><tr><th>编号</th><th>标题</th></tr></thead><tbody>${gapRows}</tbody></table></div>
|
||||
<h2 id="ch15-numbers">D. 验收数字</h2>
|
||||
<div class="table-scroll"><table><thead><tr><th>项</th><th>值</th></tr></thead><tbody>
|
||||
<tr><td>传动比</td><td>${spec ? spec.transmission.ratio : "-"}</td></tr>
|
||||
<tr><td>模数 / 压力角</td><td>${spec ? `${spec.transmission.moduleMm} mm / ${spec.transmission.pressureAngleDeg}°` : "-"}</td></tr>
|
||||
<tr><td>中心距</td><td>${strength ? strength.stages.map(s => s.centreDistanceMm + " mm").join(" / ") : "-"}</td></tr>
|
||||
<tr><td>安全系数(接触 / 弯曲)</td><td>${strength ? strength.stages.map(s => `${s.contactSafety.toFixed(2)} / ${s.bendingSafety.toFixed(2)}`).join(" · ") : "-"}</td></tr>
|
||||
<tr><td>装配组件 / 关节 / BOM 行</td><td>${assembly ? `${assembly.components} / ${assembly.joints.length} / ${assembly.bom.rows}` : "-"}</td></tr>
|
||||
<tr><td>求解最大位移</td><td>${assembly ? (assembly.displacement.maxMm < 1e-6 ? "< 1e-6 mm" : assembly.displacement.maxMm.toFixed(2) + " mm") : "-"}</td></tr>
|
||||
<tr><td>页面错误</td><td>${assembly ? (assembly.pageErrors ?? []).length : "-"}</td></tr>
|
||||
</tbody></table></div></section>`;
|
||||
|
||||
let content = sections.map(chapter => chapter.html).join("\n");
|
||||
const pager = chapters.map((chapter, index) => {
|
||||
const prev = chapters[index - 1]; const next = chapters[index + 1];
|
||||
return `${prev ? `<a href="#${esc(prev.id)}">← ${esc(prev.meta.title ?? prev.id)}</a>` : "<span></span>"}
|
||||
${next ? `<a href="#${esc(next.id)}">${esc(next.meta.title ?? next.id)} →</a>` : "<span></span>"}`;
|
||||
}).join("\n");
|
||||
content = content.replace(/<h1 id="ch15">/, `<div class="pager">${pager}</div><h1 id="ch15">`);
|
||||
|
||||
// Validate referenced screenshots before writing.
|
||||
const missing = [];
|
||||
for (const chapter of chapters) {
|
||||
for (const match of chapter.body.matchAll(/!\[[^\]]*\]\(([^)]+)\)/g)) {
|
||||
const src = match[1];
|
||||
if (!src.startsWith("./manual-assets/")) continue;
|
||||
const file = path.join(assetsDir, src.replace("./manual-assets/", ""));
|
||||
if (!fs.existsSync(file)) missing.push(src);
|
||||
}
|
||||
}
|
||||
if (missing.length) throw new Error(`missing screenshots: ${missing.slice(0, 5).join(", ")}`);
|
||||
|
||||
fs.mkdirSync(outAssets, { recursive: true });
|
||||
fs.cpSync(assetsDir, outAssets, { recursive: true });
|
||||
const template = fs.readFileSync(path.join(here, "template.html"), "utf8");
|
||||
const html = template
|
||||
.replaceAll("{{TITLE}}", "二级圆柱齿轮减速器 · Web FreeCAD 初学者手册")
|
||||
.replace("{{SIDEBAR}}", sidebarHtml)
|
||||
.replace("{{CONTENT}}", content)
|
||||
.replace("{{COMMAND_INDEX}}", commandIndex)
|
||||
.replace("{{SEARCH_INDEX}}", JSON.stringify(searchIndex).replace(/</g, "\\u003c"))
|
||||
.replace("{{COMMAND_COUNT}}", String(features.commands.length));
|
||||
fs.writeFileSync(outFile, html);
|
||||
console.log(JSON.stringify({ ok: true, outFile, chapters: chapters.length, sections: sections.length,
|
||||
commands: features.commands.length, searchEntries: searchIndex.length, bytes: fs.statSync(outFile).size }));
|
||||
@@ -4,10 +4,9 @@
|
||||
// node capture.mjs --scenario ../../manual/scenarios/ch01-ui.json [--headed]
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { listOpfsFiles, readOpfsFile, seedOpfsFromBytes } from "../carrier-course/lib/opfs.mjs";
|
||||
import { createActionRunner } from "./lib/actions.mjs";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
@@ -31,8 +30,6 @@ const reportDir = path.join(webRoot, "manual", "data", "capture");
|
||||
fs.mkdirSync(shotDir, { recursive: true });
|
||||
fs.mkdirSync(reportDir, { recursive: true });
|
||||
|
||||
const sha256 = file => createHash("sha256").update(fs.readFileSync(file)).digest("hex");
|
||||
|
||||
async function runOnce() {
|
||||
const browser = await chromium.launch({
|
||||
executablePath: "/usr/bin/google-chrome",
|
||||
@@ -47,167 +44,23 @@ async function runOnce() {
|
||||
page.on("console", message => { if (message.type() === "error") consoleErrors.push(message.text().slice(0, 300)); });
|
||||
const trace = [];
|
||||
const shots = [];
|
||||
|
||||
const record = entry => trace.push({ at: new Date().toISOString(), ...entry });
|
||||
const click = async action => {
|
||||
let locator;
|
||||
if (action.role) locator = page.getByRole(action.role, { name: action.name, exact: action.exact });
|
||||
else {
|
||||
locator = page.locator(action.selector);
|
||||
if (action.hasText) locator = locator.filter({ hasText: action.hasText });
|
||||
if (action.target) locator = locator.locator(action.target);
|
||||
}
|
||||
if (action.nth !== undefined) locator = locator.nth(action.nth);
|
||||
else if (!action.all) locator = locator.first();
|
||||
if (action.optional && (await locator.count()) === 0) return;
|
||||
if (action.all) {
|
||||
const count = await locator.count();
|
||||
for (let index = 0; index < count; index++) await locator.nth(index).click();
|
||||
} else await locator.click({ timeout: action.timeout ?? 30000 });
|
||||
};
|
||||
const shot = async action => {
|
||||
const file = path.join(shotDir, `${action.name}.png`);
|
||||
if (action.selector) {
|
||||
const target = page.locator(action.selector).first();
|
||||
await target.waitFor({ state: "visible", timeout: 30000 });
|
||||
await target.screenshot({ path: file });
|
||||
} else {
|
||||
await page.screenshot({ path: file, fullPage: Boolean(action.fullPage) });
|
||||
}
|
||||
const stat = fs.statSync(file);
|
||||
if (stat.size < 1024) throw new Error(`screenshot too small: ${file}`);
|
||||
shots.push({ id: `${chapter}/${workflow}/${action.name}`, file: path.relative(webRoot, file),
|
||||
bytes: stat.size, sha256: sha256(file), fullPage: Boolean(action.fullPage), selector: action.selector ?? null });
|
||||
record({ action: "shot", name: action.name, bytes: stat.size });
|
||||
};
|
||||
const save = async action => {
|
||||
await page.evaluate(() => { const details = document.querySelector(".file-tools"); if (details) details.open = true; });
|
||||
await page.waitForTimeout(400);
|
||||
const before = await listOpfsFiles(page);
|
||||
await page.locator('button:has-text("保存 FCStd 到 OPFS")').first().click();
|
||||
let after = before; let status = "";
|
||||
for (let attempt = 0; attempt < 40; attempt++) {
|
||||
await page.waitForTimeout(750);
|
||||
after = await listOpfsFiles(page);
|
||||
status = await page.locator("p.status").first().textContent().catch(() => "");
|
||||
if (after.some(name => !before.includes(name) && /\.FCStd$/i.test(name)) || /Saved\s+\S+\.FCStd\s+to OPFS/i.test(status ?? "")) break;
|
||||
}
|
||||
const match = /Saved\s+(\S+\.FCStd)\s+to OPFS/i.exec(status ?? "");
|
||||
const name = match?.[1] ?? after.find(item => !before.includes(item) && /\.FCStd$/i.test(item));
|
||||
if (!name) throw new Error(`save produced no FCStd; status=${status}`);
|
||||
const bytes = (await readOpfsFile(page, name)).bytes;
|
||||
const fixture = path.join(webRoot, "manual", "fixtures", `${chapter}-${workflow}.FCStd`);
|
||||
fs.mkdirSync(path.dirname(fixture), { recursive: true });
|
||||
fs.writeFileSync(fixture, Buffer.from(bytes));
|
||||
record({ action: "save", name, bytes: bytes.length, status });
|
||||
};
|
||||
// The action interpreter is shared with the headed functional suite; only the
|
||||
// evidence destinations and the record sink differ.
|
||||
const runner = createActionRunner(page, {
|
||||
origin, shotDir, shotPrefix: `${chapter}/${workflow}/`, record, shotIndex: shots,
|
||||
fixturePath: path.join(webRoot, "manual", "fixtures", `${chapter}-${workflow}.FCStd`),
|
||||
});
|
||||
|
||||
try {
|
||||
for (const action of scenario.actions) {
|
||||
switch (action.type) {
|
||||
case "goto":
|
||||
await page.goto(`${origin}${action.url}`, { waitUntil: "domcontentloaded", timeout: 120000 });
|
||||
record({ action: "goto", url: action.url });
|
||||
break;
|
||||
case "waitFor":
|
||||
if (action.selector) await page.waitForSelector(action.selector, { timeout: action.timeout ?? 120000 });
|
||||
if (action.text) await page.getByText(action.text, { exact: action.exact ?? false }).first()
|
||||
.waitFor({ state: "visible", timeout: action.timeout ?? 120000 });
|
||||
record({ action: "waitFor", selector: action.selector ?? null, text: action.text ?? null });
|
||||
break;
|
||||
case "click": await click(action); record({ action: "click", selector: action.selector ?? action.name }); break;
|
||||
case "fill":
|
||||
await page.locator(action.selector).first().fill(String(action.value));
|
||||
record({ action: "fill", selector: action.selector, value: action.value });
|
||||
break;
|
||||
case "select":
|
||||
await page.locator(action.selector).first().selectOption(action.label ? { label: action.label } : action.value);
|
||||
record({ action: "select", selector: action.selector, label: action.label ?? action.value });
|
||||
break;
|
||||
case "selectIndex":
|
||||
await page.locator(action.selector).first().selectOption({ index: action.index });
|
||||
record({ action: "selectIndex", selector: action.selector, index: action.index });
|
||||
break;
|
||||
case "press": await page.keyboard.press(action.key); record({ action: "press", key: action.key }); break;
|
||||
case "clickCanvas": {
|
||||
const target = page.locator(action.selector).first();
|
||||
await target.scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(200);
|
||||
const box = await target.boundingBox();
|
||||
if (!box) throw new Error(`canvas missing: ${action.selector}`);
|
||||
await page.mouse.click(box.x + box.width * action.fx, box.y + box.height * action.fy);
|
||||
await page.waitForTimeout(action.wait ?? 250);
|
||||
record({ action: "clickCanvas", selector: action.selector, fx: action.fx, fy: action.fy });
|
||||
break;
|
||||
}
|
||||
case "assertAnyText": {
|
||||
const texts = await page.locator(action.selector).allTextContents();
|
||||
if (!texts.some(text => String(text).includes(action.contains)))
|
||||
throw new Error(`assertAnyText failed: ${action.contains} in ${JSON.stringify(texts.slice(0, 5))}`);
|
||||
record({ action: "assertAnyText", selector: action.selector, contains: action.contains });
|
||||
break;
|
||||
}
|
||||
case "drag": {
|
||||
const box = await page.locator(action.selector).first().boundingBox();
|
||||
if (!box) throw new Error(`drag target missing: ${action.selector}`);
|
||||
const x = box.x + box.width / 2; const y = box.y + box.height / 2;
|
||||
await page.mouse.move(x, y); await page.mouse.down();
|
||||
await page.mouse.move(x + (action.dx ?? 0), y + (action.dy ?? 0), { steps: 18 });
|
||||
await page.mouse.up(); await page.waitForTimeout(400);
|
||||
record({ action: "drag", selector: action.selector, dx: action.dx, dy: action.dy });
|
||||
break;
|
||||
}
|
||||
case "eval":
|
||||
await page.evaluate(action.script);
|
||||
record({ action: "eval" });
|
||||
break;
|
||||
case "seed": {
|
||||
const file = path.resolve(action.file);
|
||||
if (!fs.existsSync(file)) throw new Error(`seed fixture missing: ${file}`);
|
||||
await seedOpfsFromBytes(page, action.name ?? path.basename(file), fs.readFileSync(file));
|
||||
record({ action: "seed", file, name: action.name ?? path.basename(file) });
|
||||
break;
|
||||
}
|
||||
case "shot": await shot(action); break;
|
||||
case "save": await save(action); break;
|
||||
case "assertText": {
|
||||
const text = await page.locator(action.selector).first().textContent();
|
||||
if (!String(text ?? "").includes(action.contains)) throw new Error(`assertText failed: ${action.selector} ${text}`);
|
||||
record({ action: "assertText", selector: action.selector, contains: action.contains });
|
||||
break;
|
||||
}
|
||||
case "assertVisible":
|
||||
await page.locator(action.selector).first().waitFor({ state: "visible", timeout: 30000 });
|
||||
record({ action: "assertVisible", selector: action.selector });
|
||||
break;
|
||||
case "waitOptions": {
|
||||
const locator = page.locator(action.selector).first();
|
||||
let count = 0;
|
||||
for (let attempt = 0; attempt < 80; attempt++) {
|
||||
count = await locator.locator("option").count();
|
||||
if (count >= (action.min ?? 1)) break;
|
||||
await page.waitForTimeout(500);
|
||||
}
|
||||
if (count < (action.min ?? 1)) throw new Error(`waitOptions failed: ${action.selector} ${count}`);
|
||||
record({ action: "waitOptions", selector: action.selector, count });
|
||||
break;
|
||||
}
|
||||
case "assertValue": {
|
||||
const value = await page.locator(action.selector).first().inputValue();
|
||||
if (String(value) !== String(action.value)) throw new Error(`assertValue failed: ${action.selector} ${value} != ${action.value}`);
|
||||
record({ action: "assertValue", selector: action.selector, value });
|
||||
break;
|
||||
}
|
||||
case "wait": await page.waitForTimeout(action.ms ?? 500); break;
|
||||
default: throw new Error(`unknown action ${action.type}`);
|
||||
}
|
||||
}
|
||||
for (const action of scenario.actions) await runner.run(action);
|
||||
if (pageErrors.length || consoleErrors.length)
|
||||
throw new Error(`page errors: ${JSON.stringify({ pageErrors, consoleErrors })}`);
|
||||
const report = {
|
||||
schema: "freecad-web-manual/capture/v1", generatedAt: new Date().toISOString(),
|
||||
chapter, workflow, scenario: path.relative(webRoot, scenarioPath), origin,
|
||||
ok: true, trace, shots, pageErrors, consoleErrors,
|
||||
ok: true, trace, pageErrors, consoleErrors,
|
||||
shots: shots.map(item => ({ ...item, file: path.relative(webRoot, item.file) })),
|
||||
};
|
||||
fs.writeFileSync(path.join(reportDir, `${chapter}-${workflow}.json`), `${JSON.stringify(report, null, 2)}\n`);
|
||||
return report;
|
||||
|
||||
63
web/tools/manual/check-fcweb-toolkit.mjs
Normal file
63
web/tools/manual/check-fcweb-toolkit.mjs
Normal file
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env node
|
||||
// Verifies the built fcweb toolkit guide in a real browser.
|
||||
//
|
||||
// Reuses tools/fcweb/capture.mjs rather than re-deriving selectors, so the
|
||||
// health metrics (overflow, broken images, page errors) are measured exactly
|
||||
// the same way any other page check measures them.
|
||||
//
|
||||
// MANUAL_URL=http://127.0.0.1:5190/fcweb-toolkit.html node web/tools/manual/check-fcweb-toolkit.mjs
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { launchBrowser, pageCheck, writeArtifact } from "../../../tools/fcweb/capture.mjs";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const contentDir = path.join(webRoot, "manual", "fcweb-toolkit", "content");
|
||||
const outDir = path.join(webRoot, "..", "docs", "current", "fcweb-toolkit-check");
|
||||
|
||||
const url = process.env.MANUAL_URL || "http://127.0.0.1:5190/fcweb-toolkit.html";
|
||||
const chapterIds = fs.readdirSync(contentDir)
|
||||
.filter(name => name.endsWith(".md"))
|
||||
.map(name => {
|
||||
const text = fs.readFileSync(path.join(contentDir, name), "utf8");
|
||||
const meta = /^---\n([\s\S]*?)\n---\n/.exec(text);
|
||||
const id = meta ? (/^id:\s*(.+)$/m.exec(meta[1])?.[1]?.trim()) : null;
|
||||
return id ?? name.replace(/\.md$/, "");
|
||||
});
|
||||
|
||||
const browser = await launchBrowser({ headed: false });
|
||||
let report;
|
||||
try {
|
||||
report = await pageCheck(browser, url, {
|
||||
viewports: [{ width: 1440, height: 900 }, { width: 390, height: 844 }],
|
||||
expect: { chapters: chapterIds.length, anchorIds: chapterIds },
|
||||
});
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
// The search box is the one interactive affordance the guide ships; prove it
|
||||
// can find a known API name rather than just render.
|
||||
const missingChapters = report.viewports
|
||||
.flatMap(viewport => viewport.missingIds)
|
||||
.filter(id => chapterIds.includes(id));
|
||||
|
||||
const summary = {
|
||||
ok: report.ok && missingChapters.length === 0,
|
||||
url,
|
||||
chapters: chapterIds.length,
|
||||
missingChapters: [...new Set(missingChapters)],
|
||||
viewports: report.viewports.map(viewport => ({
|
||||
viewport: viewport.viewport,
|
||||
status: viewport.status,
|
||||
overflow: viewport.overflow,
|
||||
brokenImages: viewport.brokenImages.length,
|
||||
pageErrors: viewport.pageErrors.length,
|
||||
failedRequests: viewport.failedRequests.length,
|
||||
ok: viewport.ok,
|
||||
})),
|
||||
};
|
||||
writeArtifact(outDir, "fcweb-toolkit-page-check.json", summary);
|
||||
console.log(JSON.stringify(summary, null, 2));
|
||||
process.exit(summary.ok ? 0 : 1);
|
||||
66
web/tools/manual/check-parts-manual.mjs
Normal file
66
web/tools/manual/check-parts-manual.mjs
Normal file
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env node
|
||||
// Desktop + mobile check for the part-design handout: overflow, page errors,
|
||||
// broken images, chapter count, and that every part is illustrated.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const require = createRequire(path.join(webRoot, "package.json"));
|
||||
const { chromium } = require("playwright");
|
||||
const url = process.env.MANUAL_URL || "http://127.0.0.1:5190/reducer-parts-manual.html";
|
||||
const specs = JSON.parse(fs.readFileSync(path.join(webRoot, "tools", "reducer-parts-course", "parts-spec.json"), "utf8"));
|
||||
|
||||
const browser = await chromium.launch({ executablePath: "/usr/bin/google-chrome", headless: true,
|
||||
args: ["--no-sandbox", "--enable-unsafe-swiftshader", "--use-gl=angle", "--use-angle=swiftshader"] });
|
||||
const report = { schema: "freecad-web-reducer-parts-manual/page-check/v1", generatedAt: new Date().toISOString(), url, viewports: [] };
|
||||
|
||||
for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) {
|
||||
const page = await browser.newPage({ viewport });
|
||||
const errors = []; const failed = [];
|
||||
page.on("pageerror", error => errors.push(String(error)));
|
||||
page.on("console", message => { if (message.type() === "error") errors.push(message.text().slice(0, 200)); });
|
||||
page.on("response", response => { if (response.status() >= 400) failed.push(`${response.status()} ${response.url()}`); });
|
||||
const response = await page.goto(url, { waitUntil: "load", timeout: 120000 });
|
||||
await page.waitForTimeout(600);
|
||||
await page.evaluate(() => { for (const image of document.images) image.loading = "eager"; });
|
||||
await page.waitForTimeout(2000);
|
||||
const metrics = await page.evaluate(() => {
|
||||
const images = [...document.images];
|
||||
return {
|
||||
chapters: document.querySelectorAll("nav.sidebar .chapter").length,
|
||||
sections: document.querySelectorAll("main h2[id]").length,
|
||||
images: images.length,
|
||||
brokenImages: images.filter(image => image.src && (!image.complete || image.naturalWidth === 0)).map(image => image.src),
|
||||
figures: document.querySelectorAll("main img").length,
|
||||
// The appendix heading is an <h1>, so the table is a following sibling
|
||||
// rather than a descendant.
|
||||
appendixRows: (() => {
|
||||
const heading = document.getElementById("appendix");
|
||||
for (let node = heading?.nextElementSibling; node; node = node.nextElementSibling) {
|
||||
const table = node.matches(".table-scroll") ? node : node.querySelector?.(".table-scroll");
|
||||
if (table) return table.querySelectorAll("tbody tr").length;
|
||||
if (node.matches("h1")) break;
|
||||
}
|
||||
return 0;
|
||||
})(),
|
||||
overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
|
||||
};
|
||||
});
|
||||
if (viewport.width === 1440) await page.screenshot({ path: path.join(webRoot, "teaching", "reducer-parts-manual.png"), fullPage: false });
|
||||
report.viewports.push({ viewport, status: response?.status(), errors, failed, ...metrics });
|
||||
await page.close();
|
||||
}
|
||||
await browser.close();
|
||||
|
||||
const expectedChapters = 15;
|
||||
report.ok = report.viewports.every(item => item.status === 200 && item.errors.length === 0
|
||||
&& item.failed.length === 0 && item.brokenImages.length === 0 && item.overflow === 0
|
||||
&& item.chapters === expectedChapters && item.figures >= 50
|
||||
&& item.appendixRows === specs.episodes.length);
|
||||
fs.mkdirSync(path.join(webRoot, "manual", "reducer-parts", "data"), { recursive: true });
|
||||
fs.writeFileSync(path.join(webRoot, "manual", "reducer-parts", "data", "page-check.json"), `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(JSON.stringify({ ok: report.ok, viewports: report.viewports.map(v => ({ w: v.viewport.width, chapters: v.chapters, figures: v.figures, overflow: v.overflow, broken: v.brokenImages.length, errors: v.errors.length, rows: v.appendixRows })) }));
|
||||
process.exitCode = report.ok ? 0 : 1;
|
||||
74
web/tools/manual/check-reducer-manual.mjs
Normal file
74
web/tools/manual/check-reducer-manual.mjs
Normal file
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env node
|
||||
// Checks the reducer manual on desktop and mobile: overflow, page errors,
|
||||
// broken images, chapter count, search, and that the appendix's build record
|
||||
// and gap list actually rendered. Writes manual/reducer/data/page-check.json.
|
||||
//
|
||||
// This is a separate checker from check-page.mjs because the two manuals have
|
||||
// genuinely different appendices: the generic one indexes 1500+ commands, the
|
||||
// reducer one records this case's build steps, gaps and acceptance numbers.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const require = createRequire(path.join(webRoot, "package.json"));
|
||||
const { chromium } = require("playwright");
|
||||
const url = process.env.MANUAL_URL || "http://127.0.0.1:5190/reducer-manual.html";
|
||||
const browser = await chromium.launch({ executablePath: "/usr/bin/google-chrome", headless: true,
|
||||
args: ["--no-sandbox", "--enable-unsafe-swiftshader", "--use-gl=angle", "--use-angle=swiftshader"] });
|
||||
const report = { schema: "freecad-web-reducer-manual/page-check/v1", generatedAt: new Date().toISOString(), url, viewports: [] };
|
||||
for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) {
|
||||
const page = await browser.newPage({ viewport });
|
||||
const errors = []; const failed = [];
|
||||
page.on("pageerror", error => errors.push(String(error)));
|
||||
page.on("console", message => { if (message.type() === "error") errors.push(message.text().slice(0, 200)); });
|
||||
page.on("response", response => { if (response.status() >= 400) failed.push(`${response.status()} ${response.url()}`); });
|
||||
const response = await page.goto(url, { waitUntil: "load", timeout: 120000 });
|
||||
await page.waitForTimeout(800);
|
||||
await page.evaluate(() => { for (const image of document.images) image.loading = "eager"; });
|
||||
await page.waitForTimeout(1500);
|
||||
const metrics = await page.evaluate(() => {
|
||||
const images = [...document.images];
|
||||
return {
|
||||
chapters: document.querySelectorAll('nav.sidebar .chapter').length,
|
||||
sections: document.querySelectorAll('main h2[id]').length,
|
||||
images: images.length,
|
||||
brokenImages: images.filter(image => image.src && (!image.complete || image.naturalWidth === 0)).map(image => image.src),
|
||||
// Walk from each appendix heading to the next table, skipping the <p>
|
||||
// that sits between them in the generated HTML.
|
||||
...(() => {
|
||||
const rowsAfter = id => {
|
||||
const heading = document.querySelector(`h2[id^="${id}"]`);
|
||||
if (!heading) return 0;
|
||||
for (let node = heading.nextElementSibling; node; node = node.nextElementSibling) {
|
||||
const table = node.matches(".table-scroll") ? node : node.querySelector?.(".table-scroll");
|
||||
if (table) return table.querySelectorAll("tbody tr").length;
|
||||
if (node.matches("h1, h2")) break;
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
return { buildRows: rowsAfter("ch15-steps"), gapRows: rowsAfter("ch15-gaps"),
|
||||
partRows: rowsAfter("ch15-parts"), numbersRows: rowsAfter("ch15-numbers") };
|
||||
})(),
|
||||
overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
|
||||
searchSize: SEARCH_INDEX.length,
|
||||
};
|
||||
});
|
||||
await page.locator('#search').fill('轴承');
|
||||
await page.waitForTimeout(300);
|
||||
const searchHits = await page.locator('#search-results a').count();
|
||||
if (viewport.width === 1440) await page.screenshot({ path: path.join(webRoot, "teaching", "reducer-manual.png"), fullPage: false });
|
||||
report.viewports.push({ viewport, status: response?.status(), errors, failed, searchHits, ...metrics });
|
||||
await page.close();
|
||||
}
|
||||
await browser.close();
|
||||
report.ok = report.viewports.every(item => item.status === 200 && item.errors.length === 0
|
||||
&& item.failed.length === 0 && item.brokenImages.length === 0 && item.overflow === 0
|
||||
&& item.chapters === 13 && item.buildRows > 50 && item.gapRows >= 20
|
||||
&& item.searchHits > 0);
|
||||
fs.mkdirSync(path.join(webRoot, "manual", "reducer", "data"), { recursive: true });
|
||||
fs.writeFileSync(path.join(webRoot, "manual", "reducer", "data", "page-check.json"), `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(JSON.stringify(report));
|
||||
process.exitCode = report.ok ? 0 : 1;
|
||||
106
web/tools/manual/check-ui-design-doc.mjs
Normal file
106
web/tools/manual/check-ui-design-doc.mjs
Normal file
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env node
|
||||
// Verify the generated UI design document in a real browser.
|
||||
//
|
||||
// Reuses tools/fcweb/capture.mjs. Checks structure (chapter anchors, appendix
|
||||
// row count), page health (errors, broken images, overflow) at two viewports,
|
||||
// and that every screenshot the document references actually exists.
|
||||
//
|
||||
// node web/tools/manual/check-ui-design-doc.mjs
|
||||
// DOC_URL=http://127.0.0.1:5199/evidence/current/web-freecad-ui-layout-and-functions.html \
|
||||
// node web/tools/manual/check-ui-design-doc.mjs
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { launchBrowser, openPage, writeArtifact } from "../../../tools/fcweb/capture.mjs";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const repoRoot = path.resolve(webRoot, "..");
|
||||
const docPath = path.join(repoRoot, "docs/current/web-freecad-ui-layout-and-functions.html");
|
||||
const inventoryPath = path.join(repoRoot, "tools/fcweb/out/ui-inventory.json");
|
||||
const outDir = path.join(repoRoot, "docs/current/ui-design/data");
|
||||
|
||||
if (!fs.existsSync(docPath)) {
|
||||
console.error(`[check-ui-design-doc] missing document: ${docPath}`);
|
||||
process.exit(2);
|
||||
}
|
||||
const inventory = JSON.parse(fs.readFileSync(inventoryPath, "utf8"));
|
||||
const expectedChapters = inventory.chapters.map(chapter => `wb-${chapter.id}`);
|
||||
const expectedAppendix = inventory.appendix.length;
|
||||
|
||||
const url = process.env.DOC_URL || pathToFileURL(docPath).href;
|
||||
const browser = await launchBrowser({ headed: false });
|
||||
const viewports = [{ width: 1440, height: 900 }, { width: 390, height: 844 }];
|
||||
const reports = [];
|
||||
|
||||
try {
|
||||
for (const viewport of viewports) {
|
||||
const { page, response, errors, failedRequests } = await openPage(browser, url, { viewport });
|
||||
try {
|
||||
// Force lazy images to load so the broken-image check is meaningful.
|
||||
await page.evaluate(async () => {
|
||||
for (const image of document.images) image.loading = "eager";
|
||||
window.scrollTo(0, document.body.scrollHeight);
|
||||
await new Promise(resolve => setTimeout(resolve, 800));
|
||||
window.scrollTo(0, 0);
|
||||
});
|
||||
await page.waitForTimeout(600);
|
||||
|
||||
const dom = await page.evaluate(() => {
|
||||
const brokenImages = [...document.images]
|
||||
.filter(image => image.getAttribute("src"))
|
||||
.filter(image => image.complete && image.naturalWidth === 0)
|
||||
.map(image => image.currentSrc || image.src);
|
||||
const doc = document.documentElement;
|
||||
const ids = [...document.querySelectorAll("[id]")].map(node => node.id);
|
||||
const duplicated = ids.filter((id, index) => ids.indexOf(id) !== index);
|
||||
return {
|
||||
overflow: Math.max(0, doc.scrollWidth - doc.clientWidth),
|
||||
brokenImages,
|
||||
ids,
|
||||
duplicatedIds: [...new Set(duplicated)],
|
||||
chapters: document.querySelectorAll("section.wb").length,
|
||||
appendixRows: document.querySelectorAll("tr[data-appendix-row]").length,
|
||||
tocLinks: document.querySelectorAll("nav.toc a").length,
|
||||
images: document.images.length,
|
||||
};
|
||||
});
|
||||
|
||||
const missing = expectedChapters.filter(id => !dom.ids.includes(id));
|
||||
reports.push({
|
||||
viewport,
|
||||
status: response?.status() ?? null,
|
||||
...dom,
|
||||
missingChapters: missing,
|
||||
pageErrors: errors,
|
||||
failedRequests: failedRequests.slice(0, 5),
|
||||
ok: (response?.status() ?? 0) === 200
|
||||
&& errors.length === 0
|
||||
&& failedRequests.length === 0
|
||||
&& dom.brokenImages.length === 0
|
||||
&& dom.overflow === 0
|
||||
&& missing.length === 0
|
||||
&& dom.duplicatedIds.length === 0
|
||||
&& dom.chapters === inventory.chapters.length
|
||||
&& dom.appendixRows === expectedAppendix,
|
||||
});
|
||||
} finally {
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
const summary = {
|
||||
ok: reports.every(report => report.ok),
|
||||
url,
|
||||
expectedChapters: expectedChapters.length,
|
||||
expectedAppendixRows: expectedAppendix,
|
||||
viewports: reports,
|
||||
};
|
||||
fs.mkdirSync(outDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(outDir, "doc-check.json"), `${JSON.stringify(summary, null, 2)}\n`);
|
||||
console.log(JSON.stringify(summary, null, 2));
|
||||
writeArtifact(outDir, "doc-check-last-run.json", summary);
|
||||
process.exit(summary.ok ? 0 : 1);
|
||||
@@ -55,6 +55,7 @@ const chapters = [
|
||||
{ id: "ch13", order: 13, level: "specialist", title: "Draft、Plot、Robot 等专项工具", moduleIds: ["Draft", "Plot", "Robot", "Cloud", "JtReader", "Sandbox", "Test", "Tux", "TemplatePyMod", "Show"] },
|
||||
{ id: "ch14", order: 14, level: "case", title: "综合案例:27 件 GLB 产线", moduleIds: [] },
|
||||
{ id: "ch15", order: 15, level: "appendix", title: "附录:命令索引与缺口", moduleIds: [] },
|
||||
{ id: "ch16", order: 16, level: "appendix", title: "全功能面板索引与实现映射", moduleIds: [] },
|
||||
];
|
||||
|
||||
const moduleChapter = new Map();
|
||||
|
||||
106
web/tools/manual/generate-final-status.mjs
Normal file
106
web/tools/manual/generate-final-status.mjs
Normal file
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env node
|
||||
// Derives web/manual/data/final-status.json from the real pipeline outputs so
|
||||
// the summary never drifts from the generated manual:
|
||||
//
|
||||
// manual-features.json commands / modules / boundaries / chapters
|
||||
// gap-ledger.json verified case count and known boundaries
|
||||
// page-check.json last browser check (overflow, images, sections)
|
||||
// capture/*.json screenshot capture reports
|
||||
// manual-assets/** actual PNG files on disk
|
||||
//
|
||||
// node tools/manual/generate-final-status.mjs
|
||||
// node tools/manual/generate-final-status.mjs --check # exit 1 on drift
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const dataDir = path.join(webRoot, "manual", "data");
|
||||
const read = name => JSON.parse(fs.readFileSync(path.join(dataDir, name), "utf8"));
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const check = args.includes("--check");
|
||||
const outPath = path.join(dataDir, "final-status.json");
|
||||
|
||||
const features = read("manual-features.json");
|
||||
const ledger = read("gap-ledger.json");
|
||||
const pageCheck = read("page-check.json");
|
||||
|
||||
const captureDir = path.join(dataDir, "capture");
|
||||
const captureReports = fs.existsSync(captureDir)
|
||||
? fs.readdirSync(captureDir).filter(name => name.endsWith(".json")).sort()
|
||||
: [];
|
||||
let screenshotsCaptured = 0;
|
||||
for (const name of captureReports) {
|
||||
const report = JSON.parse(fs.readFileSync(path.join(captureDir, name), "utf8"));
|
||||
screenshotsCaptured += (report.shots ?? []).length;
|
||||
}
|
||||
|
||||
const assetsDir = path.join(webRoot, "manual", "assets");
|
||||
const countPngs = dir => fs.readdirSync(dir, { withFileTypes: true }).reduce((total, entry) => {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) return total + countPngs(full);
|
||||
return total + (entry.name.endsWith(".png") ? 1 : 0);
|
||||
}, 0);
|
||||
const screenshots = fs.existsSync(assetsDir) ? countPngs(assetsDir) : 0;
|
||||
|
||||
const appChapters = features.chapters.filter(chapter => chapter.level !== "appendix").length;
|
||||
const desktop = pageCheck.viewports.find(view => view.viewport.width >= 900) ?? pageCheck.viewports[0] ?? null;
|
||||
const mobile = pageCheck.viewports.find(view => view.viewport.width < 900) ?? null;
|
||||
const gapRegisterPath = path.join(webRoot, "..", "docs/current/ui-design/data/gap-register.json");
|
||||
const gapRegister = fs.existsSync(gapRegisterPath)
|
||||
? JSON.parse(fs.readFileSync(gapRegisterPath, "utf8"))
|
||||
: null;
|
||||
|
||||
const state = pageCheck.ok && (gapRegister ? gapRegister.ok : false) ? "complete" : "in-progress";
|
||||
const status = {
|
||||
schema: "freecad-web-manual/final-status/v1",
|
||||
generatedAt: new Date().toISOString(),
|
||||
state,
|
||||
chapters: appChapters,
|
||||
chaptersWithAppendix: features.chapters.length,
|
||||
screenshots,
|
||||
commands: features.stats.commands,
|
||||
modules: features.stats.modules,
|
||||
nativeHandlers: features.stats.nativeHandlers,
|
||||
verifiedCommands: ledger.verified,
|
||||
workflows: captureReports.length,
|
||||
boundaries: (features.boundaries ?? []).length,
|
||||
pageCheck: {
|
||||
ok: pageCheck.ok,
|
||||
desktopOverflow: desktop?.overflow ?? null,
|
||||
mobileOverflow: mobile?.overflow ?? null,
|
||||
brokenImages: desktop?.brokenImages ?? [],
|
||||
searchHits: desktop?.searchHits ?? 0,
|
||||
images: desktop?.images ?? 0,
|
||||
sections: desktop?.sections ?? 0,
|
||||
},
|
||||
entry: "web/teaching/manual.html",
|
||||
url: pageCheck.url,
|
||||
assets: "web/teaching/manual-assets",
|
||||
captureReports: "web/manual/data/capture",
|
||||
gapLedger: "web/manual/data/gap-ledger.json",
|
||||
knownBoundaries: (ledger.boundaries ?? []).map(item => item.title),
|
||||
notes: [
|
||||
"由 generate-final-status.mjs 自动派生,不要手改。",
|
||||
`UI 表面清单:${gapRegister ? gapRegister.counts.surfaces : "未生成"} 项,缺口 ${gapRegister ? gapRegister.issues.filter(issue => issue.problem === "ui-gap").length : "未知"} 项。`,
|
||||
],
|
||||
screenshotsCaptured,
|
||||
};
|
||||
|
||||
const text = `${JSON.stringify(status, null, 2)}\n`;
|
||||
|
||||
if (check) {
|
||||
const previous = fs.existsSync(outPath) ? fs.readFileSync(outPath, "utf8") : "";
|
||||
const strip = value => JSON.stringify({ ...JSON.parse(value), generatedAt: "__stable__" });
|
||||
if (!previous || strip(previous) !== strip(text)) {
|
||||
console.error("[generate-final-status] --check: final-status.json is stale");
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(JSON.stringify({ ok: true, checked: "web/manual/data/final-status.json" }));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
fs.writeFileSync(outPath, text);
|
||||
console.log(JSON.stringify({ ok: true, out: "web/manual/data/final-status.json", state, chapters: features.chapters.length, screenshots, commands: features.stats.commands }));
|
||||
117
web/tools/manual/generate-gaps-doc.mjs
Normal file
117
web/tools/manual/generate-gaps-doc.mjs
Normal file
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env node
|
||||
// Derives docs/current/web-freecad-manual-gaps.md from the real pipeline outputs so
|
||||
// the gap register never drifts from final-status.json / gap-ledger.json /
|
||||
// gap-register.json. The previous hand-written copy still described the retired
|
||||
// 32-module inventory, which is why this file is generated instead of maintained.
|
||||
//
|
||||
// node web/tools/manual/generate-gaps-doc.mjs
|
||||
// node web/tools/manual/generate-gaps-doc.mjs --check # exit 1 on drift
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const repoRoot = path.resolve(webRoot, "..");
|
||||
const dataDir = path.join(webRoot, "manual", "data");
|
||||
const outPath = path.join(repoRoot, "docs", "current", "web-freecad-manual-gaps.md");
|
||||
const gapRegisterPath = path.join(repoRoot, "docs", "current", "ui-design", "data", "gap-register.json");
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const check = args.includes("--check");
|
||||
|
||||
const read = file => JSON.parse(fs.readFileSync(file, "utf8"));
|
||||
const status = read(path.join(dataDir, "final-status.json"));
|
||||
const ledger = read(path.join(dataDir, "gap-ledger.json"));
|
||||
const register = fs.existsSync(gapRegisterPath) ? read(gapRegisterPath) : null;
|
||||
|
||||
const cell = value => String(value ?? "—").replace(/\|/g, "\\|");
|
||||
const lines = [];
|
||||
const push = (...items) => lines.push(...items);
|
||||
|
||||
push("# Web FreeCAD 手册与界面文档 · 缺口与边界账本", "");
|
||||
push("> 本文件由 `web/tools/manual/generate-gaps-doc.mjs` 从真实产物派生,**不要手改**。");
|
||||
push("> 输入:`web/manual/data/final-status.json`、`web/manual/data/gap-ledger.json`、`docs/current/ui-design/data/gap-register.json`。");
|
||||
push("> 复核:`node web/tools/manual/generate-gaps-doc.mjs --check`。", "");
|
||||
|
||||
push("## 口径", "");
|
||||
push(`- 模块数 **${status.modules}**(不含已整体摘除的 OpenSCAD)。`);
|
||||
push(`- 命令矩阵 **${status.commands}** 条,原生承接 **${status.nativeHandlers}** 条。`);
|
||||
push(`- 手工验证命令 **${status.verifiedCommands}** 条;已知边界 **${(ledger.boundaries ?? []).length}** 条。`);
|
||||
push(`- 手册 **${status.chaptersWithAppendix}** 章(正文 ${status.chapters} 章 + 附录章)、页面截图引用 **${status.pageCheck.images}** 处、磁盘 PNG **${status.screenshots}** 个。`);
|
||||
if (register) {
|
||||
const byCategory = register.counts.byCategory ?? {};
|
||||
push(`- UI 表面 **${register.counts.surfaces}** 项:${Object.entries(byCategory).map(([key, value]) => `${key} ${value}`).join(" / ")}。`);
|
||||
const partial = (register.surfaces ?? []).filter(item => item.status === "partial").length;
|
||||
const gap = (register.surfaces ?? []).filter(item => item.status === "gap").length;
|
||||
push(`- 表面状态:implemented ${register.counts.surfaces - partial - gap} / partial ${partial} / gap **${gap}**。`);
|
||||
}
|
||||
push("");
|
||||
|
||||
push("## 已实现的界面覆盖(不是缺口)", "");
|
||||
push("| 项 | 结果 |");
|
||||
push("|---|---|");
|
||||
push(`| 界面设计文档 | \`docs/current/web-freecad-ui-layout-and-functions.html\`,${status.chaptersWithAppendix} 章 + 命令附录 |`);
|
||||
push(`| 手册 | \`web/teaching/manual.html\`,${status.chapters} 章 ${status.pageCheck.sections} 节 |`);
|
||||
push(`| 截图 | 页面引用 ${status.pageCheck.images} 处;磁盘 ${status.screenshots} 个 PNG;采集报告 ${status.workflows} 份 |`);
|
||||
push(`| 浏览器校验 | 桌面 overflow ${status.pageCheck.desktopOverflow} / 移动 overflow ${status.pageCheck.mobileOverflow} / 破图 ${status.pageCheck.brokenImages.length} |`);
|
||||
push("");
|
||||
|
||||
push(`## 已知边界(${(ledger.boundaries ?? []).length} 条)`, "");
|
||||
push("| ID | 模块 | 边界 | 状态 |");
|
||||
push("|---|---|---|---|");
|
||||
for (const item of ledger.boundaries ?? []) {
|
||||
push(`| \`${cell(item.id)}\` | ${cell(item.module)} | ${cell(item.detail)} | ${cell(item.status)} |`);
|
||||
}
|
||||
push("");
|
||||
|
||||
push("## 手工验证的用例", "");
|
||||
push(`共 **${ledger.verified}** 条(台账 \`${path.relative(repoRoot, path.join(dataDir, "gap-ledger.json"))}\`)。`);
|
||||
for (const note of ledger.notes ?? []) push(`- ${note}`);
|
||||
push("");
|
||||
|
||||
if (register) {
|
||||
const flagged = (register.surfaces ?? []).filter(item => item.status === "partial" || item.status === "gap");
|
||||
push(`## 界面表面审计(${register.counts.surfaces} 项,问题 ${register.issues.length} 项)`, "");
|
||||
if (flagged.length) {
|
||||
push("| 表面 | 分类 | 状态 | 注释 |");
|
||||
push("|---|---|---|---|");
|
||||
for (const item of flagged) push(`| ${cell(item.nameZh)} | ${cell(item.category)} | ${cell(item.status)} | ${cell(item.note ?? "—")} |`);
|
||||
} else {
|
||||
push("没有 `partial` 或 `gap` 项。");
|
||||
}
|
||||
push("");
|
||||
push("审计命令:`node web/tools/manual/audit-ui-gaps.mjs --check`。");
|
||||
push("");
|
||||
}
|
||||
|
||||
push("## 复现命令", "");
|
||||
push("```bash");
|
||||
push(`R="/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD"`);
|
||||
push(`node "$R/tools/fcweb/ui-surface-inventory.mjs" --check`);
|
||||
push(`node "$R/tools/fcweb/build-ui-doc.mjs" --check`);
|
||||
push(`node "$R/web/tools/manual/audit-ui-gaps.mjs" --check`);
|
||||
push(`node "$R/web/tools/manual/generate-gaps-doc.mjs" --check`);
|
||||
push(`cd "$R/web" && npm run build:manual && npm run check:manual`);
|
||||
push("```");
|
||||
push("");
|
||||
push("## 边界判定口径", "");
|
||||
push("- 前置未满足(缺文档、缺 Worker、缺原生对象)记边界并保留产品原始错误文本,不写成产品回归。");
|
||||
push("- GUI 控件缺口用 React 组件补齐,不以 GUI-only 名义留作 blocked。");
|
||||
push("- 空白或占位截图不得入库;空白工具栏裁剪由 `build-ui-doc.mjs` 的 1024 字节门槛自动跳过。");
|
||||
push("- 生成物(本文件、第 16 章、`final-status.json`)一律由脚本产出并带 `--check`。");
|
||||
push("");
|
||||
|
||||
const text = `${lines.join("\n")}\n`;
|
||||
if (check) {
|
||||
const previous = fs.existsSync(outPath) ? fs.readFileSync(outPath, "utf8") : "";
|
||||
if (previous !== text) {
|
||||
console.error("[generate-gaps-doc] --check: docs/current/web-freecad-manual-gaps.md is stale");
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(JSON.stringify({ ok: true, checked: "docs/current/web-freecad-manual-gaps.md" }));
|
||||
process.exit(0);
|
||||
}
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, text);
|
||||
console.log(JSON.stringify({ ok: true, out: "docs/current/web-freecad-manual-gaps.md", bytes: Buffer.byteLength(text), boundaries: (ledger.boundaries ?? []).length, surfaces: register?.counts.surfaces ?? null }));
|
||||
203
web/tools/manual/generate-panel-index.mjs
Normal file
203
web/tools/manual/generate-panel-index.mjs
Normal file
@@ -0,0 +1,203 @@
|
||||
#!/usr/bin/env node
|
||||
// Generates web/manual/content/ch16-panel-index.md from the authoritative UI
|
||||
// surface inventory (tools/fcweb/out/ui-surface-inventory.json).
|
||||
//
|
||||
// The chapter is a reference appendix: every shell region, dock, task panel,
|
||||
// modal dialog, preference page, menu, toolbar, status bar item and viewport
|
||||
// tool with its React owner and desktop reference. Deterministic output: no
|
||||
// timestamps, sorted by category then module then id.
|
||||
//
|
||||
// node tools/manual/generate-panel-index.mjs
|
||||
// node tools/manual/generate-panel-index.mjs --check # exit 1 on drift
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const repoRoot = path.resolve(webRoot, "..");
|
||||
const inventoryPath = path.join(repoRoot, "tools/fcweb/out/ui-surface-inventory.json");
|
||||
const outPath = path.join(webRoot, "manual/content/ch16-panel-index.md");
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const check = args.includes("--check");
|
||||
|
||||
if (!fs.existsSync(inventoryPath)) {
|
||||
console.error(`[generate-panel-index] missing ${inventoryPath}; run tools/fcweb/ui-surface-inventory.mjs first`);
|
||||
process.exit(2);
|
||||
}
|
||||
const inventory = JSON.parse(fs.readFileSync(inventoryPath, "utf8"));
|
||||
|
||||
const CATEGORY_ORDER = ["shell-region", "statusbar", "viewport-tool", "dock", "task-panel", "modal-dialog", "preferences-page", "menu", "toolbar"];
|
||||
const CATEGORY_TITLE = {
|
||||
"shell-region": "壳层区域",
|
||||
statusbar: "状态栏",
|
||||
"viewport-tool": "视口工具",
|
||||
dock: "停靠面板",
|
||||
"task-panel": "任务面板",
|
||||
"modal-dialog": "模态对话框",
|
||||
"preferences-page": "偏好设置页",
|
||||
menu: "菜单",
|
||||
toolbar: "工具栏",
|
||||
};
|
||||
const CATEGORY_INTRO = {
|
||||
"shell-region": "主窗口骨架:标题栏、工作台切换器、菜单栏容器、工具栏容器、视口、停靠区、底部报告区、命令面板与快捷键入口。",
|
||||
statusbar: "底部状态栏:文档名、保存状态、网格与渲染统计。",
|
||||
"viewport-tool": "三维视口右上角与导航立方体旁的视图工具:视图切换、剖切面、导航方式等。",
|
||||
dock: "可停靠面板:模型树、属性编辑器、任务面板宿主等,由右侧停靠区承载,可折叠、可切换。",
|
||||
"task-panel": "工作台任务面板:每个 `<module>-<feature>-task.tsx` 对应一个桌面 TaskDialog 参数页,统一由 `TaskFrame` 挂载。",
|
||||
"modal-dialog": "应用级模态对话框:阻断主界面交互、需要确认或选择后才能继续的操作。",
|
||||
"preferences-page": "偏好设置对话框的分页,对应桌面 Edit → Preferences。",
|
||||
menu: "菜单栏条目:按工作台聚合,每项菜单展开后给出命令列表。",
|
||||
toolbar: "工具栏组:每个工作台一组,命令与桌面工具栏一一对应。",
|
||||
};
|
||||
const STATUS_ZH = { implemented: "已实现", partial: "部分实现", gap: "缺口", boundary: "边界" };
|
||||
|
||||
const esc = value => String(value ?? "")
|
||||
.replace(/\|/g, "\\|")
|
||||
.replace(/\n+/g, " ")
|
||||
.trim();
|
||||
|
||||
const surfaceRows = inventory.surfaces
|
||||
.slice()
|
||||
.sort((a, b) => {
|
||||
const ca = CATEGORY_ORDER.indexOf(a.category);
|
||||
const cb = CATEGORY_ORDER.indexOf(b.category);
|
||||
if (ca !== cb) return ca - cb;
|
||||
const ma = a.moduleId ?? "";
|
||||
const mb = b.moduleId ?? "";
|
||||
if (ma !== mb) return ma.localeCompare(mb, "en");
|
||||
return a.id.localeCompare(b.id, "en");
|
||||
});
|
||||
|
||||
const byCategory = new Map();
|
||||
for (const surface of surfaceRows) {
|
||||
if (!byCategory.has(surface.category)) byCategory.set(surface.category, []);
|
||||
byCategory.get(surface.category).push(surface);
|
||||
}
|
||||
|
||||
const counts = inventory.counts;
|
||||
const lines = [];
|
||||
lines.push("---");
|
||||
lines.push("id: ch16");
|
||||
lines.push("order: 16");
|
||||
lines.push("title: 全功能面板索引与实现映射");
|
||||
lines.push("level: appendix");
|
||||
lines.push("---");
|
||||
lines.push("");
|
||||
lines.push("# 第 16 章 全功能面板索引与实现映射");
|
||||
lines.push("");
|
||||
lines.push("本章由 `tools/fcweb/ui-surface-inventory.mjs` 生成,是 Web FreeCAD 全部界面表面的权威索引。");
|
||||
lines.push(`当前共 **${counts.total}** 个界面表面,覆盖 ${Object.keys(counts.byCategory).length} 类;状态分布:` +
|
||||
Object.entries(counts.byStatus).map(([status, count]) => `${STATUS_ZH[status] ?? status} ${count}`).join("、") +
|
||||
"(缺口 " + counts.gaps + " 项)。");
|
||||
lines.push("");
|
||||
lines.push("> 改动 `web/src` 后请重跑 `node tools/fcweb/ui-surface-inventory.mjs` 与本生成器,不要手改本章。");
|
||||
lines.push("");
|
||||
lines.push("## 16.1 分类总览");
|
||||
lines.push("");
|
||||
lines.push("| 类别 | 数量 | 说明 |");
|
||||
lines.push("| --- | ---: | --- |");
|
||||
for (const category of CATEGORY_ORDER) {
|
||||
const rows = byCategory.get(category) ?? [];
|
||||
lines.push(`| ${CATEGORY_TITLE[category]}(\`${category}\`) | ${rows.length} | ${esc(CATEGORY_INTRO[category])} |`);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("### 状态口径");
|
||||
lines.push("");
|
||||
lines.push("| 状态 | 含义 |");
|
||||
lines.push("| --- | --- |");
|
||||
lines.push("| 已实现 | React 组件存在、已注册并能从界面到达,有对应命令或路由。 |");
|
||||
lines.push("| 部分实现 | 组件存在但未完全注册/挂载,或仅覆盖桌面能力的一部分。 |");
|
||||
lines.push("| 缺口 | 桌面 FreeCAD 有、Web 端缺失。按项目铁律用 React 组件补齐,不得留作 blocked。 |");
|
||||
lines.push("| 边界 | 受内核或平台限制无法实现(如跨 Worker 文档桥),需写明原因与解除条件。 |");
|
||||
lines.push("");
|
||||
lines.push("## 16.2 界面表面实拍");
|
||||
lines.push("");
|
||||
lines.push("以下截图由 `web/manual/scenarios/ch16-shell-surfaces.json` 在真实运行的 Web FreeCAD 上采集(Playwright,1440×900)。");
|
||||
lines.push("");
|
||||
const SHOTS = [
|
||||
["01-shell-overview", "完整壳层:应用菜单栏、工作台工具栏、对象树、属性面板、三维视口、任务区与文档标签。"],
|
||||
["02-tools-menu", "Tools 菜单:偏好设置、快捷键定制、命令面板入口。"],
|
||||
["03-preferences", "偏好设置对话框:单位制、导航风格、视图与保存选项。"],
|
||||
["04-shortcuts", "快捷键编辑器:按命令搜索并重绑按键。"],
|
||||
["05-command-palette", "命令面板(Ctrl+Shift+P):模糊搜索全部已注册命令。"],
|
||||
["06-bottom-dock", "底部停靠:Selection view / Report view / Python console 三个页签,可浮动、可全屏。"],
|
||||
["07-viewport-tools", "视口工具条:移动 / 旋转 / 关闭、局部坐标、「局部坐标…」编辑入口与位置读数。"],
|
||||
["08-task-panel", "任务面板:Part 立方体创建任务,含 Box dimensions、Volume 与 Bounds,底部为关闭与取消按钮。"],
|
||||
];
|
||||
for (const [name, caption] of SHOTS) {
|
||||
lines.push(``);
|
||||
lines.push("");
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
let sectionNumber = 3;
|
||||
for (const category of CATEGORY_ORDER) {
|
||||
const rows = byCategory.get(category) ?? [];
|
||||
if (!rows.length) continue;
|
||||
lines.push(`## 16.${sectionNumber} ${CATEGORY_TITLE[category]}(${rows.length})`);
|
||||
lines.push("");
|
||||
lines.push(CATEGORY_INTRO[category]);
|
||||
lines.push("");
|
||||
lines.push("| 名称 | React 实现 | 桌面参考 | 状态 | 注释 |");
|
||||
lines.push("| --- | --- | --- | --- | --- |");
|
||||
for (const surface of rows) {
|
||||
const owner = surface.owner?.file
|
||||
? `\`${esc(surface.owner.file.replace(/^web\//, ""))}${surface.owner.symbol ? `#${esc(surface.owner.symbol)}` : ""}\``
|
||||
: "—";
|
||||
const desktop = surface.desktopRef?.file
|
||||
? `\`${esc(surface.desktopRef.file.replace(/^freecad-source\//, ""))}${surface.desktopRef.symbol ? `#${esc(surface.desktopRef.symbol)}` : ""}\``
|
||||
: "—";
|
||||
const label = category === "menu" || category === "toolbar" ? esc(surface.nameZh) : `${esc(surface.nameZh)}(\`${esc(surface.id)}\`)`;
|
||||
lines.push(`| ${label} | ${owner} | ${desktop} | ${STATUS_ZH[surface.status] ?? surface.status} | ${esc(surface.note ?? "") || "—"} |`);
|
||||
}
|
||||
lines.push("");
|
||||
sectionNumber += 1;
|
||||
}
|
||||
|
||||
lines.push("## 16." + sectionNumber + " 缺口与边界清单");
|
||||
lines.push("");
|
||||
const gaps = inventory.gaps ?? [];
|
||||
if (!gaps.length) {
|
||||
lines.push("当前清单无 `gap`/`boundary` 项:全部界面表面均有 React 实现。");
|
||||
} else {
|
||||
lines.push("| 表面 | 类别 | 状态 | 原因 | 解除条件 |");
|
||||
lines.push("| --- | --- | --- | --- | --- |");
|
||||
for (const gap of gaps) {
|
||||
lines.push(`| \`${esc(gap.id)}\` | ${esc(CATEGORY_TITLE[gap.category] ?? gap.category)} | ${STATUS_ZH[gap.status] ?? gap.status} | ${esc(gap.reason ?? "")} | ${esc(gap.resolution ?? "")} |`);
|
||||
}
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("## 16." + (sectionNumber + 1) + " 复核命令");
|
||||
lines.push("");
|
||||
lines.push("```bash");
|
||||
lines.push('R="/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD"');
|
||||
lines.push('node "$R/tools/fcweb/ui-inventory.mjs"');
|
||||
lines.push('node "$R/tools/fcweb/ui-surface-inventory.mjs" # 生成清单');
|
||||
lines.push('node "$R/tools/fcweb/ui-surface-inventory.mjs" --check # 漂移检查');
|
||||
lines.push('node "$R/web/tools/manual/generate-panel-index.mjs" # 重生成本章');
|
||||
lines.push("```");
|
||||
lines.push("");
|
||||
|
||||
const markdown = lines.join("\n");
|
||||
|
||||
if (check) {
|
||||
const previous = fs.existsSync(outPath) ? fs.readFileSync(outPath, "utf8") : "";
|
||||
if (previous !== markdown) {
|
||||
console.error("[generate-panel-index] --check: ch16-panel-index.md is stale");
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(JSON.stringify({ ok: true, checked: path.relative(repoRoot, outPath), surfaces: counts.total }));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, markdown);
|
||||
console.log(JSON.stringify({
|
||||
ok: true,
|
||||
out: path.relative(repoRoot, outPath),
|
||||
surfaces: counts.total,
|
||||
sections: sectionNumber - 1,
|
||||
bytes: Buffer.byteLength(markdown),
|
||||
}));
|
||||
186
web/tools/manual/lib/actions.mjs
Normal file
186
web/tools/manual/lib/actions.mjs
Normal file
@@ -0,0 +1,186 @@
|
||||
// Scenario action interpreter shared by capture.mjs (screenshot capture) and the
|
||||
// headed functional suite (assertions). Behaviour is identical to the switch it
|
||||
// was extracted from; everything environment-specific arrives through options.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { listOpfsFiles, readOpfsFile, seedOpfsFromBytes } from "../../carrier-course/lib/opfs.mjs";
|
||||
|
||||
const sha256 = file => createHash("sha256").update(fs.readFileSync(file)).digest("hex");
|
||||
|
||||
export function createActionRunner(page, {
|
||||
origin = "",
|
||||
shotDir,
|
||||
shotPrefix = "",
|
||||
fixturePath = null,
|
||||
record = () => {},
|
||||
shotIndex = [],
|
||||
} = {}) {
|
||||
const click = async action => {
|
||||
let locator;
|
||||
if (action.role) locator = page.getByRole(action.role, { name: action.name, exact: action.exact });
|
||||
else {
|
||||
locator = page.locator(action.selector);
|
||||
if (action.hasText) locator = locator.filter({ hasText: action.hasText });
|
||||
if (action.target) locator = locator.locator(action.target);
|
||||
}
|
||||
if (action.nth !== undefined) locator = locator.nth(action.nth);
|
||||
else if (!action.all) locator = locator.first();
|
||||
if (action.optional && (await locator.count()) === 0) return;
|
||||
if (action.all) {
|
||||
const count = await locator.count();
|
||||
for (let index = 0; index < count; index++) await locator.nth(index).click();
|
||||
} else await locator.click({ timeout: action.timeout ?? 30000 });
|
||||
};
|
||||
const shot = async action => {
|
||||
if (!shotDir) throw new Error("shot action needs a shotDir");
|
||||
const file = path.join(shotDir, `${action.name}.png`);
|
||||
fs.mkdirSync(shotDir, { recursive: true });
|
||||
if (action.selector) {
|
||||
const target = page.locator(action.selector).first();
|
||||
await target.waitFor({ state: "visible", timeout: 30000 });
|
||||
try {
|
||||
await target.screenshot({ path: file, timeout: 20000 });
|
||||
} catch {
|
||||
// Element screenshots scroll the element into view and can time out on
|
||||
// containers taller than the viewport; evidence capture must not turn
|
||||
// a healthy page state into a failure, so fall back to the viewport.
|
||||
await page.screenshot({ path: file });
|
||||
record({ action: "shot", name: action.name, fallback: "viewport" });
|
||||
}
|
||||
} else {
|
||||
await page.screenshot({ path: file, fullPage: Boolean(action.fullPage) });
|
||||
}
|
||||
const stat = fs.statSync(file);
|
||||
if (stat.size < 1024) throw new Error(`screenshot too small: ${file}`);
|
||||
shotIndex.push({ id: `${shotPrefix}${action.name}`, file,
|
||||
bytes: stat.size, sha256: sha256(file), fullPage: Boolean(action.fullPage), selector: action.selector ?? null });
|
||||
record({ action: "shot", name: action.name, bytes: stat.size });
|
||||
return file;
|
||||
};
|
||||
const save = async action => {
|
||||
await page.evaluate(() => { const details = document.querySelector(".file-tools"); if (details) details.open = true; });
|
||||
await page.waitForTimeout(400);
|
||||
const before = await listOpfsFiles(page);
|
||||
await page.locator('button:has-text("保存 FCStd 到 OPFS")').first().click();
|
||||
let after = before; let status = "";
|
||||
for (let attempt = 0; attempt < 40; attempt++) {
|
||||
await page.waitForTimeout(750);
|
||||
after = await listOpfsFiles(page);
|
||||
status = await page.locator("p.status").first().textContent().catch(() => "");
|
||||
if (after.some(name => !before.includes(name) && /\.FCStd$/i.test(name)) || /Saved\s+\S+\.FCStd\s+to OPFS/i.test(status ?? "")) break;
|
||||
}
|
||||
const match = /Saved\s+(\S+\.FCStd)\s+to OPFS/i.exec(status ?? "");
|
||||
const name = match?.[1] ?? after.find(item => !before.includes(item) && /\.FCStd$/i.test(item));
|
||||
if (!name) throw new Error(`save produced no FCStd; status=${status}`);
|
||||
const bytes = (await readOpfsFile(page, name)).bytes;
|
||||
if (fixturePath) {
|
||||
fs.mkdirSync(path.dirname(fixturePath), { recursive: true });
|
||||
fs.writeFileSync(fixturePath, Buffer.from(bytes));
|
||||
}
|
||||
record({ action: "save", name, bytes: bytes.length, status });
|
||||
return { name, bytes: Buffer.from(bytes) };
|
||||
};
|
||||
|
||||
const run = async action => {
|
||||
switch (action.type) {
|
||||
case "goto":
|
||||
await page.goto(`${origin}${action.url}`, { waitUntil: "domcontentloaded", timeout: 120000 });
|
||||
record({ action: "goto", url: action.url });
|
||||
break;
|
||||
case "waitFor":
|
||||
if (action.selector) await page.waitForSelector(action.selector, { timeout: action.timeout ?? 120000 });
|
||||
if (action.text) await page.getByText(action.text, { exact: action.exact ?? false }).first()
|
||||
.waitFor({ state: "visible", timeout: action.timeout ?? 120000 });
|
||||
record({ action: "waitFor", selector: action.selector ?? null, text: action.text ?? null });
|
||||
break;
|
||||
case "click": await click(action); record({ action: "click", selector: action.selector ?? action.name }); break;
|
||||
case "fill":
|
||||
await page.locator(action.selector).first().fill(String(action.value));
|
||||
record({ action: "fill", selector: action.selector, value: action.value });
|
||||
break;
|
||||
case "select":
|
||||
await page.locator(action.selector).first().selectOption(action.label ? { label: action.label } : action.value);
|
||||
record({ action: "select", selector: action.selector, label: action.label ?? action.value });
|
||||
break;
|
||||
case "selectIndex":
|
||||
await page.locator(action.selector).first().selectOption({ index: action.index });
|
||||
record({ action: "selectIndex", selector: action.selector, index: action.index });
|
||||
break;
|
||||
case "press": await page.keyboard.press(action.key); record({ action: "press", key: action.key }); break;
|
||||
case "clickCanvas": {
|
||||
const target = page.locator(action.selector).first();
|
||||
await target.scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(200);
|
||||
const box = await target.boundingBox();
|
||||
if (!box) throw new Error(`canvas missing: ${action.selector}`);
|
||||
await page.mouse.click(box.x + box.width * action.fx, box.y + box.height * action.fy);
|
||||
await page.waitForTimeout(action.wait ?? 250);
|
||||
record({ action: "clickCanvas", selector: action.selector, fx: action.fx, fy: action.fy });
|
||||
break;
|
||||
}
|
||||
case "assertAnyText": {
|
||||
const texts = await page.locator(action.selector).allTextContents();
|
||||
if (!texts.some(text => String(text).includes(action.contains)))
|
||||
throw new Error(`assertAnyText failed: ${action.contains} in ${JSON.stringify(texts.slice(0, 5))}`);
|
||||
record({ action: "assertAnyText", selector: action.selector, contains: action.contains });
|
||||
break;
|
||||
}
|
||||
case "drag": {
|
||||
const box = await page.locator(action.selector).first().boundingBox();
|
||||
if (!box) throw new Error(`drag target missing: ${action.selector}`);
|
||||
const x = box.x + box.width / 2; const y = box.y + box.height / 2;
|
||||
await page.mouse.move(x, y); await page.mouse.down();
|
||||
await page.mouse.move(x + (action.dx ?? 0), y + (action.dy ?? 0), { steps: 18 });
|
||||
await page.mouse.up(); await page.waitForTimeout(400);
|
||||
record({ action: "drag", selector: action.selector, dx: action.dx, dy: action.dy });
|
||||
break;
|
||||
}
|
||||
case "eval":
|
||||
await page.evaluate(action.script);
|
||||
record({ action: "eval" });
|
||||
break;
|
||||
case "seed": {
|
||||
const file = path.resolve(action.file);
|
||||
if (!fs.existsSync(file)) throw new Error(`seed fixture missing: ${file}`);
|
||||
await seedOpfsFromBytes(page, action.name ?? path.basename(file), fs.readFileSync(file));
|
||||
record({ action: "seed", file, name: action.name ?? path.basename(file) });
|
||||
break;
|
||||
}
|
||||
case "shot": await shot(action); break;
|
||||
case "save": await save(action); break;
|
||||
case "assertText": {
|
||||
const text = await page.locator(action.selector).first().textContent();
|
||||
if (!String(text ?? "").includes(action.contains)) throw new Error(`assertText failed: ${action.selector} ${text}`);
|
||||
record({ action: "assertText", selector: action.selector, contains: action.contains });
|
||||
break;
|
||||
}
|
||||
case "assertVisible":
|
||||
await page.locator(action.selector).first().waitFor({ state: "visible", timeout: 30000 });
|
||||
record({ action: "assertVisible", selector: action.selector });
|
||||
break;
|
||||
case "waitOptions": {
|
||||
const locator = page.locator(action.selector).first();
|
||||
let count = 0;
|
||||
for (let attempt = 0; attempt < 80; attempt++) {
|
||||
count = await locator.locator("option").count();
|
||||
if (count >= (action.min ?? 1)) break;
|
||||
await page.waitForTimeout(500);
|
||||
}
|
||||
if (count < (action.min ?? 1)) throw new Error(`waitOptions failed: ${action.selector} ${count}`);
|
||||
record({ action: "waitOptions", selector: action.selector, count });
|
||||
break;
|
||||
}
|
||||
case "assertValue": {
|
||||
const value = await page.locator(action.selector).first().inputValue();
|
||||
if (String(value) !== String(action.value)) throw new Error(`assertValue failed: ${action.selector} ${value} != ${action.value}`);
|
||||
record({ action: "assertValue", selector: action.selector, value });
|
||||
break;
|
||||
}
|
||||
case "wait": await page.waitForTimeout(action.ms ?? 500); break;
|
||||
default: throw new Error(`unknown action ${action.type}`);
|
||||
}
|
||||
};
|
||||
|
||||
return { click, shot, save, run, shotIndex };
|
||||
}
|
||||
@@ -38,6 +38,20 @@
|
||||
main figure { margin:16px 0; }
|
||||
main figcaption { color:var(--muted); font-size:12.5px; }
|
||||
.table-scroll { max-width:100%; overflow-x:auto; }
|
||||
/* UI-operation block: the real screenshot plus the exact field values the
|
||||
driver typed, side by side on wide screens and stacked on phones. */
|
||||
.ui-block { margin:20px 0; padding:14px 16px; border:1px solid var(--line); border-radius:10px; background:var(--panel); }
|
||||
.ui-block h4 { margin:0 0 10px; font-size:14px; letter-spacing:0.04em; color:var(--accent); }
|
||||
.ui-block img { display:block; width:100%; height:auto; border-radius:8px; border:1px solid var(--line); }
|
||||
.ui-block table { width:100%; margin-top:10px; border-collapse:collapse; font-size:13px; }
|
||||
.ui-block th { text-align:left; font-weight:600; color:var(--muted); padding:5px 8px; width:38%; }
|
||||
.ui-block td { padding:5px 8px; font-variant-numeric:tabular-nums; }
|
||||
.ui-block tr + tr { border-top:1px solid var(--line); }
|
||||
@media (min-width:900px) {
|
||||
.ui-block { display:grid; grid-template-columns:minmax(0,1.4fr) minmax(0,1fr); gap:16px; align-items:start; }
|
||||
.ui-block h4 { grid-column:1 / -1; }
|
||||
.ui-block table { margin-top:0; }
|
||||
}
|
||||
table { width:100%; border-collapse:collapse; font-size:13px; margin:12px 0; }
|
||||
th, td { border-bottom:1px solid var(--line); padding:5px 7px; text-align:left; vertical-align:top; }
|
||||
th { color:var(--accent); }
|
||||
@@ -52,7 +66,7 @@
|
||||
.index-controls { display:flex; gap:8px; flex-wrap:wrap; margin:12px 0; }
|
||||
.index-controls select, .index-controls input { background:#0b1014; color:var(--text); border:1px solid #3f3f3f; border-radius:4px; padding:5px 8px; }
|
||||
#command-index td { font-size:12px; } #command-index tr.hidden { display:none; }
|
||||
.pager { display:flex; justify-content:space-between; gap:12px; margin-top:40px; padding-top:14px; border-top:1px solid var(--line); }
|
||||
.pager { display:flex; flex-wrap:wrap; justify-content:space-between; gap:12px; margin-top:40px; padding-top:14px; border-top:1px solid var(--line); }
|
||||
#lightbox { position:fixed; inset:0; background:#000d; z-index:60; display:none; align-items:center; justify-content:center; padding:24px; }
|
||||
#lightbox img { max-width:96vw; max-height:92vh; border-radius:6px; }
|
||||
#lightbox.open { display:flex; }
|
||||
|
||||
Reference in New Issue
Block a user