editor: several open solids have no product until the author picks one (use_as_product), and say so
DECISION: the editor keeps letting solids exist side by side (a tool next to its body), but they are no longer
the bodies of one implicit Part. With exactly one open solid the Part is implicit as before; with several the
notebook has no product yet and the editor asks the author which solid is the part.
WHY - THE DISCUSSION (owner and assistant, 2026-11-10; full account in design-docs/part-holds-one-solid.md)
This is the editor need that started the whole multi-body Part: several solids in one notebook with no
assembly constraint (pattern a tool, then cut). The owner's judgement was that solving it inside the Part
makes assembly hard and was wrong; the agreed answer was "a Part is one solid, and the editor supports the
several solids some other way". This commit is that other way at the editor: the solids stay visible and
editable (the preview draws them, commit "runtime + preview"), and the product is chosen, never guessed. A
guess would silently leave a solid out of the exported Part; the author knows which solid is the part.
WHAT CHANGES
- editor/gui_features.py
- snapshot(): the implicit product exists only for exactly one open solid (and its dict loses `bodies`);
several open solids give `product: null` while `open` still lists them.
- use_as_product(): when the notebook has no product, a part notebook and a body that is open, it writes
the product cell `<stem> = scad.make_part_rpart(part_id=scad.notebook_id(), body=<chosen>)`. Before, it
refused ("no product cell"), which would have left the author without a way out.
- editor-web
- FeatureTree: a notice with one "use <solid>" button per open solid while there is no product and
several solids are open ("N solids are open, and a Part holds exactly one solid. Choose the part:").
The product badge reads the one product body.
- features.ts: FeatureState.product loses `bodies`.
- preview.ts previewSummary: nodes `node/<id>/body:<name>` are now the notebook's open solids, not the
bodies of a part, so the header says "N open solids" (zh-CN strings added) instead of "1 part · N bodies".
- tests: test_editor / test_editor_features follow the new product dict and the required `body` argument
of Part; a new test drives the editor flow end to end (two open solids -> no product, a headless run
raises SeveralOpenBodiesError naming them -> use_as_product -> the Part exists and the notebook runs).
Checked: editor-web vitest (331 tests) and tsc --noEmit pass; the editor test files pass except for the
multi-body fixtures of other files, which are updated in the tests commit of the series.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -155,6 +155,16 @@ export function FeatureTree({
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{!state.product && state.open.length > 1 && (
|
||||
<div className="flex flex-wrap items-center gap-2 border-b-2 border-focus bg-accent px-3 py-1.5 text-[11px]">
|
||||
<span className="min-w-0 flex-1">{t("{{count}} solids are open, and a Part holds exactly one solid. Choose the part:", { count: state.open.length })}</span>
|
||||
{state.open.map((body) => (
|
||||
<Button key={body} type="button" size="sm" className="h-6 px-2" disabled={busy} onClick={() => onUseProduct(body)}>
|
||||
{t("use {{body}}", { body })}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{error && <div className="border-b border-fail px-3 py-1 text-[11px] text-fail">{error}</div>}
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
{state.features.length === 0 ? (
|
||||
@@ -164,7 +174,7 @@ export function FeatureTree({
|
||||
{state.features.map((feature) => {
|
||||
const spec = feature.gui ? catalog?.specs.find((item) => item.id === feature.gui?.spec) : undefined;
|
||||
const problem = errorText(feature);
|
||||
const productBodies = state.product ? (state.product.bodies ?? [state.product.body]) : [];
|
||||
const productBodies = state.product ? [state.product.body] : [];
|
||||
const isProduct = feature.makes.some((name) => productBodies.includes(name));
|
||||
const canEdit = Boolean(feature.gui && spec);
|
||||
const Icon = feature.gui ? FEATURE_ICONS[feature.gui.spec] : CODE_FEATURE_ICON;
|
||||
|
||||
@@ -1205,6 +1205,9 @@
|
||||
"unused": "未使用",
|
||||
"use picked face": "使用所选面",
|
||||
"use {{body}}": "使用 {{body}}",
|
||||
"1 open solid": "1 个开放实体",
|
||||
"{{count}} open solids": "{{count}} 个开放实体",
|
||||
"{{count}} solids are open, and a Part holds exactly one solid. Choose the part:": "有 {{count}} 个开放实体,而一个零件只能有一个实体。请选择作为零件的那个:",
|
||||
"use_as_product": "设为产品",
|
||||
"used": "已使用",
|
||||
"used by": "被使用于",
|
||||
|
||||
@@ -68,8 +68,9 @@ export type FeatureState = {
|
||||
bodies: { name: string; produces: string }[];
|
||||
open: string[];
|
||||
tip: string | null;
|
||||
/** The body the notebook's Part is built from: by a product cell, or (`implicit`, no cell) by the runtime from the open body. */
|
||||
product: { cell: string | null; body: string; bodies?: string[]; implicit?: boolean } | null;
|
||||
/** The body the notebook's Part is built from: by a product cell, or (`implicit`, no cell) by the runtime from the one open body.
|
||||
* A Part holds exactly one solid: with several open solids and no product cell this is null and the author chooses. */
|
||||
product: { cell: string | null; body: string; implicit?: boolean } | null;
|
||||
defaults: Record<string, Record<string, string>>;
|
||||
/** The face-making sketches of the notebook (what a `profile` slot chooses from). */
|
||||
profiles?: { name: string; plane: string | { origin: number[]; x_axis: number[]; y_axis: number[] }; normal: string; normal_vec?: [number, number, number] }[];
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
describe("the header's count of a preview", () => {
|
||||
it("counts parts, and the bodies of a multi-body part", async () => {
|
||||
it("counts parts, and the open solids of a notebook that has no Part yet (a Part holds one solid)", async () => {
|
||||
const { previewSummary } = await import("@/lib/preview");
|
||||
expect(previewSummary([{ nodeId: "node/plate" }])).toBe("1 part");
|
||||
expect(previewSummary([{ nodeId: "node/body/body:base" }, { nodeId: "node/body/body:post" }])).toBe("1 part · 2 bodies");
|
||||
expect(previewSummary([{ nodeId: "node/body/body:base" }, { nodeId: "node/body/body:tool" }])).toBe("2 open solids");
|
||||
expect(previewSummary([{ nodeId: "node/body/body:base" }])).toBe("1 open solid");
|
||||
expect(previewSummary([{ nodeId: "node/a" }, { nodeId: "node/b" }])).toBe("2 parts");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -132,16 +132,19 @@ export function parsePreview(buffer: ArrayBuffer, cache: ReadonlyMap<string, Pre
|
||||
}
|
||||
|
||||
|
||||
/** What the header says about a preview: parts (a multi-body part's bodies are scene nodes `<part node>/body:<id>`) and bodies. */
|
||||
/** The node id of a surface value of the notebook (a face or shell that is not part of the product): `node/surface/<name>`
|
||||
* (simplecadapi/scene/preview.py: drawn from both sides, picked whole with the sketches and curves). */
|
||||
export const SURFACE_NODE_PREFIX = "node/surface/";
|
||||
export const isSurfaceNode = (nodeId: string): boolean => nodeId.startsWith(SURFACE_NODE_PREFIX);
|
||||
|
||||
/** What the header says about a preview: its parts, and the open solids of the notebook drawn beside them (scene nodes
|
||||
* `node/<notebook id>/body:<name>`: a Part holds one solid, so these are loose values, not parts). */
|
||||
export function previewSummary(all: readonly { nodeId: string }[]): string {
|
||||
const nodes = all.filter((node) => !isSurfaceNode(node.nodeId));
|
||||
const parts = new Set(nodes.map((node) => node.nodeId.replace(/\/body:[^/]+$/, "")));
|
||||
const partCount = parts.size === 1 ? t("1 part") : t("{{count}} parts", { count: parts.size });
|
||||
const bodyCount = nodes.length === 1 ? t("1 body") : t("{{count}} bodies", { count: nodes.length });
|
||||
return nodes.length > parts.size ? `${partCount} · ${bodyCount}` : partCount;
|
||||
const open = nodes.filter((node) => /\/body:[^/]+$/.test(node.nodeId)).length;
|
||||
const placed = nodes.length - open;
|
||||
const partCount = placed === 1 ? t("1 part") : t("{{count}} parts", { count: placed });
|
||||
if (open === 0) return partCount;
|
||||
const openCount = open === 1 ? t("1 open solid") : t("{{count}} open solids", { count: open });
|
||||
return placed > 0 ? `${partCount} · ${openCount}` : openCount;
|
||||
}
|
||||
|
||||
@@ -167,9 +167,10 @@ class FeatureService:
|
||||
"normal_vec": sketch_doc.plane_normal(plane),
|
||||
}
|
||||
)
|
||||
if product is None and open_bodies and self._implicit_part():
|
||||
# no cell builds the Part: the runtime makes it from the open bodies (several are the bodies of one Part)
|
||||
product = {"cell": None, "body": open_bodies[-1], "bodies": list(open_bodies), "implicit": True}
|
||||
if product is None and len(open_bodies) == 1 and self._implicit_part():
|
||||
# no cell builds the Part: the runtime makes it from the one open body. Several open solids have no product
|
||||
# yet (a Part holds exactly one solid): they are shown side by side and the author picks (use_as_product).
|
||||
product = {"cell": None, "body": open_bodies[0], "implicit": True}
|
||||
return {
|
||||
"features": features,
|
||||
"bodies": [{"name": name, "produces": bodies[name]} for name in order],
|
||||
@@ -370,6 +371,12 @@ class FeatureService:
|
||||
name = str(request.get("body", ""))
|
||||
if name not in {b["name"] for b in snap["bodies"]}:
|
||||
raise GuiError(f"{name!r} is not a body in this notebook")
|
||||
if not snap["product"] and self._implicit_part() and name in snap["open"]:
|
||||
# several solids are open and no cell makes the Part: the author's choice is the Part (a Part holds one solid)
|
||||
made = self._product_cell(snap, name)
|
||||
steps = [self._create(made["after"], f"{made['variable']} = scad.make_part_rpart(part_id=scad.notebook_id(), body={name})", run=True)]
|
||||
self._record(steps)
|
||||
return self._result(steps[0]["id"], steps, name)
|
||||
if not snap["product"]:
|
||||
raise GuiError("this notebook has no product cell that builds a Part from a body")
|
||||
if not snap["product"]["cell"]:
|
||||
|
||||
+1
-1
@@ -866,7 +866,7 @@ class ApiIndexTest(unittest.TestCase):
|
||||
self.assertEqual(part["k"], "c")
|
||||
names = [p["n"] for p in part["p"]]
|
||||
# a Part takes one ``body`` or several ``bodies`` (multi-body parts), so only part_id is required
|
||||
self.assertEqual([p["n"] for p in part["p"] if p["r"]], ["part_id"])
|
||||
self.assertEqual([p["n"] for p in part["p"] if p["r"]], ["part_id", "body"])
|
||||
self.assertIn("body", names)
|
||||
self.assertIn("bodies", names)
|
||||
self.assertFalse([n for n in names if n.startswith("_")])
|
||||
|
||||
@@ -315,7 +315,7 @@ def test_a_blank_notebook_gets_its_product_with_the_first_feature(tmp_path):
|
||||
snap = service.snapshot()
|
||||
assert [f["slug"] for f in snap["features"]] == ["base"]
|
||||
# the header says kind = "part": the runtime makes the Part from the open body, no product cell is written
|
||||
assert snap["product"] == {"cell": None, "body": "base", "bodies": ["base"], "implicit": True}
|
||||
assert snap["product"] == {"cell": None, "body": "base", "implicit": True}
|
||||
assert "make_part_rpart" not in path.read_text()
|
||||
# a part holds one solid: the new cylinder says how it meets the body, so no second body is left behind
|
||||
assert service.snapshot()["defaults"]["cylinder"]["operation"] == "join"
|
||||
@@ -538,7 +538,7 @@ def test_a_cell_written_as_code_makes_what_the_kernel_says_it_made():
|
||||
service._implicit_part = lambda: True # type: ignore[method-assign]
|
||||
snap = service.snapshot()
|
||||
assert snap["bodies"] == [{"name": "path", "produces": "wire"}, {"name": "base", "produces": "solid"}]
|
||||
assert snap["open"] == ["base"] and snap["product"]["bodies"] == ["base"]
|
||||
assert snap["open"] == ["base"] and snap["product"]["body"] == "base"
|
||||
assert snap["defaults"]["op.sweep_rsolid"]["path"] == "path"
|
||||
|
||||
|
||||
@@ -562,3 +562,49 @@ def test_curves_to_a_flat_face_a_sewn_shell_and_a_solid_run():
|
||||
exec("\n".join(rendered.params + [rendered.feature]), scope)
|
||||
bodies[slug] = made
|
||||
assert scope["tray"].get_volume() == pytest.approx(40 * 30 * 20, rel=1e-3)
|
||||
|
||||
|
||||
def test_several_open_solids_have_no_product_until_the_author_picks_one(tmp_path):
|
||||
"""A Part holds exactly one solid: with a tool left next to its body there is no implicit product, and the editor's
|
||||
`use_as_product` makes the Part of the solid the author chooses (a make_part_rpart cell)."""
|
||||
import threading
|
||||
|
||||
import uvicorn
|
||||
|
||||
from simplecadapi.editor.server import WorkspaceState, create_app
|
||||
from simplecadapi.editor.templates import create_notebook
|
||||
from simplecadapi.runtime import run_notebook
|
||||
from simplecadapi.runtime.projection import SeveralOpenBodiesError
|
||||
|
||||
path = create_notebook(tmp_path, "plate", "blank")
|
||||
state = WorkspaceState(tmp_path)
|
||||
state.port = 17734
|
||||
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
|
||||
service.add({"spec": "box", "name": "base", "values": {}})
|
||||
_wait_idle(state)
|
||||
service.add({"spec": "cylinder", "name": "tool", "values": {"radius": 3.0, "height": 30.0, "operation": "new"}}) # stays beside the body
|
||||
_wait_idle(state)
|
||||
snap = service.snapshot()
|
||||
assert snap["open"] == ["base", "tool"], snap
|
||||
assert snap["product"] is None # no guess: the author says which solid is the part
|
||||
assert "make_part_rpart" not in path.read_text()
|
||||
try:
|
||||
run_notebook(path, cache=False)
|
||||
except SeveralOpenBodiesError as error:
|
||||
assert error.names == ("base", "tool") and "exactly one solid" in str(error)
|
||||
else:
|
||||
raise AssertionError("a headless run must not pick a solid for the author")
|
||||
service.use_as_product({"body": "base"})
|
||||
_wait_idle(state)
|
||||
snap = service.snapshot()
|
||||
assert snap["product"] is not None and snap["product"]["body"] == "base" and snap["product"]["cell"], snap
|
||||
assert "make_part_rpart(part_id=scad.notebook_id(), body=base)" in path.read_text()
|
||||
assert run_notebook(path, cache=False).product.part_id == "plate"
|
||||
finally:
|
||||
if state.kernel is not None:
|
||||
state.kernel.stop()
|
||||
|
||||
Reference in New Issue
Block a user