editor: shell as an operation in progress: picked faces, Shell, and the cup is there at once with a 1 mm wall; an arrow on the opened face drags the thickness into the body (at least 0.1 mm), the panel lists the openings and takes one out, a click on a face of the model (the shelled body itself) opens it too; Esc undoes the feature with every opening added or taken out meanwhile. Fillet and chamfer take more edges the same way (any operation whose one selection takes several picks)

Server: the feature list carries what each selection slot holds as references (gui.refs), an edit keeps the references it is given for items with no entity on screen (a face a shell opened is not drawn), and a reference given twice is selected once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NiJingzhe
2026-11-06 04:47:31 +08:00
parent 5c2acac1d6
commit 1505ff1f42
11 changed files with 276 additions and 25 deletions
@@ -108,6 +108,7 @@ sca feature ls # features, bodies, tip, product, defaults
sca feature add box --name base --values '{"width": 40, "height": 30, "depth": 20}'
sca feature add fillet --values '{"radius": 2}' --selections '{"edges": [{"kind": "edge", "entity_id": "entity/..."}]}' # named by the kernel; geometry-only items keep the older recipe
sca feature edit base --values '{"width": 50}' # a GUI feature; a code feature is refused
sca feature edit cup --selections '{"faces": [{"kind": "face", "ref": {...}}, {"kind": "face", "entity_id": "entity/..."}]}' # keep a held reference (`sca feature ls`: gui.refs), add a pick
sca feature rm base | sca feature undo | sca feature redo
sca sketch ls | get CELL | put CELL -f doc.json | solve CELL
sca sketch op CELL trim --args '{"entity": "h", "at": [8, 0]}' [--dry-run]
+78 -11
View File
@@ -21,7 +21,7 @@ import { NewNotebookPrompt } from "@/components/NewNotebookPrompt";
import { FloatingPanels } from "@/components/FloatingPanels";
import { OperationPanel } from "@/components/OperationPanel";
import { PressPullHandle } from "@/components/PressPullHandle";
import { featureParams, quickStart } from "@/lib/operation-session";
import { addPick, featureParams, pickSlot, quickStart, refLabel, removePick } from "@/lib/operation-session";
import { createSettler, SETTLE_MS } from "@/lib/settle";
import { PartialNotice } from "@/components/PartialModel";
import { describePartial, parsePartial, samePartial, type PartialModel } from "@/lib/partial";
@@ -54,7 +54,7 @@ import { describeSketch, nextSketchSelection, readHidden, sketchCentre, sketchIn
import { useSketchShapes } from "@/lib/useSketchShapes";
import type { Vec3 } from "@/lib/sketch-plane";
import { PALETTES } from "@/scene/theme";
import { assertCellRan, cellFailure, isCellCommand, pickedPayload, type FeatureCommand, type FeatureRow, type Spec } from "@/lib/features";
import { assertCellRan, cellFailure, isCellCommand, pickedPayload, type FeatureCommand, type FeatureRow, type SelectionPayload, type Spec } from "@/lib/features";
import { useRunLog } from "@/lib/runlog";
import { useTheme } from "@/lib/theme";
import { selectionPayload, variableNames, type SelectionItem } from "@/lib/selection";
@@ -545,6 +545,8 @@ export function App() {
const leftTabRef = useRef(leftTab);
leftTabRef.current = leftTab;
const selectComponent = asm.setSelected;
/** The session's pick editor (declared with the session below): a click during an operation goes to it. */
const editSessionPicksRef = useRef<(items: SelectionPayload[]) => void>(() => {});
const handlePick = useCallback((result: PickResult) => {
if (placingRef.current || drawingRef.current) return; // a click on the handles, or a curve's point, is not a pick
if (dialogRef.current?.spec.id === "hole") return; // a click places the hole (HolePlacer), it picks nothing
@@ -570,6 +572,12 @@ export function App() {
geometry: entity?.geometry ?? null,
tags: entity?.tags ?? null,
};
// An operation in progress that takes several picks: a click on the model adds what it hits (the server names it)
const current = sessionRef.current;
if (current) {
if (current.pick && item.kind === current.pick.entity && item.entityId) editSessionPicksRef.current(addPick(sessionHeldRef.current, { ...item, variable: "" }));
return;
}
// A preview carries no entity details: ask the kernel for them.
const needsDetails = Boolean(view?.isPreview) && Boolean(item.entityId) && Object.keys(item.properties ?? {}).length === 0;
if (needsDetails && item.entityId) {
@@ -640,8 +648,16 @@ export function App() {
// -- an operation in progress (lib/operation-session.ts): added at once, its numbers tuned live by the selection ----------
/** `handle`: a press / pull's arrow, on the picked face (mm, world) along its outward normal. */
type OpSession = { slug: string; cell: string | null; title: string; specId: string; anchorMm: Vec3 | null; editing: boolean; busy: boolean; error: string | null; handle: { origin: Vec3; normal: Vec3 } | null };
/** `handle`: an arrow on the picked face (mm, world) that drags the number whose name ends in `param`: a press / pull's
* distance along the face's outward normal, a shell's wall thickness into the body.
* `pick`: the selection a click on the model adds to (the faces a shell opens, the edges a fillet rounds), see
* lib/operation-session.ts; `edits`: the feature edits those clicks made (Esc undoes them with the rest). */
type OpSession = {
slug: string; cell: string | null; title: string; specId: string; anchorMm: Vec3 | null; editing: boolean; busy: boolean; error: string | null;
handle: { origin: Vec3; normal: Vec3; param: string; min?: number } | null;
pick: ReturnType<typeof pickSlot>;
edits: number;
};
const [session, setSession] = useState<OpSession | null>(null);
const sessionRef = useRef(session);
sessionRef.current = session;
@@ -649,8 +665,13 @@ export function App() {
const paramsRef = useRef<ParamMeta[]>([]);
const sessionSettler = useRef(createSettler<ParamValue>(SETTLE_MS, (values) => socketRef.current?.send({ type: "param.set", values })));
const sessionParams = useMemo(() => (session ? featureParams(params, session.slug) : []), [params, session]);
/** The distance a press / pull's arrow drags. */
const sessionDistance = sessionParams.find((param) => param.id.endsWith("_DISTANCE"));
/** The number the session's arrow drags. */
const sessionDistance = session?.handle ? sessionParams.find((param) => param.id.endsWith(session.handle!.param)) : undefined;
/** What the session's pick slot holds, as references (in the feature's cell). */
const sessionHeld = useMemo(() => {
if (!session?.pick || !session.cell) return [];
return gui.state.features.find((feature) => feature.cell === session.cell)?.gui?.refs?.[session.pick.slot] ?? [];
}, [session, gui.state.features]);
/** The numbers changed in the session (the server's `modified` may not have come back yet when Enter is pressed). */
const sessionTouched = useRef(new Set<string>());
/** The numbers of the session the notebook source does not have yet. */
@@ -681,7 +702,13 @@ export function App() {
if (names.length) socketRef.current?.send({ type: "param.revert", names });
sessionTouched.current.clear();
setSession(null);
if (!current.editing) void gui.run({ op: "undo" }).then(() => log.push("info", t("took back {{name}}", { name: current.slug }))).catch(() => undefined);
// the picks added while tuning are edits of their own: they go back first, then the feature itself when it is new
const steps = current.edits + (current.editing ? 0 : 1);
void (async () => {
for (let step = 0; step < steps; step += 1) await gui.run({ op: "undo" });
})()
.then(() => steps && log.push("info", t("took back {{name}}", { name: current.slug })))
.catch(() => undefined);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [gui.run, log.push]);
/** Start `spec` on the selection with its defaults when that is all it needs (else false: the dialog opens). */
@@ -691,10 +718,18 @@ export function App() {
const start = quickStart(request.spec, gui.state, selectionRef.current, request.prefill);
if (!start) return false;
const title = t(plainLabel(request.spec.id, request.spec.label));
const picked = request.spec.id === "press_pull" ? selectionRef.current.find((item) => item.kind === "face") : undefined;
// a press / pull drags its distance out of the face, a shell its wall thickness into the body
const arrow = ({ press_pull: { param: "_DISTANCE", into: false }, shell: { param: "_THICKNESS", into: true } } as const)[request.spec.id as "press_pull" | "shell"];
const picked = arrow ? selectionRef.current.find((item) => item.kind === "face") : undefined;
const frame = picked?.entityId ? (viewRef.current?.faceFrameMm(picked.nodeId, picked.entityId) ?? null) : null;
const handle = frame ? { origin: frame.centroid, normal: frame.normal } : null;
setSession({ slug: start.name, cell: null, title, specId: request.spec.id, anchorMm: frame?.centroid ?? anchorRef.current, editing: false, busy: true, error: null, handle });
const handle =
frame && arrow
? { origin: frame.centroid, normal: (arrow.into ? frame.normal.map((v) => -v) : frame.normal) as Vec3, param: arrow.param, ...(arrow.into ? { min: 0.1 } : {}) }
: null;
setSession({
slug: start.name, cell: null, title, specId: request.spec.id, anchorMm: frame?.centroid ?? anchorRef.current, editing: false, busy: true, error: null,
handle, pick: pickSlot(request.spec), edits: 0,
});
setDialog(null);
gui
.run(start.command)
@@ -712,10 +747,31 @@ export function App() {
},
[gui.state, gui.run, log.push],
);
/** Write a new list into the session's pick slot (a click added to it, the panel took one out): an edit of the feature. */
const editSessionPicks = useCallback(
(items: SelectionPayload[]) => {
const current = sessionRef.current;
if (!current?.pick || !current.cell || current.busy) return;
const { cell, pick } = current;
setSession({ ...current, busy: true });
gui
.run({ op: "edit", cell, values: {}, selections: { [pick.slot]: items } })
.then((result) => setSession((now) => (now && now.cell === cell ? { ...now, busy: false, edits: now.edits + 1, error: cellFailure(result) } : now)))
.catch((error) => setSession((now) => (now && now.cell === cell ? { ...now, busy: false, error: error instanceof Error ? error.message : String(error) } : now)));
},
[gui.run],
);
const sessionHeldRef = useRef(sessionHeld);
sessionHeldRef.current = sessionHeld;
editSessionPicksRef.current = editSessionPicks;
/** Tune the numbers of a feature of the tree in place (Esc gives them back). */
const editInPlace = useCallback((feature: FeatureRow, spec: Spec): boolean => {
if (!featureParams(paramsRef.current, feature.slug).length) return false;
setSession({ slug: feature.slug, cell: feature.cell, title: t(plainLabel(spec.id, spec.label)), specId: spec.id, anchorMm: anchorRef.current, editing: true, busy: false, error: null, handle: null });
setSession({
slug: feature.slug, cell: feature.cell, title: t(plainLabel(spec.id, spec.label)), specId: spec.id, anchorMm: anchorRef.current, editing: true, busy: false, error: null,
handle: null, pick: feature.gui?.refs?.[pickSlot(spec)?.slot ?? ""] ? pickSlot(spec) : null, edits: 0,
});
return true;
}, []);
@@ -1623,6 +1679,7 @@ export function App() {
origin={session.handle.origin}
normal={session.handle.normal}
distance={Number(sessionDistance.value)}
min={session.handle.min}
onChange={(distance, done) => {
sessionTouched.current.add(sessionDistance.id);
sessionSettler.current.push(sessionDistance.id, distance);
@@ -1639,6 +1696,16 @@ export function App() {
error={session.error ?? (session.cell ? (partial?.failed.find((cell) => cell.cell === session.cell)?.error ?? null) : null)}
busy={session.busy}
editing={session.editing}
picks={
session.pick && session.cell
? {
label: t(session.pick.label),
hint: session.pick.entity === "edge" ? t("Click edges on the model to add them") : t("Click faces on the model to add them"),
items: sessionHeld.map(refLabel),
onRemove: (index) => editSessionPicks(removePick(sessionHeld, index)),
}
: undefined
}
onParam={(id, value, now) => {
sessionTouched.current.add(id);
sessionSettler.current.push(id, value);
+25 -1
View File
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from "react";
import { Check, ChevronsDownUp, ChevronsUpDown, SlidersHorizontal, X } from "lucide-react";
import { Check, ChevronsDownUp, ChevronsUpDown, MousePointerClick, SlidersHorizontal, X } from "lucide-react";
import { ParamControl, type ParamMeta, type ParamValue } from "@/components/ParamControl";
import { useViewer } from "@/components/sketch/SketchOverlay";
@@ -19,6 +19,7 @@ export function OperationPanel({
error,
busy,
editing,
picks,
onParam,
onConfirm,
onCancel,
@@ -34,6 +35,9 @@ export function OperationPanel({
busy: boolean;
/** The feature existed before (Esc reverts its numbers instead of removing it). */
editing: boolean;
/** What the operation works on, when a click on the model adds to it (the faces a shell opens): each can be taken out
* while more than one is left. */
picks?: { label: string; hint: string; items: readonly string[]; onRemove: (index: number) => void };
onParam: (id: string, value: ParamValue, now?: boolean) => void;
onConfirm: () => void;
onCancel: () => void;
@@ -98,6 +102,26 @@ export function OperationPanel({
<ChevronsDownUp className="size-3.5" />
</button>
</div>
{picks && (
<div className="flex flex-col gap-1" data-testid="session-picks">
<span className="text-muted-foreground">{picks.label}</span>
<div className="flex flex-wrap gap-1">
{picks.items.map((item, index) => (
<span key={`${item}-${index}`} className="flex items-center gap-1 border border-border px-1.5 py-0.5 font-mono text-[10px]">
{item}
{picks.items.length > 1 && (
<button type="button" disabled={busy} className="text-muted-foreground hover:text-fail disabled:opacity-40" aria-label={t("Take {{item}} out", { item })} title={t("Take {{item}} out", { item })} onClick={() => picks.onRemove(index)}>
<X className="size-3" />
</button>
)}
</span>
))}
</div>
<span className="flex items-center gap-1 text-[10px] text-muted-foreground">
<MousePointerClick className="size-3" /> {picks.hint}
</span>
</div>
)}
{params.length ? (
params.map((param) => <ParamControl key={param.id} param={param} forwardParam={onParam} editable />)
) : (
@@ -9,14 +9,15 @@ import type { SceneView } from "@/scene/scene-view";
/** Snap of a drag, mm (Shift drags freely). */
const SNAP_MM = 0.5;
/** The arrow of a press / pull: it stands on the picked face, along its outward normal, at `distance` (mm) from it.
* Dragging it out pulls the face, dragging it in presses it (the distance goes negative); typing the distance moves it.
/** An arrow on a picked face that drags a distance (mm) along `normal`: a press / pull's (along the outward normal; dragged
* in, the distance goes negative), a shell's wall thickness (into the body, at least `min`). Typing the number moves it.
* The scene is the CAD frame in metres. */
export function PressPullHandle({
view,
origin,
normal,
distance,
min,
onChange,
}: {
view: SceneView;
@@ -25,12 +26,14 @@ export function PressPullHandle({
/** The face's outward unit normal. */
normal: Vec3;
distance: number;
/** The smallest distance the drag gives (none: any, negative included). */
min?: number;
onChange: (distance: number, done: boolean) => void;
}) {
const targetRef = useRef<THREE.Group | null>(null);
const dragging = useRef(false);
const changeRef = useRef(onChange);
changeRef.current = onChange;
const changeRef = useRef((value: number, done: boolean) => onChange(min === undefined ? value : Math.max(min, value), done));
changeRef.current = (value: number, done: boolean) => onChange(min === undefined ? value : Math.max(min, value), done);
const at = useRef({ origin, normal });
at.current = { origin, normal };
+3
View File
@@ -121,6 +121,8 @@
"Click again to delete": "再点一次删除",
"Click again to delete this cell": "再点一次删除此单元",
"Click an item to delete it.": "点击要删除的对象。",
"Click edges on the model to add them": "在模型上点击边即可加入",
"Click faces on the model to add them": "在模型上点击面即可加入",
"Click or shift-click to select; drag a point or a line to move it; click inside a loop for the profile, shift-click for a hole. Click a spline to show its handles.": "点击或 Shift+点击选择;拖动点或线来移动;点击环内部设为轮廓,Shift+点击设为孔。点击样条显示它的控制柄。",
"Click the centre.": "点击圆心。",
"Click the end (counter-clockwise from start).": "点击终点(从起点逆时针)。",
@@ -699,6 +701,7 @@
"Tab: next field · Enter: place · Esc: close": "Tab:下一个输入框 · Enter:放置 · Esc:关闭",
"Tag": "标签",
"Take one or more bodies out of another.": "从一个实体中去除一个或多个实体。",
"Take {{item}} out": "移除 {{item}}",
"Tangent": "相切",
"Taper": "拔模角",
"Target": "目标",
+11 -3
View File
@@ -54,7 +54,8 @@ export type FeatureRow = {
index: number;
slug: string;
role: string;
gui: { spec: string; values: Record<string, unknown>; picked: Record<string, unknown> } | null;
/** `refs`: what each selection slot holds, as references (a slot written as an older recipe is absent). */
gui: { spec: string; values: Record<string, unknown>; picked: Record<string, unknown>; refs?: Record<string, RefRecord[]> } | null;
makes: string[];
reads: string[];
status: string | null;
@@ -81,6 +82,13 @@ export type FeatureState = {
redo: number;
};
/** A stable reference as the server writes it (`scad.ref.face(feature, op, role=...)`; see simplecadapi/ref.py). */
export type RefRecord = { kind: string; feature?: string; op?: string; role?: string | null; ordinal?: number; piece?: number | null; [key: string]: unknown };
/** What a selection slot is given: an entity picked in the viewport (named by the server), or a reference the feature
* already holds (kept by an edit: a face a shell opened is not drawn any more, so it cannot be picked again). */
export type SelectionPayload = PickedItem | { kind: string; ref: RefRecord };
export type PickedItem = {
kind: string;
entity_id: string | null;
@@ -92,8 +100,8 @@ export type PickedItem = {
};
export type FeatureCommand =
| { op: "add"; spec: string; name?: string; values: Record<string, unknown>; selections?: Record<string, PickedItem[]>; after?: string }
| { op: "edit"; cell: string; values: Record<string, unknown>; selections?: Record<string, PickedItem[]> }
| { op: "add"; spec: string; name?: string; values: Record<string, unknown>; selections?: Record<string, SelectionPayload[]>; after?: string }
| { op: "edit"; cell: string; values: Record<string, unknown>; selections?: Record<string, SelectionPayload[]> }
| { op: "delete"; cell: string }
| { op: "use_as_product"; body: string }
| { op: "set_connectors"; connectors: { id: string; origin: number[]; x_axis: number[]; y_axis: number[] }[] }
+24 -1
View File
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import type { Spec } from "@/lib/features";
import type { SelectionItem } from "@/lib/selection";
import { featureParams, quickStart } from "@/lib/operation-session";
import { addPick, featureParams, pickSlot, quickStart, refLabel, removePick } from "@/lib/operation-session";
const FILLET: Spec = {
id: "fillet",
@@ -60,3 +60,26 @@ describe("an operation started on the selection", () => {
expect(featureParams(params, "fillet").map((p) => p.id)).toEqual(["FILLET_RADIUS"]);
});
});
describe("picks added and taken out while tuning", () => {
const top = { kind: "face", feature: "base", op: "make_box_rsolid", role: "box.top", ordinal: 0 };
const side = { kind: "face", feature: "base", op: "make_box_rsolid", role: "box.front", ordinal: 0 };
it("adds to the one slot that takes several picks", () => {
expect(pickSlot(FILLET)).toEqual({ slot: "edges", entity: "edge", label: "Edges" });
const single: Spec = { ...FILLET, slots: [{ name: "face", label: "Face", kind: "select", entity: "face", single: true }] };
expect(pickSlot(single)).toBeNull();
});
it("sends back what the feature holds as references, then the new pick", () => {
const added = addPick([top], edge("e1"));
expect(added[0]).toEqual({ kind: "face", ref: top });
expect(added[1]).toMatchObject({ kind: "edge", entity_id: "entity/demo/edge/e1" });
expect(removePick([top, side], 0)).toEqual([{ kind: "face", ref: side }]);
});
it("names a reference by its feature and role", () => {
expect(refLabel(top)).toBe("base · box.top");
expect(refLabel({ kind: "edge", op: "make_fillet_rsolid", ordinal: 2, piece: 1 })).toBe("fillet · #3 (2)");
});
});
+31 -1
View File
@@ -6,11 +6,15 @@
* \--Esc--> idle (undone, or reverted when editing)
* idle --edit a feature of the tree--> tuning (its own numbers)
*
* While tuning an operation that takes a list of picks (the edges of a fillet, the faces a shell opens), a click on the
* model adds what it hits to the list and the panel takes one out: each is an edit of the feature (the ones it holds go
* back as their references), and Esc undoes them with the rest.
*
* An operation that needs more than the selection and defaults (a sketch profile, a hole's position, a list of points)
* opens its dialog instead. */
import { formDefaults } from "@/lib/combine";
import { filterSelection, formToValues, initialForm, pickedPayload, suggestName, type FeatureCommand, type FeatureState, type Spec } from "@/lib/features";
import { filterSelection, formToValues, initialForm, pickedPayload, suggestName, type FeatureCommand, type FeatureState, type RefRecord, type SelectionPayload, type Spec } from "@/lib/features";
import type { SelectionItem } from "@/lib/selection";
/** Slot kinds that need nothing but their default (numbers become the feature's parameters, tuned in the panel). */
@@ -50,3 +54,29 @@ export function quickStart(
export function featureParams<P extends { group: string }>(params: readonly P[], slug: string): P[] {
return params.filter((param) => param.group === slug);
}
/** The selection a session adds to with clicks: the operation's one slot that takes several picks (the faces a shell
* opens, the edges a fillet rounds); null for one that takes a single pick or none. */
export function pickSlot(spec: Spec): { slot: string; entity: "face" | "edge"; label: string } | null {
const slots = spec.slots.filter((slot) => slot.kind === "select" && !slot.single);
return slots.length === 1 ? { slot: slots[0].name, entity: slots[0].entity ?? "face", label: slots[0].label } : null;
}
/** The slot's new list after a click: what it holds (as references), then the picked item. */
export function addPick(held: readonly RefRecord[], item: SelectionItem): SelectionPayload[] {
return [...held.map((ref) => ({ kind: ref.kind, ref })), pickedPayload(item)];
}
/** The slot's new list without the `index`-th reference it holds. */
export function removePick(held: readonly RefRecord[], index: number): SelectionPayload[] {
return held.filter((_, at) => at !== index).map((ref) => ({ kind: ref.kind, ref }));
}
/** A reference in a word or two: its role on the feature that made it (`base · box.top`), else the operation and its
* ordinal. */
export function refLabel(ref: RefRecord): string {
const where = ref.feature || (ref.op ?? "").replace(/^make_|_r\w+$/g, "");
const what = ref.role ? String(ref.role) : `#${(ref.ordinal ?? 0) + 1}`;
const piece = typeof ref.piece === "number" ? ` (${ref.piece + 1})` : "";
return where ? `${where} · ${what}${piece}` : `${what}${piece}`;
}
+12 -2
View File
@@ -700,7 +700,7 @@ SPECS: tuple[Spec, ...] = (
Spec("chamfer", "Chamfer", "Features", "modifier", "solid", "Bevel the picked edges.",
(_BODY(), Slot("edges", "Edges", "select", entity="edge"), _length("distance", "Distance", 0.5)), _chamfer),
Spec("shell", "Shell", "Features", "modifier", "solid", "Hollow the body, opening the picked faces.",
(_BODY(), Slot("faces", "Faces to open", "select", entity="face"), _length("thickness", "Wall thickness", 2.0)), _shell),
(_BODY(), Slot("faces", "Faces to open", "select", entity="face"), _length("thickness", "Wall thickness", 1.0)), _shell),
Spec("linear_pattern", "Linear pattern", "Pattern", "build", "solids", "Copies of a body along a direction (the original is the first copy).",
(_body("shape", "Body to repeat"), _AXIS("direction", "Direction", "+x"), Slot("count", "Count", "count", default=3, min=2, max=500),
_length("spacing", "Spacing", 15.0)), _linear_pattern),
@@ -989,7 +989,9 @@ def selection_recipe(slot: Slot, items: Sequence[Mapping[str, Any]], known_slugs
raise FeatureError(f"{slot.label}: pick at least one {slot.entity} in the viewport")
refs = _picked_refs(slot, picked)
if refs is not None:
return f"_{slot.name} = {_ref.selection_code(slot.entity or 'face', refs)}".splitlines()
# one entity picked twice (picked again in the viewport while the feature already holds it) is selected once
unique = list({json.dumps(r.to_dict(), sort_keys=True): r for r in refs}.values())
return f"_{slot.name} = {_ref.selection_code(slot.entity or 'face', unique)}".splitlines()
geometry: list[str] = []
tags: list[str] = []
all_tagged = True
@@ -1058,6 +1060,14 @@ def replace_refs(code: str, slot: str, refs: Sequence[_ref.ElementRef]) -> str:
return "\n".join(lines) + ("\n" if code.endswith("\n") else "")
def selection_refs(code: str, slot: str) -> list[dict[str, Any]] | None:
"""The references a selection slot of a feature cell holds (records, in order), or ``None`` when it is not written as
``scad.ref`` references (an older recipe, a cell written as code): what a form shows of what is picked, and what an
edit sends back for the ones it keeps."""
found = _ref_statement(code, slot)
return [reference.to_dict() for reference in found[3]] if found is not None else None
def extract_recipe(code: str, slot: str) -> list[str] | None:
"""The recipe lines of a selection slot in an existing feature cell, so an edit can keep what was picked."""
found = _ref_statement(code, slot)
+19 -2
View File
@@ -124,7 +124,19 @@ class FeatureService:
"index": index + 1,
"slug": head.slug,
"role": head.role,
"gui": {"spec": gui["spec"], "values": gui.get("values", {}), "picked": gui.get("picked", {})} if gui else None,
"gui": {
"spec": gui["spec"],
"values": gui.get("values", {}),
"picked": gui.get("picked", {}),
# what each selection holds, as references (absent for a slot written as an older recipe)
"refs": {
slot.name: refs
for slot in F.BY_ID[gui["spec"]].slots
if slot.kind == "select" and (refs := F.selection_refs(code, slot.name)) is not None
},
}
if gui
else None,
"makes": made,
"part_of": part_of,
"reads": sorted(loaded & (set(bodies) | {w["name"] for w in workplanes}) - set(made)),
@@ -459,7 +471,9 @@ class FeatureService:
def _name_picks(self, picked: dict[str, list]) -> dict[str, list]:
"""Each picked entity with its stable reference (``ref``: a record), named in the kernel from the value it
was drawn from. An entity the kernel cannot name keeps no ``ref`` (its slot falls back to the older recipe)."""
was drawn from. An item that comes with its ``ref`` and no entity on screen (one an edit keeps of what the feature
holds: a face it opened is no longer drawn) keeps it; an entity the kernel cannot name keeps no ``ref`` (its slot
falls back to the older recipe)."""
ids = [str(item.get("entity_id")) for items in picked.values() for item in items if isinstance(item, Mapping) and item.get("entity_id")]
kernel = getattr(self.state, "kernel", None)
named: dict[str, Any] = {}
@@ -473,6 +487,9 @@ class FeatureService:
for slot, items in picked.items():
rows = []
for item in items:
if isinstance(item, Mapping) and not item.get("entity_id") and isinstance(item.get("ref"), Mapping):
rows.append(dict(item))
continue
row = {k: v for k, v in dict(item).items() if k != "ref"} if isinstance(item, Mapping) else item
record = named.get(str(row.get("entity_id"))) if isinstance(row, dict) else None
if record:
+65
View File
@@ -149,3 +149,68 @@ def test_the_server_names_picks_shows_a_split_and_writes_the_chosen_piece(tmp_pa
if state.kernel is not None:
state.kernel.stop()
server.should_exit = True
def test_an_edit_keeps_the_references_it_is_given_and_adds_what_is_picked_on_the_result(tmp_path):
"""The shell session: faces picked on the shelled body are named on the body before it and join the openings; the
ones the feature holds come back as references (a face it opened is not drawn any more), so one can be taken out."""
import threading
import uvicorn
from simplecadapi.editor.server import WorkspaceState, create_app
from simplecadapi.editor.templates import create_notebook
path = create_notebook(tmp_path, "cup", "blank")
state = WorkspaceState(tmp_path)
state.port = 17742
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())
def pick(axis: int, at: float) -> str:
found = state.kernel.execute(
"from simplecadapi.runtime import live as _live\n"
"_s = _live._live_scene()\n"
"for _k, _solid in _s.solids.items():\n"
" for _f in _solid._iter_faces():\n"
f" if abs(_f.get_center().{'xyz'[axis]} - {at}) < 1e-6:\n"
" print('SCA-PICK', f'entity/{_s.definitions[_k]}/face/{_f.topo_id}')\n"
)
(entity_id,) = [line.split(" ", 1)[1] for line in found["log"].splitlines() if line.startswith("SCA-PICK ")]
return entity_id
def cup() -> dict:
return next(f for f in state.features.snapshot()["features"] if f["slug"] == "cup")
try:
state.start_kernel(path)
service = state.features
service.add({"spec": "box", "name": "base", "values": {"width": 40.0, "height": 30.0, "depth": 20.0}})
_wait_idle(state)
service.add({"spec": "shell", "name": "cup", "values": {"body": "base"}, "selections": {"faces": [{"kind": "face", "entity_id": pick(2, 20.0)}]}})
_wait_idle(state)
(top,) = cup()["gui"]["refs"]["faces"]
assert top["role"] == "box.top" and not cup()["errors"]
assert cup()["gui"]["values"]["thickness"] == 1.0 # a thin wall to start from
# a side picked on the cup itself joins the openings; picking it again changes nothing
side = pick(0, 20.0)
kept = {"kind": "face", "ref": top}
service.edit({"cell": cup()["cell"], "selections": {"faces": [kept, {"kind": "face", "entity_id": side}]}})
_wait_idle(state)
refs = cup()["gui"]["refs"]["faces"]
assert [r["role"] for r in refs] == ["box.top", "box.front"] and not cup()["errors"], (refs, cup()["errors"])
again = [{"kind": "face", "ref": r} for r in refs] + [{"kind": "face", "ref": refs[1]}]
service.edit({"cell": cup()["cell"], "selections": {"faces": again}})
_wait_idle(state)
assert len(cup()["gui"]["refs"]["faces"]) == 2
# the top taken out again: only the side is open
service.edit({"cell": cup()["cell"], "selections": {"faces": [{"kind": "face", "ref": refs[1]}]}})
_wait_idle(state)
assert [r["role"] for r in cup()["gui"]["refs"]["faces"]] == ["box.front"] and not cup()["errors"]
finally:
if state.kernel is not None:
state.kernel.stop()
server.should_exit = True