diff --git a/design-docs/editor-sw-terms.md b/design-docs/editor-sw-terms.md new file mode 100644 index 00000000..3ed2efd2 --- /dev/null +++ b/design-docs/editor-sw-terms.md @@ -0,0 +1,32 @@ +# Editor wording follows SolidWorks (Chinese UI) + +The editor's manual mode is used by people who learned CAD on SolidWorks. Where the editor named a thing differently, they +looked for the SolidWorks word and did not find it. The Chinese translation table (`editor-web/src/i18n/locales/zh-CN.json`) +now uses the SolidWorks Chinese terms. Only words a person reads changed: the SDK, the notebook code, the keys of the table and +everything an agent reads stay as they were, so the kernel stays agent-friendly. + +| Thing | Was | Now (SolidWorks) | +|---|---|---| +| A plane to sketch on | 工作平面 | 基准面 | +| Sketch fully determined | 已求解 | 完全定义 | +| Sketch still free to move | 欠约束 N 自由度 | 欠定义(还有 N 个自由度) | +| Sketch over-determined | 冲突 | 过定义 | +| Sketch constraints (as a group) | 约束 | 几何关系/尺寸 | +| Automatic horizontal/vertical | 自动约束 | 自动添加几何关系 | +| Construction geometry | 构造线 | 构造几何线 | +| Mirror | 镜像 | 镜向 | +| Extrude that adds | 拉伸(合并) | 拉伸凸台 | +| Extrude that removes | 拉伸(切除) | 拉伸切除 | +| Push or pull a face | 推拉 | 移动面 | +| Hole on a face | 在此打孔 | 简单直孔 | +| An edge to pick | 边 | 边线 | +| Assembly joints | …约束 | …配合(铰链、滑块、齿轮、齿条小齿轮、皮带/链、锁定) | +| A part or sub-assembly placed in an assembly | 组件 | 零部件 | + +Not changed on purpose: + +- **基本体** (box, cylinder, …): SolidWorks has no primitives (it sketches and extrudes), so there is no word to copy. +- Behaviour that differs from SolidWorks (pick-kind chips instead of hover selection, connectors instead of face mates, no + rollback bar) is not a wording question; it is listed with the editor's open issues. + +The SolidWorks terms are the ones its Chinese releases commonly use; a few may differ slightly between versions. diff --git a/editor-web/src/App.tsx b/editor-web/src/App.tsx index 0b10ca16..730c9b34 100644 --- a/editor-web/src/App.tsx +++ b/editor-web/src/App.tsx @@ -37,6 +37,7 @@ import { viewPose } from "@/lib/sketch-plane"; import * as THREE from "three"; import { addConnectorFrame, connectorFrameFromFace, setConnectorsCommand, setRef } from "@/lib/assembly"; import { useAssemblyEditor, useConnectorDraft } from "@/lib/useAssembly"; +import { ExportDialog, type ExportState } from "@/components/ExportDialog"; import { Header } from "@/components/Header"; import { Inspector } from "@/components/Inspector"; import { SketchMode, type FaceCheck, type SketchAfter, type SketchSession } from "@/components/sketch/SketchMode"; @@ -90,7 +91,7 @@ const MANUAL_TABS = ["features", "assembly"]; const CODE_TABS = ["notebook", "module"]; export function App() { - useI18n(); // a change of language renders the whole editor again + const { language } = useI18n(); // a change of language renders the whole editor again const viewRef = useRef(null); // Whether a model of the open notebook is on screen (it may be the last run's, // restored while the kernel boots): then nothing is being waited for. @@ -137,6 +138,7 @@ export function App() { const [currentPath, setCurrentPath] = useState(null); const [kernelAlive, setKernelAlive] = useState(false); const [status, setStatus] = useState(() => t("Connecting…")); + const [exportState, setExportState] = useState(null); const [params, setParams] = useState([]); const [cells, setCells] = useState([]); @@ -464,6 +466,8 @@ export function App() { if (envelope["error"]) { log.push("error", envelope["error"]); setLoading(null); + const message = envelope["error"]; + setExportState((current) => (current?.phase === "working" ? { phase: "error", message } : current)); } } else if (typeof envelope["info"] === "string") { setStatus(t(envelope["info"])); @@ -476,6 +480,10 @@ export function App() { } else if (typeof envelope["exported"] === "string") { setStatus(t("exported {{path}}", { path: envelope["exported"] })); log.push("ok", t("exported {{file}}", { file: envelope["exported"] })); + setLoading(null); + const dir = envelope["export_dir"]; + const files = envelope["export_files"]; + if (typeof dir === "string" && Array.isArray(files)) setExportState({ phase: "done", dir, files: files.map(String) }); } else if (typeof envelope["created"] === "string") { setStatus(t("created {{path}}", { path: envelope["created"] })); log.push("ok", t("created {{name}}", { name: envelope["created"] })); @@ -1700,6 +1708,18 @@ export function App() { [selection, livePickedSurfaces], ); const inspectorPanel = ; + // the names the feature tree shows (# 名称:…, or the operation in the person's language), for notices about a step + const stepNames = useMemo(() => { + const names = new Map(cellTitles); + for (const feature of gui.state.features) { + const spec = feature.gui ? gui.catalog?.specs.find((item) => item.id === feature.gui?.spec) : undefined; + const name = feature.title || (spec ? t(plainLabel(spec.id, spec.label)) : ""); + if (name) names.set(feature.cell, name); + } + return names; + // the names are translated: a change of language makes them again + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [cellTitles, gui.state.features, gui.catalog, language]); return (
@@ -1711,7 +1731,12 @@ export function App() { status={status} themePreference={theme.preference} onTheme={theme.cycle} + onExport={() => { + setExportState({ phase: "working" }); + socketRef.current?.send({ type: "export.request" }); + }} /> + setExportState(null)} />
@@ -1739,7 +1764,7 @@ export function App() { ))}
-
+
{!MANUAL_MODE ? ( panelFor("code") ) : ( @@ -1901,7 +1926,7 @@ export function App() { task={taskOpen} locked={sketching || moving} leftNotice={!taskOpen && viewRef.current ? : null} - rightNotice={partial && !sketching ? : null} + rightNotice={partial && !sketching ? : null} /> )} {sketchSession && viewRef.current && ( diff --git a/editor-web/src/components/ExportDialog.tsx b/editor-web/src/components/ExportDialog.tsx new file mode 100644 index 00000000..891649f1 --- /dev/null +++ b/editor-web/src/components/ExportDialog.tsx @@ -0,0 +1,135 @@ +import { Check, Copy, Download, Loader2 } from "lucide-react"; +import { useState } from "react"; + +import { Button } from "@/components/ui/button"; +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { useI18n } from "@/i18n"; + +/** Where an export stands: being made, written (the folder and the file names), or failed. */ +export type ExportState = { phase: "working" } | { phase: "done"; dir: string; files: string[] } | { phase: "error"; message: string } | null; + +/** What each kind of file is for, in a person's words (English keys of the translation table). */ +const PURPOSE: Record = { + step: "STEP: opens in other CAD programs (SolidWorks, FreeCAD, Fusion 360)", + stl: "STL: for a 3D printer's slicer", + scadpkg: "SimpleCAD package: the full model with its history, for this SDK", +}; + +type SavePicker = (options: { suggestedName: string }) => Promise<{ createWritable: () => Promise<{ write: (data: Blob) => Promise; close: () => Promise }> }>; + +/** Save one exported file where the person chooses: the system "save as" dialog where the browser has one, else a download. */ +async function saveAs(name: string): Promise<"saved" | "downloaded" | "cancelled"> { + const picker = (window as unknown as { showSaveFilePicker?: SavePicker }).showSaveFilePicker; + if (picker) { + let handle; + try { + handle = await picker({ suggestedName: name }); + } catch { + return "cancelled"; // the person closed the dialog + } + try { + const response = await fetch(`/api/export/file/${encodeURIComponent(name)}`); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + const writable = await handle.createWritable(); + await writable.write(await response.blob()); + await writable.close(); + return "saved"; + } catch { + // some browsers (an embedded one) show the dialog but refuse the write: a plain download still works + } + } + const link = document.createElement("a"); + link.href = `/api/export/file/${encodeURIComponent(name)}`; + link.download = name; + link.click(); + return "downloaded"; +} + +/** The export dialog: it waits for the files, then says where they were written and offers "save as" for each. */ +export function ExportDialog({ state, onClose }: { state: ExportState; onClose: () => void }) { + const { t } = useI18n(); + const [copied, setCopied] = useState(false); + const [saved, setSaved] = useState>({}); + const open = state !== null; + const copy = (text: string) => { + void navigator.clipboard?.writeText(text).then(() => { + setCopied(true); + window.setTimeout(() => setCopied(false), 1500); + }); + }; + const save = (name: string) => { + saveAs(name) + .then((outcome) => { + if (outcome === "saved") setSaved((s) => ({ ...s, [name]: t("Saved where you chose.") })); + if (outcome === "downloaded") setSaved((s) => ({ ...s, [name]: t("Downloaded: look in the browser's downloads (usually the Downloads folder).") })); + }) + .catch(() => setSaved((s) => ({ ...s, [name]: t("Could not save it here. Use the folder above: the file is already there.") }))); + }; + // every way out (the close button, Esc, a click outside) forgets what was saved: the next export starts clean + const close = () => { + setSaved({}); + onClose(); + }; + return ( + { + if (!next) close(); + }} + > + + + {t("Export")} + + {state?.phase === "working" && t("Making the files from the model; this takes a few seconds…")} + {state?.phase === "done" && t("The files were written to this folder (next to the notebook):")} + {state?.phase === "error" && t("The export failed:")} + + + {state?.phase === "working" && ( +
+ + {t("building the package")} +
+ )} + {state?.phase === "error" &&

{state.message}

} + {state?.phase === "done" && ( +
+
+ {state.dir} + +
+
    + {state.files.map((name) => { + const kind = name.split(".").pop()?.toLowerCase() ?? ""; + return ( +
  • +
    +
    +
    {name}
    + {PURPOSE[kind] &&
    {t(PURPOSE[kind])}
    } +
    + +
    + {saved[name] &&

    {saved[name]}

    } +
  • + ); + })} +
+
+ )} + + + +
+
+ ); +} diff --git a/editor-web/src/components/FeatureTree.tsx b/editor-web/src/components/FeatureTree.tsx index 4aef9b44..5b31a252 100644 --- a/editor-web/src/components/FeatureTree.tsx +++ b/editor-web/src/components/FeatureTree.tsx @@ -1,4 +1,6 @@ -import { ArrowRight, Eye, EyeOff, Pencil, Redo2, Trash2, Undo2 } from "lucide-react"; +import { Eye, EyeOff, Pencil, Redo2, Trash2, Undo2 } from "lucide-react"; +import { rowClick } from "@/lib/tree-click"; +import { plainGuiError, sdkErrorParts } from "@/lib/plain-label"; import { useEffect, useRef, useState } from "react"; import { CODE_FEATURE_ICON, FEATURE_ICONS } from "@/components/feature-icons"; @@ -25,22 +27,19 @@ export function UndoRedo({ state, busy, onUndo, onRedo }: { state: Pick).message ?? (first as Record).error ?? JSON.stringify(first)); - // The SDK's errors lead with the operation and signature: the line that says what happened is the one to show. - const what = text.split("\n").find((line) => line.startsWith("What happened:")); - return (what ? what.replace("What happened:", "").trim() : text.split("\n")[0]).slice(0, 300); - } - return feature.status === "error" || feature.status === "exception" ? "this step failed" : null; +/** The texts a failed step carries (the SDK's message, possibly also a cut-short summary of it). */ +function errorTexts(feature: FeatureRow): string[] { + return feature.errors.map((error) => + typeof error === "string" ? error : String((error as Record).message ?? (error as Record).error ?? JSON.stringify(error)), + ); +} + +function isFailed(feature: FeatureRow): boolean { + return feature.errors.length > 0 || feature.status === "error" || feature.status === "exception"; } function statusColor(feature: FeatureRow): string { - if (errorText(feature)) return "bg-fail"; + if (isFailed(feature)) return "bg-fail"; if (feature.status === "running" || feature.status === "queued") return "bg-focus"; if (feature.status === "done" || feature.status === "ok" || feature.status === "idle") return "bg-pass"; return "bg-muted-foreground"; @@ -63,28 +62,55 @@ export function ReferenceHealth({ cell, version, busy, onRepair }: { cell: strin }, [cell, version]); if (failure) return

{t("references:")} {failure}

; if (!status || status.badge === null) return null; + const rows = Object.entries(status.slots).flatMap(([slot, list]) => list.map((row, index) => ({ slot, index, row, state: refState(row) }))); + // every picked face/edge is still found: that is not why the step failed, so say nothing + if (rows.every(({ state }) => state === "ok" || state === "merged")) return null; return (
- {Object.entries(status.slots).flatMap(([slot, rows]) => - rows.map((row, index) => { - const state = refState(row); + {rows.map(({ slot, index, row, state }) => { + const what = t(SLOT_WORD[slot] ?? slot); return (
- {slot} {index + 1}: {state} - {state === "lost" && row.reason && ({row.reason}{row.lost_at ? ` at ${row.lost_at}` : ""})} + + {t("{{what}} {{n}}: {{state}}", { what, n: index + 1, state: t(STATE_WORD[state]) })} + {(state === "split" || state === "lost") && row.candidates.length > 0 && (
{row.candidates.map((candidate, choice) => ( ))}
)}
); - }), + })} +
+ ); +} + +const SLOT_WORD: Record = { faces: "face", edges: "edge", vertices: "vertex", face: "face", edge: "edge" }; +const STATE_WORD: Record = { ok: "still there", merged: "still there (merged)", split: "split into pieces: pick one", lost: "can't be found" }; + +/** A failed step in a person's words: what did not work, what to do, and the SDK's own message folded away. */ +function FailureNote({ name, texts }: { name: string; texts: string[] }) { + const parts = sdkErrorParts(texts); + return ( +
+

{t("{{name}} did not work", { name })}

+

{t("Try changing its numbers, or select the part and ask the AI to find out why and fix it.")}

+ {parts.full && ( +
+ {t("Details (the SDK's message, in English)")} +
+ {parts.what &&

{parts.what}

} + {parts.causes.length > 0 &&

{t("Possible causes:")} {parts.causes.join("; ")}

} + {parts.fixes.length > 0 &&

{t("How to fix:")} {parts.fixes.join("; ")}

} + {!parts.what &&

{parts.full.slice(0, 600)}

} +
+
)}
); @@ -97,7 +123,8 @@ export type TreeSketches = { selected: readonly string[]; hover: string | null; onToggleHidden: (name: string) => void; - onSelect: (name: string, additive: boolean) => void; + /** Pick a row (Ctrl/Cmd: add or take out); null clears the selection. */ + onSelect: (name: string | null, additive: boolean) => void; onHover: (name: string | null) => void; }; @@ -139,6 +166,23 @@ export function FeatureTree({ }; const stale = state.product && state.tip && state.product.body !== state.tip ? state.product : null; + + /** A feature's name for a person: its operation in their language (Box → 方块), numbered when the operation repeats; a + * feature with a written name (`# 名称:…`) shows that, other code its own name. */ + const plainName = (feature: (typeof state.features)[number]): string => { + if (feature.title) return feature.title; // the name written for a person (# 名称:…), by the agent or by hand + const spec = feature.gui ? catalog?.specs.find((item) => item.id === feature.gui?.spec) : undefined; + if (!spec) return feature.slug; + const label = t(plainLabel(spec.id, spec.label)); + const same = state.features.filter((other) => other.gui?.spec === feature.gui?.spec); + return same.length > 1 ? `${label} ${same.indexOf(feature) + 1}` : label; + }; + /** The name of the feature that makes a body (bodies are code names). */ + const bodyName = (body: string): string => { + const maker = state.features.find((feature) => feature.makes.includes(body)); + return maker ? plainName(maker) : body; + }; + return (
@@ -148,10 +192,10 @@ export function FeatureTree({ {stale && state.tip && (
- {t("The product still builds from")} {stale.body}. + {t("The finished part is the result of {{name}}.", { name: bodyName(stale.body) })}
)} @@ -160,22 +204,30 @@ export function FeatureTree({ {t("{{count}} solids are open, and a Part holds exactly one solid. Choose the part:", { count: state.open.length })} {state.open.map((body) => ( ))}
)} - {error &&
{error}
} - + {error &&
{plainGuiError(error)}
} + { + // a click on the empty part of the list (not on a row or a button) clears what the tree picked + if (!(event.target as HTMLElement).closest("li, button")) sketches?.onSelect(null, false); + }} + > {state.features.length === 0 ? (

{t("No features yet. Add a Box or another operation from the command bar; each one becomes an ordinary cell in the notebook.")}

) : (
    - {state.features.map((feature) => { + {state.features.map((feature, position) => { const spec = feature.gui ? catalog?.specs.find((item) => item.id === feature.gui?.spec) : undefined; - const problem = errorText(feature); - const productBodies = state.product ? [state.product.body] : []; - const isProduct = feature.makes.some((name) => productBodies.includes(name)); + const name = plainName(feature); + const failed = isFailed(feature); + // No "product" badge: in a chain of steps the part is the last one, as in any feature tree. When it is not, or when + // several solids are open, the banners above the list say so and offer the choice (the product is chosen, never + // guessed: design-docs/part-holds-one-solid.md). const canEdit = Boolean(feature.gui && spec); const Icon = feature.gui ? FEATURE_ICONS[feature.gui.spec] : CODE_FEATURE_ICON; const sketch = sketches?.infos.find((info) => info.cell === feature.cell); @@ -193,31 +245,33 @@ export function FeatureTree({ onMouseLeave={sketch ? () => sketches?.onHover(null) : undefined} onClick={sketch ? (event) => { if ((event.target as HTMLElement).closest("button")) return; - sketches?.onSelect(sketch.name, event.ctrlKey || event.metaKey); + const click = rowClick(sketch.name, sketches?.selected ?? [], event.ctrlKey || event.metaKey); + if (click.kind === "clear") sketches?.onSelect(null, false); // the picked row again: nothing picked + else sketches?.onSelect(sketch.name, click.additive); } : undefined} >
    - {feature.index} + {position + 1} {Icon ? : } - {feature.slug} - {isProduct && ( - - {t("product")} - - )} - {t(feature.role)} + {name} {sketch && sketch.usedBy.length > 0 && ( {t("used")} )} - {spec ? plainLabel(spec.id, spec.label) : feature.gui ? feature.gui.spec.replace(/_/g, " ") : "code"}
    - ${feature.makes.join(", ")}`}> - {feature.reads.length > 0 ? feature.reads.join(", ") : "start"} {feature.makes.length > 0 ? feature.makes.join(", ") : "no body"} - + {(() => { + // what the step does, in a sentence: its written note (# 说明:…), else what it builds on + const lineage = feature.reads.length > 0 ? t("builds on {{names}}", { names: feature.reads.map((body) => `「${bodyName(body)}」`).join(t(", ")) }) : t("a new shape"); + const text = feature.note || lineage; + return ( + + {text} + + ); + })()} {sketch && ( )} - + @@ -256,9 +310,9 @@ export function FeatureTree({
    - {problem &&

    {problem}

    } - {problem && onRepairRef && spec?.slots.some((slot) => slot.kind === "select") && ( - onRepairRef(feature.cell, slot, index, choice)} /> + {failed && } + {failed && onRepairRef && spec?.slots.some((slot) => slot.kind === "select") && ( + onRepairRef(feature.cell, slot, index, choice)} /> )} ); diff --git a/editor-web/src/components/FloatingPanels.tsx b/editor-web/src/components/FloatingPanels.tsx index b57007ef..2a13c29c 100644 --- a/editor-web/src/components/FloatingPanels.tsx +++ b/editor-web/src/components/FloatingPanels.tsx @@ -1,6 +1,7 @@ import { useState, type ReactNode } from "react"; import { ChevronsRight, ScanSearch } from "lucide-react"; +import { useFloatingDrag } from "@/lib/useFloatingDrag"; import { useSizeTransition } from "@/lib/useSizeTransition"; import { cn } from "@/lib/utils"; import { t } from "@/i18n"; @@ -55,12 +56,19 @@ export function FloatingPanels({ }) { const [inspectorOpen, setInspectorOpen] = useRemembered("sca.floating.inspector"); const inspectorBox = useSizeTransition(inspectorOpen); + // the person moves these out of each other's way: the inspector by its header, the notice anywhere on it + const inspectorDrag = useFloatingDrag("sca.floating.inspector.at"); + const noticeDrag = useFloatingDrag("sca.floating.notice.at", { anywhere: true }); return (
    {!task && leftNotice &&
    {leftNotice}
    }
    { + inspectorBox.current = element; + inspectorDrag.bind.ref(element); + }} className={cn(CARD, "relative flex flex-col overflow-hidden", inspectorOpen ? "max-h-[70%] w-full" : "hover:bg-accent")} data-testid={inspectorOpen ? "floating-inspector" : undefined} > @@ -84,7 +92,11 @@ export function FloatingPanels({ )}
    - {rightNotice &&
    {rightNotice}
    } + {rightNotice && ( +
    + {rightNotice} +
    + )}
    {!task && (
    diff --git a/editor-web/src/components/Header.tsx b/editor-web/src/components/Header.tsx index b4f1bb62..f653fce4 100644 --- a/editor-web/src/components/Header.tsx +++ b/editor-web/src/components/Header.tsx @@ -1,4 +1,4 @@ -import { Languages, Monitor, Moon, Sun } from "lucide-react"; +import { Download, Languages, Monitor, Moon, Sun } from "lucide-react"; import type { ThemePreference } from "@/lib/theme"; @@ -15,6 +15,7 @@ export function Header({ status, themePreference, onTheme, + onExport, }: { notebook: string | null; kind: string | null; @@ -22,6 +23,8 @@ export function Header({ status: string; themePreference: ThemePreference; onTheme: () => void; + /** Write STEP and STL of the model next to the notebook (in out/); absent: no button. */ + onExport?: () => void; }) { const { t, language } = useI18n(); const failing = status.startsWith("error"); @@ -32,8 +35,8 @@ export function Header({ {notebook ? ( - {notebook} - {kind && kind !== "helper" && {kind}} + {notebook.replace(/\.py$/, "")} + {kind && kind !== "helper" && {t(kind)}} ) : ( {t("no notebook")} @@ -48,6 +51,18 @@ export function Header({ > {status} + {onExport && ( + + )}
)}
@@ -71,6 +94,39 @@ export function Inspector({ selection, sketches = [] }: { selection: SelectionIt ); } +/** Measured numbers: a label, the value with its unit, and a button that copies the plain number. */ +function Rows({ rows }: { rows: MeasureRow[] }) { + if (!rows.length) return

{t("Nothing to measure here")}

; + return ( +
+ {rows.map((row) => ( +
+
{t(row.label)}
+
+ {row.value} {row.unit && {row.unit}} +
+ {row.copy && ( + + )} +
+ ))} +
+ ); +} + function Line({ label, value }: { label: string; value: string }) { return (
diff --git a/editor-web/src/components/ParamControl.tsx b/editor-web/src/components/ParamControl.tsx index 182503fc..dbae416a 100644 --- a/editor-web/src/components/ParamControl.tsx +++ b/editor-web/src/components/ParamControl.tsx @@ -1,4 +1,5 @@ import { useEffect, useRef, useState } from "react"; +import { plainParamLabel } from "@/lib/plain-label"; import { Slider } from "@/components/ui/slider"; import { cn } from "@/lib/utils"; @@ -28,10 +29,11 @@ export type ParamMeta = { export function ParamControl({ param, forwardParam, - editable = false, + editable = true, }: { param: ParamMeta; - /** A slider also has a box to type the value in (the operation panel: exact values matter while tuning). */ + /** A slider also has a box to type the value in (on by default: a person who knows the number types it rather than drags to + * it); false leaves the slider alone. */ editable?: boolean; /** `now`: send at once (a click, a release) instead of when the changes settle. */ forwardParam: (id: string, value: ParamValue, now?: boolean) => void; @@ -43,7 +45,7 @@ export function ParamControl({ useEffect(() => { if (!dragging.current) setDrag(null); }, [param.value]); - const label = param.label || param.id; + const label = plainParamLabel(param.label || param.id); const title = [param.comment, ...(param.issues ?? [])].filter(Boolean).join("\n") || undefined; const ink = param.modified ? "text-focus" : "text-name"; if (param.control === "toggle") { diff --git a/editor-web/src/components/PartialModel.tsx b/editor-web/src/components/PartialModel.tsx index f618e763..4d8a1bb9 100644 --- a/editor-web/src/components/PartialModel.tsx +++ b/editor-web/src/components/PartialModel.tsx @@ -9,8 +9,13 @@ import { t } from "@/i18n"; * whole model replaces it; the failing step is marked in the feature tree as well. */ /** `docked`: laid out in a column of floating cards (manual mode) instead of pinned to the viewport's top right corner. */ export function PartialNotice({ partial, titles, docked = false }: { partial: PartialModel; titles: ReadonlyMap; docked?: boolean }) { - const { title, reason, after } = useMemo(() => describePartial(partial, titles), [partial, titles]); + const { after } = useMemo(() => describePartial(partial, titles), [partial, titles]); const full = partial.failed.map((cell) => cell.error).filter(Boolean).join("\n"); + // in a person's words: which step, that it did not work; the program's own message stays in the tooltip and the tree + const first = partial.failed[0]; + const step = titles.get(first.cell) || first.name; + const title = t("Showing the model before「{{step}}」", { step }); + const reason = first.status === "interrupted" ? t("「{{step}}」was stopped", { step }) : t("「{{step}}」did not work", { step }); return (
; picked: Record; refs?: Record } | null; makes: string[]; @@ -169,7 +172,7 @@ export function refTone(state: RefState): "pass" | "warn" | "fail" { export function candidateLabel(candidate: RefCandidate): string { const at = candidate.center.map((v) => (Math.abs(v) < 5e-5 ? "0" : String(Math.round(v * 10) / 10))).join(", "); const unit = candidate.kind === "edge" ? "mm" : "mm²"; - return `${candidate.geom_type.toLowerCase()} at (${at}), ${Math.round(candidate.size * 10) / 10} ${unit}`; + return t("{{kind}} at ({{at}}), {{size}} {{unit}}", { kind: t(candidate.geom_type.toLowerCase()), at, size: Math.round(candidate.size * 10) / 10, unit }); } /** How the references of a feature resolve now (asks the kernel). */ diff --git a/editor-web/src/lib/manual-mode.ts b/editor-web/src/lib/manual-mode.ts index 50e3ac7d..8d2d225a 100644 --- a/editor-web/src/lib/manual-mode.ts +++ b/editor-web/src/lib/manual-mode.ts @@ -1,6 +1,8 @@ /** - * Manual modelling (features, sketches, assemblies by buttons and dialogs) is built but not offered: it needs a plan of - * its own before it is a release. While this is false the editor has the code mode only: no mode switch, no command - * bar, none of its keys, and the notebook is where a model is made. Nothing of manual mode is removed. + * Manual modelling (features, sketches, assemblies by buttons and dialogs) is built but not offered by default: it needs a + * plan of its own before it is a release. While this is false the editor has the code mode only: no mode switch, no + * command bar, none of its keys, and the notebook is where a model is made. Nothing of manual mode is removed. + * + * `VITE_MANUAL_MODE=1 npm run dev` (or a build made with it) turns it on, to work on it without changing the release. */ -export const MANUAL_MODE = false; +export const MANUAL_MODE = import.meta.env.VITE_MANUAL_MODE === "1"; diff --git a/editor-web/src/lib/measure.test.ts b/editor-web/src/lib/measure.test.ts new file mode 100644 index 00000000..1abe5f5f --- /dev/null +++ b/editor-web/src/lib/measure.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from "vitest"; + +import { facing, fmt, measureItem, measureMany, measurePair, type MeasureItem } from "@/lib/measure"; + +const topFace: MeasureItem = { + kind: "face", + properties: { area: 1200, centroid: [0, 0, 20], bounds: { min: [-20, -15, 20], max: [20, 15, 20] } }, + geometry: { type: "plane", normal: [0, 0, 1] }, +}; +const bottomFace: MeasureItem = { + kind: "face", + properties: { area: 1200, centroid: [0, 0, 0], bounds: { min: [-20, -15, 0], max: [20, 15, 0] } }, + geometry: { type: "plane", normal: [0, 0, -1] }, +}; +const sideFace: MeasureItem = { + kind: "face", + properties: { area: 600, centroid: [20, 0, 10] }, + geometry: { type: "plane", normal: [1, 0, 0] }, +}; + +describe("fmt", () => { + it("keeps two decimals at most and drops -0", () => { + expect(fmt(12.3456)).toBe("12.35"); + expect(fmt(40)).toBe("40"); + expect(fmt(-0.001)).toBe("0"); + }); +}); + +describe("facing", () => { + it("names an axis direction and calls anything else slanted", () => { + expect(facing([0, 0, 1])).toBe("facing up (+Z)"); + expect(facing([0, 0, -2])).toBe("facing down (−Z)"); + expect(facing([0.7, 0, 0.7])).toBe("slanted"); + }); +}); + +describe("measureItem", () => { + it("gives a flat face its direction, area, size and centre", () => { + const m = measureItem(topFace); + expect(m.titleValues).toEqual({ kind: "Flat face", way: "facing up (+Z)" }); + expect(m.rows.map((r) => [r.label, r.value])).toEqual([ + ["Area", "1200"], + ["Size", "40 × 30"], + ["Centre", "(0, 0, 20)"], + ]); + }); + + it("gives a hole's wall its diameter", () => { + const m = measureItem({ kind: "face", properties: { area: 754 }, geometry: { type: "cylinder", radius: 6 } }); + expect(m.title).toBe("Cylindrical face"); + expect(m.rows[0]).toMatchObject({ label: "Diameter", value: "12" }); + }); + + it("tells a full circle from an arc, and gives a straight edge its length", () => { + expect(measureItem({ kind: "edge", properties: { length: 2 * Math.PI * 6 }, geometry: { type: "circle", radius: 6 } }).title).toBe("Circle"); + expect(measureItem({ kind: "edge", properties: { length: Math.PI * 6 }, geometry: { type: "circle", radius: 6 } }).title).toBe("Arc"); + const line = measureItem({ kind: "edge", properties: { length: 40 }, geometry: { type: "line" } }); + expect(line.title).toBe("Straight edge"); + expect(line.rows[0]).toMatchObject({ label: "Length", value: "40" }); + }); + + it("gives a solid its size, volume and surface area", () => { + const m = measureItem({ kind: "solid", properties: { bounds: { min: [-20, -15, 0], max: [20, 15, 20] }, volume: 24000, surface_area: 5200 } }); + expect(m.rows.map((r) => [r.label, r.value])).toEqual([ + ["Size (X × Y × Z)", "40 × 30 × 20"], + ["Volume", "24000"], + ["Surface area", "5200"], + ]); + }); +}); + +describe("measurePair", () => { + it("measures two parallel faces: the distance between them, no angle, and the centre offset", () => { + const rows = Object.fromEntries(measurePair(topFace, bottomFace).map((r) => [r.label, r.value])); + expect(rows["Distance between the faces"]).toBe("20"); + expect(rows.Angle).toBe("0"); + expect(rows["Centre distance"]).toBe("20"); + expect(rows["ΔX / ΔY / ΔZ"]).toBe("0 / 0 / 20"); + }); + + it("gives two faces at a right angle their angle and no face distance", () => { + const rows = Object.fromEntries(measurePair(topFace, sideFace).map((r) => [r.label, r.value])); + expect(rows.Angle).toBe("90"); + expect(rows["Distance between the faces"]).toBeUndefined(); + }); +}); + +describe("measureMany", () => { + it("adds up the faces' area and the edges' length", () => { + const rows = measureMany([topFace, bottomFace, sideFace, { kind: "edge", properties: { length: 40 } }]); + expect(rows.map((r) => [r.label, r.value])).toEqual([ + ["Total area", "3000"], + ["Total length", "40"], + ]); + }); +}); diff --git a/editor-web/src/lib/measure.ts b/editor-web/src/lib/measure.ts new file mode 100644 index 00000000..28c1ac01 --- /dev/null +++ b/editor-web/src/lib/measure.ts @@ -0,0 +1,133 @@ +/** What picked geometry measures, in a person's words: the inspector's top block (Onshape-style: picking is measuring). + * + * Built from what a pick already carries (properties: bounds, area, length, volume, surface_area, centroid, position; + * geometry: type, normal, radius), so nothing is asked of the kernel. Two items give the distance between their centres + * with its X/Y/Z parts, and for two flat faces the angle between them and, when they are parallel, the distance between the + * planes; more items give the total area or length. Words are English keys of the translation table. */ + +export type MeasureItem = { kind: string; properties?: Record | null; geometry?: Record | null }; +/** One line: `label` and `unit` are translation keys; `value` is the number as shown; `copy` the plain number to copy. */ +export type MeasureRow = { label: string; value: string; unit?: string; copy?: string }; +export type Measured = { title: string; titleValues?: Record; rows: MeasureRow[] }; + +type V3 = [number, number, number]; + +const vec = (value: unknown): V3 | null => + Array.isArray(value) && value.length >= 3 && value.slice(0, 3).every((n) => typeof n === "number" && Number.isFinite(n)) ? [value[0], value[1], value[2]] : null; +const num = (value: unknown): number | null => (typeof value === "number" && Number.isFinite(value) ? value : null); +const sub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; +const dot = (a: V3, b: V3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +const norm = (a: V3) => Math.hypot(a[0], a[1], a[2]); + +/** A number for a person: at most two decimals, no trailing zeros, no "-0". */ +export function fmt(value: number): string { + const rounded = Math.round(value * 100) / 100; + return String(Object.is(rounded, -0) ? 0 : rounded); +} + +const row = (label: string, value: number, unit?: string): MeasureRow => ({ label, value: fmt(value), unit, copy: fmt(value) }); + +/** Which way a flat face points, when it points along an axis (Z is up in this editor). */ +export function facing(normal: V3 | null): string | null { + if (!normal) return null; + const n = norm(normal); + if (!(n > 0)) return null; + const [x, y, z] = normal.map((c) => c / n); + const sides: [number, string][] = [ + [z, "facing up (+Z)"], [-z, "facing down (−Z)"], [x, "facing +X"], [-x, "facing −X"], [y, "facing +Y"], [-y, "facing −Y"], + ]; + const best = sides.find(([c]) => c > 0.999); + return best ? best[1] : "slanted"; +} + +function center(item: MeasureItem): V3 | null { + return vec(item.properties?.centroid) ?? vec(item.properties?.position) ?? vec(item.geometry?.position); +} + +function extents(item: MeasureItem): V3 | null { + const bounds = item.properties?.bounds as { min?: unknown; max?: unknown } | undefined; + const min = vec(bounds?.min); + const max = vec(bounds?.max); + return min && max ? sub(max, min) : null; +} + +/** One picked item: what it is and its key numbers. */ +export function measureItem(item: MeasureItem): Measured { + const p = item.properties ?? {}; + const g = item.geometry ?? {}; + const type = typeof g.type === "string" ? g.type : ""; + const radius = num(g.radius); + const rows: MeasureRow[] = []; + const middle = center(item); + if (item.kind === "face") { + const area = num(p.area); + if (type === "cylinder" && radius !== null) rows.push(row("Diameter", radius * 2, "mm")); + if (type === "sphere" && radius !== null) rows.push(row("Diameter", radius * 2, "mm")); + if (area !== null) rows.push(row("Area", area, "mm²")); + const size = extents(item); + if (size && type === "plane") { + const sides = size.filter((d) => d > 1e-6); + if (sides.length === 2) rows.push({ label: "Size", value: `${fmt(sides[0])} × ${fmt(sides[1])}`, unit: "mm" }); + } + if (middle) rows.push({ label: "Centre", value: `(${middle.map(fmt).join(", ")})`, unit: "mm" }); + const kind = { plane: "Flat face", cylinder: "Cylindrical face", sphere: "Spherical face", torus: "Ring face" }[type] ?? "Curved face"; + const way = type === "plane" ? facing(vec(g.normal)) : null; + return { title: way ? "{{kind}} · {{way}}" : kind, titleValues: way ? { kind, way } : undefined, rows }; + } + if (item.kind === "edge") { + const length = num(p.length); + const full = radius !== null && length !== null && Math.abs(length - 2 * Math.PI * radius) < 1e-3 * Math.max(1, length); + if (type === "circle" && radius !== null) rows.push(row("Diameter", radius * 2, "mm")); + if (length !== null) rows.push(row("Length", length, "mm")); + if (middle) rows.push({ label: "Centre", value: `(${middle.map(fmt).join(", ")})`, unit: "mm" }); + const kind = type === "line" ? "Straight edge" : type === "circle" ? (full ? "Circle" : "Arc") : "Curved edge"; + return { title: kind, rows }; + } + if (item.kind === "solid" || item.kind === "component") { + const size = extents(item); + if (size) rows.push({ label: "Size (X × Y × Z)", value: size.map(fmt).join(" × "), unit: "mm", copy: size.map(fmt).join(" × ") }); + const volume = num(p.volume); + if (volume !== null) rows.push(row("Volume", volume, "mm³")); + const surface = num(p.surface_area); + if (surface !== null) rows.push(row("Surface area", surface, "mm²")); + if (middle) rows.push({ label: "Centre of mass", value: `(${middle.map(fmt).join(", ")})`, unit: "mm" }); + return { title: item.kind === "component" ? "Component" : "Solid", rows }; + } + if (item.kind === "vertex") { + if (middle) rows.push({ label: "Position", value: `(${middle.map(fmt).join(", ")})`, unit: "mm" }); + return { title: "Point", rows }; + } + return { title: item.kind, rows }; +} + +/** Two picked items: the distance between their centres and its parts; two flat faces add their angle, and the distance + * between them when they are parallel. */ +export function measurePair(a: MeasureItem, b: MeasureItem): MeasureRow[] { + const rows: MeasureRow[] = []; + const ca = center(a); + const cb = center(b); + const na = a.geometry?.type === "plane" ? vec(a.geometry?.normal) : null; + const nb = b.geometry?.type === "plane" ? vec(b.geometry?.normal) : null; + if (na && nb && norm(na) > 0 && norm(nb) > 0) { + const cos = Math.min(1, Math.abs(dot(na, nb)) / (norm(na) * norm(nb))); + const angle = (Math.acos(cos) * 180) / Math.PI; + if (angle < 0.01 && ca && cb) rows.push(row("Distance between the faces", Math.abs(dot(sub(cb, ca), na)) / norm(na), "mm")); + rows.push(row("Angle", angle, "°")); + } + if (ca && cb) { + const d = sub(cb, ca); + rows.push(row("Centre distance", norm(d), "mm")); + rows.push({ label: "ΔX / ΔY / ΔZ", value: d.map((c) => fmt(Math.abs(c))).join(" / "), unit: "mm", copy: d.map((c) => fmt(Math.abs(c))).join(" / ") }); + } + return rows; +} + +/** Three or more items: the total area of the faces and the total length of the edges among them. */ +export function measureMany(items: readonly MeasureItem[]): MeasureRow[] { + const area = items.filter((i) => i.kind === "face").reduce((sum, i) => sum + (num(i.properties?.area) ?? 0), 0); + const length = items.filter((i) => i.kind === "edge").reduce((sum, i) => sum + (num(i.properties?.length) ?? 0), 0); + const rows: MeasureRow[] = []; + if (area > 0) rows.push(row("Total area", area, "mm²")); + if (length > 0) rows.push(row("Total length", length, "mm")); + return rows; +} diff --git a/editor-web/src/lib/plain-label.test.ts b/editor-web/src/lib/plain-label.test.ts new file mode 100644 index 00000000..0112a47b --- /dev/null +++ b/editor-web/src/lib/plain-label.test.ts @@ -0,0 +1,47 @@ +import { beforeAll, describe, expect, it } from "vitest"; + +import i18n from "@/i18n"; +import { plainParamLabel, sdkErrorParts } from "@/lib/plain-label"; + +describe("plainParamLabel", () => { + beforeAll(async () => { + await i18n.changeLanguage("zh-CN"); + }); + + it("uses the table for a whole label", () => { + expect(plainParamLabel("Width (x)")).toBe("宽度(x)"); + }); + + it("translates a point coordinate's label as its slot label and axis", () => { + expect(plainParamLabel("Bottom face centre x")).toBe(`${i18n.t("Bottom face centre")} x`); + expect(plainParamLabel("Bottom face centre x")).not.toContain("Bottom"); + }); + + it("keeps a label it cannot translate", () => { + expect(plainParamLabel("frobnicate z")).toBe("frobnicate z"); + }); +}); + +describe("sdkErrorParts", () => { + const full = [ + "SimpleCADError: Operation: shell_rsolid", + "What happened: Failed to apply the shell operation.", + "Possible causes:", + "- The thickness is not a positive finite scalar.", + "- No valid faces were selected for removal.", + "How to fix:", + "- Use a positive shell thickness.", + "Technical details: ValueError: Shell failed", + ].join("\n"); + + it("reads what happened, the causes and the fixes from the fullest text, not a cut-short one", () => { + const parts = sdkErrorParts(["SimpleCADError: Operation: shell_rsolid\nWhat happened: F", full]); + expect(parts.what).toBe("Failed to apply the shell operation."); + expect(parts.causes).toEqual(["The thickness is not a positive finite scalar.", "No valid faces were selected for removal."]); + expect(parts.fixes).toEqual(["Use a positive shell thickness."]); + }); + + it("gives nothing it cannot find", () => { + expect(sdkErrorParts(["boom"])).toMatchObject({ what: null, causes: [], fixes: [], full: "boom" }); + }); +}); diff --git a/editor-web/src/lib/plain-label.ts b/editor-web/src/lib/plain-label.ts new file mode 100644 index 00000000..cd17f956 --- /dev/null +++ b/editor-web/src/lib/plain-label.ts @@ -0,0 +1,46 @@ +import { t } from "@/i18n"; + +/** A parameter's label in the person's language: the label itself when the table has it, else a point coordinate's label + * ("Bottom face centre x": the slot's label, then its axis) as the translated slot label and the axis. */ +export function plainParamLabel(label: string): string { + const whole = t(label); + if (whole !== label) return whole; + const axis = /^(.*\S) ([xyz])$/.exec(label); + if (axis) { + const base = t(axis[1]); + if (base !== axis[1]) return `${base} ${axis[2]}`; + } + return label; +} + +/** A feature command's error in the person's words where it is a known one (undo or redo refused because the code changed + * since, or nothing left to undo), else the error as the server said it. */ +export function plainGuiError(message: string): string { + const refused = /^cannot (undo|redo): the notebook changed since/.exec(message); + if (refused) + return refused[1] === "undo" + ? t("Can't undo: this step's code was changed somewhere else afterwards (in the code, or by the AI). Undo stopped so it won't overwrite that change.") + : t("Can't redo: the code was changed somewhere else afterwards (in the code, or by the AI). Redo stopped so it won't overwrite that change."); + if (message === "nothing to undo") return t("Nothing left to undo."); + if (message === "nothing to redo") return t("Nothing left to redo."); + return message; +} + +/** The parts of the SDK's error messages ("What happened:", "Possible causes:", "How to fix:"), from the fullest of the + * texts a failed step carries (one of them may be a cut-short summary, a single letter). */ +export function sdkErrorParts(texts: readonly string[]): { what: string | null; causes: string[]; fixes: string[]; full: string } { + const full = [...texts].sort((a, b) => b.length - a.length)[0] ?? ""; + const lines = full.split("\n").map((line) => line.trim()); + const what = lines.find((line) => line.startsWith("What happened:"))?.replace("What happened:", "").trim() || null; + const list = (title: string) => { + const at = lines.indexOf(title); + if (at === -1) return []; + const out: string[] = []; + for (const line of lines.slice(at + 1)) { + if (!line.startsWith("-")) break; + out.push(line.replace(/^-\s*/, "")); + } + return out; + }; + return { what, causes: list("Possible causes:"), fixes: list("How to fix:"), full }; +} diff --git a/editor-web/src/lib/tree-click.test.ts b/editor-web/src/lib/tree-click.test.ts new file mode 100644 index 00000000..73b960f4 --- /dev/null +++ b/editor-web/src/lib/tree-click.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest"; + +import { rowClick } from "@/lib/tree-click"; + +describe("rowClick", () => { + it("clears the selection when the only picked row is clicked again", () => { + expect(rowClick("sketch", ["sketch"], false)).toEqual({ kind: "clear" }); + }); + + it("picks a row that is not picked", () => { + expect(rowClick("sketch", [], false)).toEqual({ kind: "pick", additive: false }); + expect(rowClick("sketch", ["path"], false)).toEqual({ kind: "pick", additive: false }); + }); + + it("picks the clicked row alone when several are picked", () => { + expect(rowClick("sketch", ["sketch", "path"], false)).toEqual({ kind: "pick", additive: false }); + }); + + it("leaves Ctrl/Cmd+click to the additive pick", () => { + expect(rowClick("sketch", ["sketch"], true)).toEqual({ kind: "pick", additive: true }); + }); +}); diff --git a/editor-web/src/lib/tree-click.ts b/editor-web/src/lib/tree-click.ts new file mode 100644 index 00000000..4d7b887d --- /dev/null +++ b/editor-web/src/lib/tree-click.ts @@ -0,0 +1,9 @@ +/** What a click on a row of the feature tree does to the selection, the way every file list does it: a plain click on the one + * row already picked clears the selection, a plain click on another row picks that row alone, and Ctrl/Cmd+click adds or takes + * out the row (the caller's additive pick). */ +export type RowClick = { kind: "clear" } | { kind: "pick"; additive: boolean }; + +export function rowClick(name: string, selected: readonly string[], additive: boolean): RowClick { + if (!additive && selected.length === 1 && selected[0] === name) return { kind: "clear" }; + return { kind: "pick", additive }; +} diff --git a/editor-web/src/lib/useFloatingDrag.test.ts b/editor-web/src/lib/useFloatingDrag.test.ts new file mode 100644 index 00000000..0563629a --- /dev/null +++ b/editor-web/src/lib/useFloatingDrag.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vitest"; + +import { clampToView } from "@/lib/useFloatingDrag"; + +const view = { width: 1440, height: 900 }; +// the inspector as the layout puts it: against the right edge, below the top bar +const inspector = { left: 1130, top: 156, width: 300, height: 400 }; + +describe("clampToView", () => { + it("leaves an offset that keeps the card on screen as it is", () => { + expect(clampToView({ x: -400, y: 200 }, inspector, view)).toEqual({ x: -400, y: 200 }); + }); + + it("stops a card at the right edge from being pushed out to the right", () => { + // the right-hand limit is relative to the card: it may go only until 48 px of it are left on screen + expect(clampToView({ x: 600, y: 0 }, inspector, view).x).toBe(1440 - 48 - 1130); + }); + + it("stops a card going out to the left, above the window, or below it", () => { + const kept = clampToView({ x: -5000, y: -5000 }, inspector, view); + expect(kept).toEqual({ x: 48 - 1130 - 300, y: -156 }); + expect(clampToView({ x: 0, y: 5000 }, inspector, view).y).toBe(900 - 48 - 156); + }); +}); diff --git a/editor-web/src/lib/useFloatingDrag.ts b/editor-web/src/lib/useFloatingDrag.ts new file mode 100644 index 00000000..6a3e8df7 --- /dev/null +++ b/editor-web/src/lib/useFloatingDrag.ts @@ -0,0 +1,121 @@ +import { useCallback, useRef, useState, type CSSProperties, type PointerEvent } from "react"; + +/** How far a floating card is moved from where the layout puts it (px). */ +export type Offset = { x: number; y: number }; +/** Where the card sits with no offset (its layout box), and the window. */ +export type Box = { left: number; top: number; width: number; height: number }; + +/** The offset kept so the card stays reachable: at least `keep` px of it on screen left and right, its top (where the handle + * is) never above the window and at least `keep` px above its bottom. */ +export function clampToView(offset: Offset, base: Box, view: { width: number; height: number }, keep = 48): Offset { + const clamp = (v: number, low: number, high: number) => Math.min(Math.max(v, low), Math.max(low, high)); + return { + x: clamp(offset.x, keep - base.left - base.width, view.width - keep - base.left), + y: clamp(offset.y, -base.top, view.height - keep - base.top), + }; +} + +function read(key: string): Offset { + try { + const value = JSON.parse(window.localStorage.getItem(key) ?? "null") as Offset | null; + return value && Number.isFinite(value.x) && Number.isFinite(value.y) ? value : { x: 0, y: 0 }; + } catch { + return { x: 0, y: 0 }; + } +} + +function save(key: string, offset: Offset): void { + try { + window.localStorage.setItem(key, JSON.stringify(offset)); + } catch { + // storage blocked: the card stays where it is until the page reloads + } +} + +const view = () => ({ width: window.innerWidth, height: window.innerHeight }); + +/** A floating card the person can drag by its handle (an element inside it marked `data-drag-handle`, or the whole card when + * `anywhere`), remembered in this browser and always kept on screen. Buttons and fields inside the handle keep their clicks; + * two quick presses on the handle put the card back. Spread `bind` on the card. */ +export function useFloatingDrag(key: string, { anywhere = false }: { anywhere?: boolean } = {}) { + const [offset, setOffset] = useState(() => read(key)); + const offsetRef = useRef(offset); + offsetRef.current = offset; + const drag = useRef<{ from: { x: number; y: number }; start: Offset; base: Box; id: number; moving: boolean } | null>(null); + // the pointer is captured on press (so the card follows it anywhere), which retargets the browser's double-click to the + // card: the double-click that puts it back is told here instead, from two presses on the handle close in time and place + const lastPress = useRef<{ t: number; x: number; y: number } | null>(null); + const putBack = () => { + setOffset({ x: 0, y: 0 }); + save(key, { x: 0, y: 0 }); + }; + const onHandle = (target: EventTarget | null): boolean => { + const element = target as HTMLElement | null; + if (!element || element.closest("button, input, textarea, select, a, [role=slider]")) return false; + return anywhere || !!element.closest("[data-drag-handle]"); + }; + /** The card's layout box: where it is now, less the offset it is moved by. */ + const baseOf = (element: HTMLElement, by: Offset): Box => { + const r = element.getBoundingClientRect(); + return { left: r.left - by.x, top: r.top - by.y, width: r.width, height: r.height }; + }; + // A remembered offset from another window size could put the card out of reach: pull it back in once it is on screen. + const ref = useCallback( + (element: HTMLElement | null) => { + if (!element) return; + const current = offsetRef.current; + if (!current.x && !current.y) return; + const kept = clampToView(current, baseOf(element, current), view()); + if (kept.x !== current.x || kept.y !== current.y) { + setOffset(kept); + save(key, kept); + } + }, + [key], + ); + const finish = (element: HTMLElement, pointerId: number) => { + const d = drag.current; + if (!d) return; + drag.current = null; + if (element.hasPointerCapture?.(pointerId)) element.releasePointerCapture(pointerId); + if (!d.moving) return; // a click, not a drag + save(key, offsetRef.current); + }; + const style: CSSProperties = offset.x || offset.y ? { transform: `translate(${offset.x}px, ${offset.y}px)` } : {}; + return { + offset, + bind: { + ref, + style, + onPointerDown: (event: PointerEvent) => { + if (event.button !== 0 || !onHandle(event.target)) return; + event.preventDefault(); + const now = performance.now(); + const before = lastPress.current; + lastPress.current = { t: now, x: event.clientX, y: event.clientY }; + if (before && now - before.t < 400 && Math.hypot(event.clientX - before.x, event.clientY - before.y) < 6) { + lastPress.current = null; + drag.current = null; + putBack(); + return; + } + event.currentTarget.setPointerCapture(event.pointerId); + drag.current = { from: { x: event.clientX, y: event.clientY }, start: offset, base: baseOf(event.currentTarget, offset), id: event.pointerId, moving: false }; + }, + onPointerMove: (event: PointerEvent) => { + const d = drag.current; + if (!d || d.id !== event.pointerId) return; + if (!d.moving) { + if (Math.hypot(event.clientX - d.from.x, event.clientY - d.from.y) < 4) return; // a click, so far + d.moving = true; + } + const next = { x: d.start.x + event.clientX - d.from.x, y: d.start.y + event.clientY - d.from.y }; + setOffset(clampToView(next, d.base, view())); + }, + onPointerUp: (event: PointerEvent) => finish(event.currentTarget, event.pointerId), + // a drag the system breaks off (another window takes the pointer) ends here, so the card does not keep following + onPointerCancel: (event: PointerEvent) => finish(event.currentTarget, event.pointerId), + onLostPointerCapture: (event: PointerEvent) => finish(event.currentTarget, event.pointerId), + }, + }; +} diff --git a/src/simplecadapi/editor/gui_features.py b/src/simplecadapi/editor/gui_features.py index bff2d9e4..217a31c5 100644 --- a/src/simplecadapi/editor/gui_features.py +++ b/src/simplecadapi/editor/gui_features.py @@ -27,6 +27,17 @@ _PARAMS_FOR = re.compile(r"^#\s*-{3,}\s*params:\s*(?P[a-z][a-z0-9_]*)\s*-{3,}\s*$") _PRODUCT_BODY = re.compile(r"(\bbody\s*=\s*)([A-Za-z_][A-Za-z0-9_]*)") _ROLES_WITH_BODIES = {"build", "add", "subtract", "modifier", "intersect"} +# The tags a person writes over a feature cell: ``# name: ...`` / ``# note: ...``, or the Chinese words for "name" and +# "note" with an ASCII or a full-width colon (escaped here: the library's source stays English). +_TITLE = re.compile(r"^\s*#\s*(?:\u540d\u79f0|name)\s*[:\uff1a]\s*(?P.+?)\s*$", re.MULTILINE | re.IGNORECASE) +_NOTE = re.compile(r"^\s*#\s*(?:\u8bf4\u660e|note)\s*[:\uff1a]\s*(?P.+?)\s*$", re.MULTILINE | re.IGNORECASE) + + +def feature_words(code: str) -> tuple[str | None, str | None]: + """A feature cell's name and one-line note for a person, from its ``# name: ...`` and ``# note: ...`` comment lines + (or the same tags in Chinese).""" + title, note = _TITLE.search(code), _NOTE.search(code) + return (title.group("text") if title else None), (note.group("text") if note else None) class GuiError(Exception): @@ -66,6 +77,7 @@ def __init__(self, state: Any): self._lock = threading.RLock() self._undo: list[list[dict]] = [] self._redo: list[list[dict]] = [] + self._applying: list[dict] | None = None # the steps an undo or redo is applying (off both stacks meanwhile) self._notebook: Any = None # -- reading ---------------------------------------------------------------------------------------------------- @@ -128,6 +140,8 @@ def snapshot(self) -> dict[str, Any]: "index": index + 1, "slug": head.slug, "role": head.role, + "title": feature_words(code)[0], + "note": feature_words(code)[1], "gui": { "spec": gui["spec"], "values": gui.get("values", {}), @@ -515,8 +529,12 @@ def undo(self) -> dict[str, Any]: if not self._undo: raise GuiError("nothing to undo") steps = self._undo.pop() - for step in reversed(steps): - self._apply(step, forward=False) + self._applying = steps # off both stacks while it runs: _rename must still reach it + try: + for step in reversed(steps): + self._apply(step, forward=False) + finally: + self._applying = None self._redo.append(steps) return self._result(None, [], "undo") @@ -526,11 +544,31 @@ def redo(self) -> dict[str, Any]: if not self._redo: raise GuiError("nothing to redo") steps = self._redo.pop() - for step in steps: - self._apply(step, forward=True) + self._applying = steps # off both stacks while it runs: _rename must still reach it + try: + for step in steps: + self._apply(step, forward=True) + finally: + self._applying = None self._undo.append(steps) return self._result(None, [], "redo") + def follow(self, changes: Mapping[str, tuple[str, str]]) -> None: + """Cells the person changed through the GUI outside a command (a slider's value kept into its params cell): the + history takes the new code as the cell's, so undo and redo go on from it. ``changes`` maps a cell id to + (old code, new code); a step remembers a cell's code only where it equals the old one. An edit made in the code + itself does not come here: undoing over that is still refused, never forced.""" + with self._lock: + for steps in (*self._undo, *self._redo): + for step in steps: + change = changes.get(step.get("id", "")) + if change is None: + continue + old, new = change + for key in ("code", "old", "new"): + if isinstance(step.get(key), str) and step[key].strip() == old.strip(): + step[key] = new + # -- internals ------------------------------------------------------------------------------------------------------ def _sync(self) -> None: """History belongs to one open notebook.""" @@ -701,7 +739,7 @@ def _apply(self, step: dict, *, forward: bool) -> None: raise GuiError(f"cannot {'redo' if forward else 'undo'}: the notebook changed since ({exc})", conflict=exc.conflict) from exc def _rename(self, old: str, new: str) -> None: - for steps in (*self._undo, *self._redo): + for steps in (*self._undo, *self._redo, *([self._applying] if self._applying else [])): for step in steps: if step.get("id") == old: step["id"] = new diff --git a/src/simplecadapi/editor/server.py b/src/simplecadapi/editor/server.py index b99e7a65..c2de9307 100644 --- a/src/simplecadapi/editor/server.py +++ b/src/simplecadapi/editor/server.py @@ -146,6 +146,7 @@ def __init__(self, workspace: Path, notebook: Path | None = None) -> None: # A cell failed and the model shown is the one before it: {failed, skipped, shown} (see runtime.live.preview_product) self.partial: dict | None = None self.latest_package_bytes: bytes | None = None # a full package, made on demand (export) + self.exported_files: dict[str, Path] = {} # file name -> path, of the last export (served for "save as") # The latest preview (replaced as a whole, so a reader on another thread never sees half of one) and the # parts of it by key: a page is sent only the parts it lacks. self._model = _Model(None, frozenset(), None) @@ -1565,6 +1566,8 @@ def _commit(self, kernel: MarimoKernel, names: list[str], *, revert: bool) -> No for cell_id, code in changed.items(): kernel.edit_cell(cell_id, code) kernel.wait_idle() + # the person kept the value through the GUI: undo and redo follow it (an edit in the code is not this) + self.features.follow({cell_id: (codes[cell_id], code) for cell_id, code in changed.items()}) for name in names: saved.pop(name, None) write_saved_params(config, saved) @@ -1787,7 +1790,18 @@ def _export(self) -> None: target = self.notebook.parent / "out" / f"{self.notebook.stem}.scadpkg" target.parent.mkdir(parents=True, exist_ok=True) target.write_bytes(self.latest_package_bytes) - self.hub.broadcast({"type": "status", "exported": str(target)}) + written = [target.name] + # the files a person takes elsewhere (a CAD program, a slicer); each is made on its own, so one that fails keeps the other + from ..exporter import export_product_package_to_step, export_product_package_to_stl + + for suffix, make in ((".step", export_product_package_to_step), (".stl", export_product_package_to_stl)): + try: + make(target, target.with_suffix(suffix)) + written.append(target.with_suffix(suffix).name) + except Exception as error: # noqa: BLE001 - reported to the person, the package is still written + self.hub.broadcast({"type": "status", "error": f"{suffix[1:].upper()} export failed: {error}"[:300]}) + self.exported_files = {name: target.parent / name for name in written} + self.hub.broadcast({"type": "status", "exported": f"{target.parent} ({', '.join(written)})", "export_dir": str(target.parent), "export_files": written}) def _upstream_of(cells: list[dict]) -> dict[str, set[str]]: @@ -1820,6 +1834,17 @@ def walk(cid: str) -> set[str]: return {cid: walk(cid) for cid in refs} + +def _attachment(name: str) -> str: + """A ``Content-Disposition`` that downloads *name* under its own name, also when it is not ASCII (a Chinese notebook + name): HTTP headers are Latin-1, so the name goes as RFC 5987 ``filename*``, with an ASCII ``filename`` for old + clients.""" + from urllib.parse import quote + + fallback = name.encode("ascii", "replace").decode("ascii").replace('"', "_").replace("\\", "_") + return f"attachment; filename=\"{fallback}\"; filename*=UTF-8''{quote(name, safe='')}" + + def _module_code(code: str) -> str: """marimo's code_mode compiles cell code as a MODULE: a ``return`` in the cell's own scope (normal in marimo's file format) is a SyntaxError there. @@ -2095,6 +2120,17 @@ async def latest_package(request: Request) -> Response: ) return JSONResponse({"error": "no package made yet"}, status_code=404) + async def exported_file(request: Request) -> Response: + """One file of the last export, by its name, for the webui's "save as" (only names that export wrote are served).""" + path = state.exported_files.get(request.path_params["name"]) + if path is None or not path.is_file(): + return JSONResponse({"error": "no such exported file; export first"}, status_code=404) + return Response( + content=path.read_bytes(), + media_type="application/octet-stream", + headers={"Content-Disposition": _attachment(path.name)}, + ) + async def api_cells(request: Request) -> JSONResponse: """The open notebook's cells, with their state (for ``sca cell ls``).""" report = await asyncio.to_thread(state.cells_report) @@ -2392,6 +2428,7 @@ async def ws_endpoint(websocket) -> None: Route("/api/preview/refine", refine_preview, methods=["POST"]), Route("/api/runtime/package", push_package, methods=["POST"]), Route("/api/package/latest", latest_package, methods=["GET"]), + Route("/api/export/file/{name}", exported_file, methods=["GET"]), Route("/api/sdk", sdk_index, methods=["GET"]), Route("/api/cells", api_cells, methods=["GET"]), Route("/api/cells/{op}", api_cell_command, methods=["POST"]), diff --git a/test/test_editor.py b/test/test_editor.py index 5a2c6eaf..9aa79274 100644 --- a/test/test_editor.py +++ b/test/test_editor.py @@ -1659,3 +1659,28 @@ def test_a_deleted_notebook_is_kept_in_the_trash_and_the_last_open_one_stays(sel self.assertIn("only notebook", refused.json()["error"]) self.assertTrue(first.exists()) self.assertEqual(client.post("/api/workspace/delete", json={"path": "../x.py"}).status_code, 400) + + +class ExportedFileTest(unittest.TestCase): + """The page's "save as" downloads an exported file under its own name, a Chinese one too (review of #103).""" + + def test_a_non_ascii_name_is_sent_in_the_rfc_5987_form(self) -> None: + from starlette.testclient import TestClient + + from simplecadapi.editor.server import create_app + + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + first = create_notebook(root, "first", "sample") + out = root / "out" / "法兰.step" + out.parent.mkdir() + out.write_bytes(b"ISO-10303-21;") + state = WorkspaceState(root, first) + state.exported_files = {"法兰.step": out} + client = TestClient(create_app(state)) + reply = client.get("/api/export/file/%E6%B3%95%E5%85%B0.step") + self.assertEqual(reply.status_code, 200) + self.assertEqual(reply.content, b"ISO-10303-21;") + disposition = reply.headers["content-disposition"] + self.assertIn("filename*=UTF-8''%E6%B3%95%E5%85%B0.step", disposition) + self.assertTrue(disposition.isascii()) diff --git a/test/test_editor_features.py b/test/test_editor_features.py index b8a39a93..ff8750b0 100644 --- a/test/test_editor_features.py +++ b/test/test_editor_features.py @@ -291,6 +291,49 @@ def test_the_commands_add_edit_undo_and_redo_against_the_real_editor(tmp_path): server.should_exit = True +def test_numbers_tuned_on_the_sliders_and_kept_do_not_break_undo_and_redo(tmp_path): + """Keeping a slider's value writes it into the params cell; that is the person's own GUI edit, so undo and redo follow it.""" + import threading + + import uvicorn + + from simplecadapi.editor.server import WorkspaceState, create_app + from simplecadapi.editor.templates import create_notebook + from simplecadapi.runtime.params import write_saved_params + + path = create_notebook(tmp_path, "bracket", "sample") + state = WorkspaceState(tmp_path) + state.port = 17733 + server = uvicorn.Server(uvicorn.Config(create_app(state), port=state.port, log_level="error")) + threading.Thread(target=server.run, daemon=True).start() + state.hub.attach_loop(__import__("asyncio").new_event_loop()) + try: + state.start_kernel(path) + service = state.features + before = [c["code"] for c in state.cells] + service.add({"spec": "hole", "values": {"position": [0.0, 0.0, 10.0], "direction": "-z", "diameter": 8.0, "depth": 12.0}}) + _wait_idle(state) + # the slider moved and the person kept it (Enter): the value goes into the source + write_saved_params(state.config, {"HOLE_DIAMETER": 9.0}) + state._commit(state.kernel, ["HOLE_DIAMETER"], revert=False) + _wait_idle(state) + assert "default=9.0" in path.read_text() + + service.undo() + _wait_idle(state) + assert [c["code"] for c in state.cells] == before + service.redo() + _wait_idle(state) + assert "default=9.0" in path.read_text() # redo brings back what was kept, not the first default + service.undo() + _wait_idle(state) + assert [c["code"] for c in state.cells] == before + finally: + if state.kernel is not None: + state.kernel.stop() + server.should_exit = True + + def test_a_blank_notebook_gets_its_product_with_the_first_feature(tmp_path): import threading