From a24cfbb3d792eaa84df57a41d0960fbcaca8f24b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 22:02:40 +0000 Subject: [PATCH] =?UTF-8?q?[K4][6][8]=20Aktionen=20erzeugen=20Ops=20direkt?= =?UTF-8?q?=20statt=20Projekt=20=E2=86=92=20Projekt=20+=20diffToOps?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Store `applyChange(ops | (p) => ops, coalesceKey?)` geht ohne Differenz an den Kern; `setProject` erkennt `opsMutation`-Funktionen und nimmt deren Ops. - Umgestellt: Griffe (moveGripOf/moveElementByOf/moveEdgeOf, Decke/Dach/Treppe/Raum), Objekt-Info (updateWall/-Ceiling/-Opening/-Roof/-Stair/-Room/-Drawing2D, Farbe, Füllung, Vorder-/Hintergrund, Resize, Wand-/Deckendicke, Polylinien-Punkte), Auswahl verschieben/ kopieren/drehen (`transformOps`), Löschen der Auswahl (+ Schnittlinien, eine Gruppe), Ebenen/Sichtbarkeit/Kategorien, Text-Tippen, Panel-Zeichnungs-Eigenschaften und die Zeichenbefehle (Wand, Decke, Raum, Treppe, Öffnung, Dach, Stütze, Extrusion, alle 2D-Zeichenbefehle, move/copy/mirror/rotate/scale/array). Gruppen-Zuordnung beim Zeichnen in einer Gruppe über `activeGroupOps`. - Griff-Zug mit mitgeführten Ecken: je Mausschritt eine Gruppe mit Schlüssel → ein Undo-Schritt für den ganzen Zug; aufgeschobene Commits beim Loslassen als Gruppe. - Tests: Store-Zufallsfolgen (Leseansicht = Kern, Aktion = applyOps(vorher, ihre Ops), Undo bis Anfang/Redo bis Ende exakt), activeGroupOps = addNewElementsToActiveGroup; beim Umbau zusätzlich 2400 Zufallsschritte gegen die alte setProject-Fassung und 400 Transformationen gegen das alte commitTransform geprüft (gleiches Projekt bis auf erzeugte ids und fehlend/leere Listen). - Messung (vitest, 3000 Wände): Griff ziehen 3,3 → 0,2–0,3 ms/Schritt, Auswahl (300 Wände) verschieben 30 → 6–7 ms, Eigenschaft tippen 3 → 0,03 ms. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src/App.tsx | 81 ++-- src/commands/cmds/arc.ts | 19 +- src/commands/cmds/array.ts | 4 +- src/commands/cmds/bezier.ts | 11 +- src/commands/cmds/block.ts | 13 +- src/commands/cmds/ceiling.ts | 16 +- src/commands/cmds/circle.ts | 16 +- src/commands/cmds/column.ts | 13 +- src/commands/cmds/copy.ts | 6 +- src/commands/cmds/detailref.ts | 9 +- src/commands/cmds/dimension.ts | 17 +- src/commands/cmds/ellipse.ts | 17 +- src/commands/cmds/extrude.ts | 12 +- src/commands/cmds/kote.ts | 9 +- src/commands/cmds/leader.ts | 13 +- src/commands/cmds/line.ts | 8 +- src/commands/cmds/mirror.ts | 6 +- src/commands/cmds/move.ts | 6 +- src/commands/cmds/multiline.ts | 13 +- src/commands/cmds/offset.ts | 12 +- src/commands/cmds/opening.ts | 12 +- src/commands/cmds/pointmarker.ts | 9 +- src/commands/cmds/polygon.ts | 19 +- src/commands/cmds/polyline.ts | 17 +- src/commands/cmds/ray.ts | 9 +- src/commands/cmds/rect.ts | 35 +- src/commands/cmds/revcloud.ts | 15 +- src/commands/cmds/roof.ts | 12 +- src/commands/cmds/room.ts | 18 +- src/commands/cmds/rotate.ts | 9 +- src/commands/cmds/scale.ts | 6 +- src/commands/cmds/scalebar.ts | 9 +- src/commands/cmds/spline.ts | 13 +- src/commands/cmds/stair.ts | 12 +- src/commands/cmds/text.ts | 10 +- src/commands/cmds/textbox.ts | 9 +- src/commands/cmds/textpath.ts | 9 +- src/commands/cmds/wall.ts | 22 +- src/commands/cmds/wipeout.ts | 11 +- src/commands/cmds/xline.ts | 9 +- src/state/applyChange.perf.test.ts | 57 +++ src/state/applyChange.test.ts | 177 ++++++++ src/state/groupActions.test.ts | 29 ++ src/state/groupActions.ts | 54 +++ src/state/projectSlice.ts | 577 ++++++++++--------------- src/state/useGripEditing.ts | 27 +- src/state/useMouseSelectionHandlers.ts | 29 +- src/state/usePanelHostBase.ts | 127 +++--- src/tools/transform.ts | 108 +++-- 49 files changed, 1001 insertions(+), 750 deletions(-) create mode 100644 src/state/applyChange.perf.test.ts create mode 100644 src/state/applyChange.test.ts diff --git a/src/App.tsx b/src/App.tsx index 509d9717..64619482 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -156,7 +156,8 @@ import { useGripEditing } from "./state/useGripEditing"; import { usePanelHostBase } from "./state/usePanelHostBase"; import { useDockDragState } from "./state/useDockDragState"; import { useMouseSelectionHandlers } from "./state/useMouseSelectionHandlers"; -import { addNewElementsToActiveGroup, containingGroupId, EMPTY_MEMBERSHIP } from "./state/groupActions"; +import { activeGroupOps, addNewElementsToActiveGroup, containingGroupId, EMPTY_MEMBERSHIP } from "./state/groupActions"; +import { isOpsMutation, opsMutation, removeItems } from "./core"; import type { GroupMembership, MemberKind } from "./state/groupActions"; import { isLocked, setLockedForMembers } from "./state/objectLock"; import { useProjectFileActions } from "./state/useProjectFileActions"; @@ -352,6 +353,7 @@ export default function App() { // Endlosschleife). Actions leben ebenfalls im Zustand und sind referenzstabil. const project = useStore((s) => s.project); const setProject = useStore((s) => s.setProject); + const groupChanges = useStore((s) => s.groupChanges); const notify = useStore((s) => s.notify); const undo = useStore((s) => s.undo); const redo = useStore((s) => s.redo); @@ -937,10 +939,21 @@ export default function App() { // „wenn man etwas neu zeichnet ... zeichnet man in der Gruppe") — s. // state/groupActions.ts::addNewElementsToActiveGroup (Diff vor/nach // Commit über alle Elementarten, additiv zur eigentlichen Mutation). - commit: (mutate) => - cmdLatest.current.setProject((p) => - addNewElementsToActiveGroup(p, mutate(p), cmdLatest.current.groupPath), - ), + // [K4] S3: Befehle mit mitgeführten Ops (`opsMutation`) gehen ohne Projekt-Differenz an den + // Kern; die Gruppen-Zuordnung kommt dann als weitere Ops dazu (`activeGroupOps`). + commit: (mutate) => { + const groupPath = cmdLatest.current.groupPath; + if (isOpsMutation(mutate)) { + cmdLatest.current.setProject( + opsMutation((p) => { + const ops = mutate.toOps(p); + return [...ops, ...activeGroupOps(p, ops, groupPath)]; + }), + ); + } else { + cmdLatest.current.setProject((p) => addNewElementsToActiveGroup(p, mutate(p), groupPath)); + } + }, isFloor: () => cmdLatest.current.activeLevel.kind === "floor", // Frisch über `text`/`textbox` erzeugtes Element sofort inline editieren // (kein Lookup nötig — der Commit hat es bereits angehängt, s. engine.ts @@ -1223,6 +1236,21 @@ export default function App() { // Löscht die AKTUELLE Auswahl (alle Kanäle) — geteilte Logik zwischen dem // Entf-Tastatur-Handler und dem Menüpunkt „Bearbeiten > Löschen". const deleteSelection = () => { + // Ein Undo-Schritt für alles (Schnittlinien + Elemente), [K4] S3. + groupChanges(() => deleteSelectionChanges()); + setSelectedDrawingIds([]); + setSelectedWallIds([]); + setSelectedCeilingIds([]); + setSelectedOpeningIds([]); + setSelectedStairIds([]); + setSelectedRoomIds([]); + setSelectedExtrudedSolidIds([]); + setSelectedColumnIds([]); + setSelectedRoofIds([]); + setSelectedContextObjectIds([]); + setSelectedSectionLineIds([]); + }; + const deleteSelectionChanges = () => { // Schnittlinie(n): Entf löscht NUR ihre Linie (linePoints), die Ebene // bleibt — ADDITIV zu den übrigen Kanälen unten (nicht mehr exklusiv: // seit Cmd/Ctrl+A Schnittlinien zusammen mit Wänden/etc. mitselektiert, @@ -1246,33 +1274,21 @@ export default function App() { const colids = new Set(notLocked("columnIds", selectedColumnIds)); const rfids = new Set(notLocked("roofIds", selectedRoofIds)); const ctxids = new Set(selectedContextObjectIds); - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.filter((d) => !dids.has(d.id)), - walls: p.walls.filter((w) => !wids.has(w.id)), - ceilings: (p.ceilings ?? []).filter((c) => !cids.has(c.id)), - roofs: (p.roofs ?? []).filter((r) => !rfids.has(r.id)), - stairs: (p.stairs ?? []).filter((s) => !stids.has(s.id)), - rooms: (p.rooms ?? []).filter((r) => !rmids.has(r.id)), - extrudedSolids: (p.extrudedSolids ?? []).filter((s) => !exids.has(s.id)), - columns: (p.columns ?? []).filter((c) => !colids.has(c.id)), - // Öffnungen: eigene Auswahl löschen UND alle, deren Host-Wand entfällt. - openings: (p.openings ?? []).filter( - (o) => !oids.has(o.id) && !wids.has(o.hostWallId), - ), - context: (p.context ?? []).filter((o) => !ctxids.has(o.id)), - })); - setSelectedDrawingIds([]); - setSelectedWallIds([]); - setSelectedCeilingIds([]); - setSelectedOpeningIds([]); - setSelectedStairIds([]); - setSelectedRoomIds([]); - setSelectedExtrudedSolidIds([]); - setSelectedColumnIds([]); - setSelectedRoofIds([]); - setSelectedContextObjectIds([]); - setSelectedSectionLineIds([]); + setProject( + opsMutation((p) => [ + ...removeItems(p, "drawings2d", dids), + ...removeItems(p, "walls", wids), + ...removeItems(p, "ceilings", cids), + ...removeItems(p, "roofs", rfids), + ...removeItems(p, "stairs", stids), + ...removeItems(p, "rooms", rmids), + ...removeItems(p, "extrudedSolids", exids), + ...removeItems(p, "columns", colids), + // Öffnungen: eigene Auswahl löschen UND alle, deren Host-Wand entfällt. + ...removeItems(p, "openings", (o) => oids.has(o.id) || wids.has(o.hostWallId)), + ...removeItems(p, "context", ctxids), + ]), + ); }; // Tastatur im Auswahl-Werkzeug: Ctrl/Cmd+A = alles wählen, Entf/Backspace = @@ -1823,6 +1839,7 @@ export default function App() { moveRoomBy, moveCeilingBy, moveElementByOf, + groupChanges, }); // Nummern-Shortcuts für Zeichenwerkzeuge (Vectorworks-Stil): 1 Text, 2 Linie, diff --git a/src/commands/cmds/arc.ts b/src/commands/cmds/arc.ts index e0df69d3..3be38e40 100644 --- a/src/commands/cmds/arc.ts +++ b/src/commands/cmds/arc.ts @@ -42,11 +42,12 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; @@ -202,8 +203,8 @@ function lineDraft(a: Vec2, b: Vec2): ToolDraft { return { preview: [{ kind: "line", a, b }], vertices: [a] }; } -function appendArc(p: Project, center: Vec2, r: number, a0: number, a1: number, ctx: CommandContext): Project { - if (r < EPS) return p; +function appendArc(center: Vec2, r: number, a0: number, a1: number, ctx: CommandContext): CoreOp[] { + if (r < EPS) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -211,7 +212,7 @@ function appendArc(p: Project, center: Vec2, r: number, a0: number, a1: number, categoryCode: ctx.defaultCategoryCode, geom: { shape: "arc", center, r, a0, a1 }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (method: ArcMethod): [CommandState, CommandResult] => [ @@ -268,7 +269,7 @@ export const arcCommand: Command = { if (!arc) return [s, { draft: null }]; return [ idle("ser")[0], - { draft: null, done: true, commit: (p) => appendArc(p, arc.center, arc.r, arc.a0, arc.a1, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendArc(arc.center, arc.r, arc.a0, arc.a1, ctx)) }, ]; } if (input.kind !== "point") return [s, { draft: null }]; @@ -291,7 +292,7 @@ export const arcCommand: Command = { const { center, r, a0 } = s; return [ idle("center")[0], - { draft: null, done: true, commit: (p) => appendArc(p, center, r, a0, a1, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendArc(center, r, a0, a1, ctx)) }, ]; } @@ -311,7 +312,7 @@ export const arcCommand: Command = { if (!arc) return [s, { draft: lineDraft(s.a, pt) }]; // kollinear — Punkt ignorieren, weiter warten return [ idle("three")[0], - { draft: null, done: true, commit: (p) => appendArc(p, arc.center, arc.r, arc.a0, arc.a1, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendArc(arc.center, arc.r, arc.a0, arc.a1, ctx)) }, ]; } @@ -331,7 +332,7 @@ export const arcCommand: Command = { if (!arc) return [s, { draft: lineDraft(s.a, s.b) }]; // Radius zu klein — weiter warten return [ idle("ser")[0], - { draft: null, done: true, commit: (p) => appendArc(p, arc.center, arc.r, arc.a0, arc.a1, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendArc(arc.center, arc.r, arc.a0, arc.a1, ctx)) }, ]; } @@ -350,7 +351,7 @@ export const arcCommand: Command = { if (!sedArc) return [s, { draft: lineDraft(s.a, s.b) }]; // entartete Richtung — weiter warten return [ idle("sed")[0], - { draft: null, done: true, commit: (p) => appendArc(p, sedArc.center, sedArc.r, sedArc.a0, sedArc.a1, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendArc(sedArc.center, sedArc.r, sedArc.a0, sedArc.a1, ctx)) }, ]; }, diff --git a/src/commands/cmds/array.ts b/src/commands/cmds/array.ts index e112cba9..167e1b59 100644 --- a/src/commands/cmds/array.ts +++ b/src/commands/cmds/array.ts @@ -23,7 +23,7 @@ // wie move/copy). Leere Auswahl → No-op. import { - commitTransform, + transformMutation, hasTransformSelection, toTransformSel, transformPreview, @@ -200,7 +200,7 @@ export const arrayCommand: Command = { const pts = kind === "polar" ? polarPts(base, segAngleDeg(base, target)) : [base, target]; return [ idle(kind)[0], - { draft: null, done: true, commit: (p) => commitTransform(p, toTransformSel(sel), op, pts, "array", lastCount) }, + { draft: null, done: true, commit: transformMutation(toTransformSel(sel), op, pts, "array", lastCount) }, ]; }, diff --git a/src/commands/cmds/bezier.ts b/src/commands/cmds/bezier.ts index 8d7c7db3..cceb3a8a 100644 --- a/src/commands/cmds/bezier.ts +++ b/src/commands/cmds/bezier.ts @@ -17,10 +17,11 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; interface BezierStart extends CommandState { phase: "start"; @@ -58,8 +59,8 @@ function bezierDraft(pts: Vec2[], rubber: Vec2[]): ToolDraft { return { preview, vertices: pts.length > 0 ? [pts[0]] : [] }; } -function appendBezier(p: Project, pts: Vec2[], ctx: CommandContext): Project { - if (pts.length < 4) return p; +function appendBezier(pts: Vec2[], ctx: CommandContext): CoreOp[] { + if (pts.length < 4) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -67,7 +68,7 @@ function appendBezier(p: Project, pts: Vec2[], ctx: CommandContext): Project { categoryCode: ctx.defaultCategoryCode, geom: { shape: "bezier", pts }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -76,7 +77,7 @@ const idle = (): [CommandState, CommandResult] => [ ]; const finish = (pts: Vec2[], ctx: CommandContext): [CommandState, CommandResult] => [ { phase: "start", lastPoint: null } as BezierStart, - { draft: null, done: true, commit: (p) => appendBezier(p, pts, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendBezier(pts, ctx)) }, ]; export const bezierCommand: Command = { diff --git a/src/commands/cmds/block.ts b/src/commands/cmds/block.ts index 4b5e2da6..6619e424 100644 --- a/src/commands/cmds/block.ts +++ b/src/commands/cmds/block.ts @@ -22,9 +22,10 @@ import type { CommandContext, CommandResult, CommandState, - Project, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; @@ -51,14 +52,12 @@ function readDefs(ctx: CommandContext): { ids: string[]; names: string[] } { return { ids: defs.map((d) => d.id), names: defs.map((d) => d.name) }; } -function appendInstance( - p: Project, - blockDefId: string, +function appendInstance(blockDefId: string, at: Vec2, rotation: number, scale: number, ctx: CommandContext, -): Project { +): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -66,7 +65,7 @@ function appendInstance( categoryCode: ctx.defaultCategoryCode, geom: { shape: "block", blockDefId, at, rotation, scale }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } /** Drehwinkel + Skalierungsfaktor aus DEMSELBEN Punkt: Klick auf `at` = (0, 1). */ @@ -117,7 +116,7 @@ export const blockCommand: Command = { const { rotation, scale } = rotationAndScaleFrom(at, pt); return [ idle()[0], - { draft: null, done: true, commit: (p) => appendInstance(p, blockDefId, at, rotation, scale, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendInstance(blockDefId, at, rotation, scale, ctx)) }, ]; }, diff --git a/src/commands/cmds/ceiling.ts b/src/commands/cmds/ceiling.ts index 2ace28b9..d9ea59c4 100644 --- a/src/commands/cmds/ceiling.ts +++ b/src/commands/cmds/ceiling.ts @@ -26,10 +26,11 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -115,9 +116,9 @@ function ceilingDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { } /** Hängt eine Decke ans Projekt (immutabel). Entartete Umrisse werden verworfen. */ -function appendCeiling(p: Project, pts: Vec2[], ctx: CommandContext): Project { +function appendCeiling(pts: Vec2[], ctx: CommandContext): CoreOp[] { const outline = normalizeOutline(pts); - if (!outline || ceilingArea(outline) < 1e-4) return p; + if (!outline || ceilingArea(outline) < 1e-4) return []; const ceiling: Ceiling = { id: uniqueId("C"), type: "ceiling", @@ -126,8 +127,7 @@ function appendCeiling(p: Project, pts: Vec2[], ctx: CommandContext): Project { outline, wallTypeId: activeTypeId(ctx), }; - const ceilings = p.ceilings ? [...p.ceilings, ceiling] : [ceiling]; - return { ...p, ceilings }; + return addItems("ceilings", [ceiling]); } const idle = (): [CommandState, CommandResult] => [ @@ -175,7 +175,7 @@ export const ceilingCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null } as CeilIdle, - { draft: null, done: true, commit: (p) => appendCeiling(p, pts, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendCeiling(pts, ctx)) }, ]; } return [s, { draft: ceilingDraft(s.points, s.cursor) }]; @@ -197,7 +197,7 @@ export const ceilingCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null } as CeilIdle, - { draft: null, done: true, commit: (p) => appendCeiling(p, pts, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendCeiling(pts, ctx)) }, ]; } // Null-Strecke (Klick auf denselben Punkt) ignorieren. @@ -224,7 +224,7 @@ export const ceilingCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null } as CeilIdle, - { draft: null, done: true, commit: (p) => appendCeiling(p, pts, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendCeiling(pts, ctx)) }, ]; } return idle(); diff --git a/src/commands/cmds/circle.ts b/src/commands/cmds/circle.ts index 94bc2869..7e49a7bb 100644 --- a/src/commands/cmds/circle.ts +++ b/src/commands/cmds/circle.ts @@ -52,6 +52,8 @@ import type { Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; @@ -265,8 +267,8 @@ function lineDraft(a: Vec2, b: Vec2): ToolDraft { return { preview: [{ kind: "line", a, b }], vertices: [a] }; } -function appendCircle(p: Project, center: Vec2, r: number, ctx: CommandContext): Project { - if (r < EPS) return p; +function appendCircle(center: Vec2, r: number, ctx: CommandContext): CoreOp[] { + if (r < EPS) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -274,7 +276,7 @@ function appendCircle(p: Project, center: Vec2, r: number, ctx: CommandContext): categoryCode: ctx.defaultCategoryCode, geom: { shape: "circle", center, r }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (method: CircleMethod): [CommandState, CommandResult] => [ @@ -335,7 +337,7 @@ export const circleCommand: Command = { if (input.kind === "number") r = input.value; else r = dist(s.center, input.point); const center = s.center; - return [idle("center")[0], { draft: null, done: true, commit: (p) => appendCircle(p, center, r, ctx) }]; + return [idle("center")[0], { draft: null, done: true, commit: opsMutation(() => appendCircle(center, r, ctx)) }]; } if (s.method === "ttr") { @@ -346,7 +348,7 @@ export const circleCommand: Command = { const center = r > EPS ? nearestCandidate(tangentCircleCenters(s.t1, s.t2, r), s.near1, s.near2) : null; // Kein Kandidat (z. B. Radius geometrisch unpassend) — ignorieren, weiter warten. if (!center) return [s, { draft: null }]; - return [idle("ttr")[0], { draft: null, done: true, commit: (p) => appendCircle(p, center, r, ctx) }]; + return [idle("ttr")[0], { draft: null, done: true, commit: opsMutation(() => appendCircle(center, r, ctx)) }]; } if (input.kind !== "point") return [s, { draft: null }]; const pick = pickTangentTarget(ctx.project, ctx.level.id, input.point); @@ -387,7 +389,7 @@ export const circleCommand: Command = { } const center = mid(s.a, pt); const r = dist(s.a, pt) / 2; - return [idle("twoPoint")[0], { draft: null, done: true, commit: (p) => appendCircle(p, center, r, ctx) }]; + return [idle("twoPoint")[0], { draft: null, done: true, commit: opsMutation(() => appendCircle(center, r, ctx)) }]; } // threePoint @@ -405,7 +407,7 @@ export const circleCommand: Command = { if (!circ) return [s, { draft: lineDraft(s.a, pt) }]; // kollinear — ignorieren, weiter warten return [ idle("threePoint")[0], - { draft: null, done: true, commit: (p) => appendCircle(p, circ.center, circ.r, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendCircle(circ.center, circ.r, ctx)) }, ]; }, diff --git a/src/commands/cmds/column.ts b/src/commands/cmds/column.ts index 7d6cf22f..a84fa172 100644 --- a/src/commands/cmds/column.ts +++ b/src/commands/cmds/column.ts @@ -22,9 +22,10 @@ import type { CommandResult, CommandState, CmdOption, - Project, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; /** Default-Ebene (Kategorie) für Stützen: „50" Tragwerk (Fallback: aktive). */ const COLUMN_CATEGORY = "50"; @@ -48,11 +49,9 @@ function currentProfile(): ColumnProfile { } /** Fügt die Stütze immutabel an `project.columns` an. */ -function appendColumn( - p: Project, - position: Vec2, +function appendColumn(position: Vec2, ctx: CommandContext, -): Project { +): CoreOp[] { const height = ctx.level.floorHeight != null && ctx.level.floorHeight > 0 ? ctx.level.floorHeight @@ -67,7 +66,7 @@ function appendColumn( rotation: 0, height, }; - return { ...p, columns: [...(p.columns ?? []), column] }; + return addItems("columns", [column]); } interface ColState extends CommandState { @@ -135,7 +134,7 @@ export const columnCommand: Command = { if (input.kind === "point") { return [ { phase: "done", lastPoint: null } as ColState, - { draft: null, done: true, commit: (p) => appendColumn(p, input.point, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendColumn(input.point, ctx)) }, ]; } return [s, { draft: null }]; diff --git a/src/commands/cmds/copy.ts b/src/commands/cmds/copy.ts index e49e66be..daf0d109 100644 --- a/src/commands/cmds/copy.ts +++ b/src/commands/cmds/copy.ts @@ -5,11 +5,11 @@ // → weitere Zielpunkte = weitere Kopien (Basispunkt bleibt), bis Esc/Enter. // // Die Auswahl kommt vorab über ctx.selection. Leere Auswahl → No-op + Hinweis. -// Der Commit nutzt `commitTransform` (op:"move", mode:"copy") — eine Kopie der +// Der Commit nutzt `transformMutation` (op:"move", mode:"copy") — eine Kopie der // Auswahl an die Endlage, Original unverändert; neue IDs via uniqueId (dort). import { - commitTransform, + transformMutation, hasTransformSelection, toTransformSel, transformPreview, @@ -136,7 +136,7 @@ export const copyCommand: Command = { next, { draft: copyDraft(ctx.project, sel, base, pt), - commit: (p) => commitTransform(p, toTransformSel(sel), "move", [base, pt], "copy", 1), + commit: transformMutation(toTransformSel(sel), "move", [base, pt], "copy", 1), }, ]; }, diff --git a/src/commands/cmds/detailref.ts b/src/commands/cmds/detailref.ts index 55b96f57..2754a667 100644 --- a/src/commands/cmds/detailref.ts +++ b/src/commands/cmds/detailref.ts @@ -14,10 +14,11 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const PREVIEW_RADIUS = 0.3; // Modell-Meter, deckt sich mit DETAILREF_RADIUS_M (drawing2d.ts) const DEFAULT_LABEL = "A"; @@ -39,7 +40,7 @@ function pointDraft(at: Vec2): ToolDraft { return { preview, vertices: [at] }; } -function appendDetailRef(p: Project, at: Vec2, ctx: CommandContext): Project { +function appendDetailRef(at: Vec2, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -47,7 +48,7 @@ function appendDetailRef(p: Project, at: Vec2, ctx: CommandContext): Project { categoryCode: ctx.defaultCategoryCode, geom: { shape: "detailref", at, label: DEFAULT_LABEL }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -68,7 +69,7 @@ export const detailrefCommand: Command = { if (input.kind !== "point") return [s, { draft: null }]; return [ { phase: "point", lastPoint: null } as DetailRefIdle, - { draft: null, done: true, commit: (p) => appendDetailRef(p, input.point, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendDetailRef(input.point, ctx)) }, ]; }, diff --git a/src/commands/cmds/dimension.ts b/src/commands/cmds/dimension.ts index a31f1191..e53c34d3 100644 --- a/src/commands/cmds/dimension.ts +++ b/src/commands/cmds/dimension.ts @@ -36,6 +36,8 @@ import type { ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation, patchItem } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); @@ -151,16 +153,11 @@ function offsetDraft(pts: Vec2[], offset: number, at: Vec2 | null): ToolDraft { } /** Committet eine Kette: neu anhängen (editId null) ODER dasselbe Element ersetzen. */ -function commitChain(p: Project, pts: Vec2[], offset: number, editId: string | null, ctx: CommandContext): Project { +function commitChain(p: Project, pts: Vec2[], offset: number, editId: string | null, ctx: CommandContext): CoreOp[] { const cleaned = pts.filter((pt, i) => i === 0 || dist(pts[i - 1], pt) >= EPS); - if (cleaned.length < 2) return p; // zu wenig gültige Punkte → nichts committen/ändern + if (cleaned.length < 2) return []; // zu wenig gültige Punkte → nichts committen/ändern if (editId) { - return { - ...p, - drawings2d: p.drawings2d.map((d) => - d.id === editId ? { ...d, geom: { shape: "dimension", pts: cleaned, offset } } : d, - ), - }; + return patchItem(p, "drawings2d", editId, (d): Drawing2D => ({ ...d, geom: { shape: "dimension", pts: cleaned, offset } })); } const d: Drawing2D = { id: uniqueId("dr2d"), @@ -169,7 +166,7 @@ function commitChain(p: Project, pts: Vec2[], offset: number, editId: string | n categoryCode: ctx.defaultCategoryCode, geom: { shape: "dimension", pts: cleaned, offset }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -237,7 +234,7 @@ export const dimensionCommand: Command = { const editId = s.editId; return [ { phase: "start", lastPoint: null }, - { draft: null, done: true, commit: (p) => commitChain(p, pts, offset, editId, ctx) }, + { draft: null, done: true, commit: opsMutation((p) => commitChain(p, pts, offset, editId, ctx)) }, ]; }, diff --git a/src/commands/cmds/ellipse.ts b/src/commands/cmds/ellipse.ts index 6e79a1cf..2c72920c 100644 --- a/src/commands/cmds/ellipse.ts +++ b/src/commands/cmds/ellipse.ts @@ -30,11 +30,12 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; @@ -138,15 +139,13 @@ function axisMinorDraft(center: Vec2, major: Vec2, cursor: Vec2 | null): ToolDra // ── Commit ─────────────────────────────────────────────────────────────────── -function appendEllipse( - p: Project, - center: Vec2, +function appendEllipse(center: Vec2, rx: number, ry: number, rotation: number, ctx: CommandContext, -): Project { - if (rx < EPS || ry < EPS) return p; +): CoreOp[] { + if (rx < EPS || ry < EPS) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -154,7 +153,7 @@ function appendEllipse( categoryCode: ctx.defaultCategoryCode, geom: { shape: "ellipse", center, rx, ry, rotation }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (method: EllipseMethod): [CommandState, CommandResult] => [ @@ -201,7 +200,7 @@ export const ellipseCommand: Command = { return [ns, { draft: boxDraft(pt, pt) }]; } const { center, rx, ry } = ellipseFromCorners(s.p0, pt); - return [idle("box")[0], { draft: null, done: true, commit: (p) => appendEllipse(p, center, rx, ry, 0, ctx) }]; + return [idle("box")[0], { draft: null, done: true, commit: opsMutation(() => appendEllipse(center, rx, ry, 0, ctx)) }]; } // axis @@ -221,7 +220,7 @@ export const ellipseCommand: Command = { const rotation = angleOf(center, major); return [ idle("axis")[0], - { draft: null, done: true, commit: (p) => appendEllipse(p, center, rx, ry, rotation, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendEllipse(center, rx, ry, rotation, ctx)) }, ]; }, diff --git a/src/commands/cmds/extrude.ts b/src/commands/cmds/extrude.ts index 58a5ec0b..f2645452 100644 --- a/src/commands/cmds/extrude.ts +++ b/src/commands/cmds/extrude.ts @@ -25,6 +25,8 @@ import type { Project, Vec2, } from "../types"; +import { addItems, opsMutation, removeItems } from "../../core"; +import type { CoreOp } from "../../core"; const HIT_TOL = 0.25; // Modell-Meter: Pick-Toleranz für die Profil-Wahl @@ -113,7 +115,7 @@ function appendExtrudedSolid( taper: number, sourceId: string, ctx: CommandContext, -): Project { +): CoreOp[] { const solid: ExtrudedSolid = { id: uniqueId("extrude"), type: "extrudedSolid", @@ -123,11 +125,7 @@ function appendExtrudedSolid( circle: profile.circle, ...(taper > 0 ? { taper } : {}), }; - return { - ...p, - drawings2d: p.drawings2d.filter((d) => d.id !== sourceId), - extrudedSolids: [...(p.extrudedSolids ?? []), solid], - }; + return [...removeItems(p, "drawings2d", [sourceId]), ...addItems("extrudedSolids", [solid])]; } // ── Zustand ─────────────────────────────────────────────────────────────────── @@ -177,7 +175,7 @@ const commitTaper = ( ctx: CommandContext, ): [CommandState, CommandResult] => [ { phase: "done", lastPoint: null } as ExDone, - { draft: null, done: true, commit: (p) => appendExtrudedSolid(p, profile, height, taper, sourceId, ctx) }, + { draft: null, done: true, commit: opsMutation((p) => appendExtrudedSolid(p, profile, height, taper, sourceId, ctx)) }, ]; export const extrudeCommand: Command = { diff --git a/src/commands/cmds/kote.ts b/src/commands/cmds/kote.ts index 80b14f13..284b8d80 100644 --- a/src/commands/cmds/kote.ts +++ b/src/commands/cmds/kote.ts @@ -14,11 +14,12 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; type KoteKind = "okFertig" | "ukFertig" | "okRoh" | "ukRoh"; const KIND_ORDER: KoteKind[] = ["okFertig", "ukFertig", "okRoh", "ukRoh"]; @@ -62,7 +63,7 @@ function valueDraft(at: Vec2, kind: KoteKind): ToolDraft { return { preview, vertices: [at] }; } -function appendKote(p: Project, at: Vec2, value: number, kind: KoteKind, ctx: CommandContext): Project { +function appendKote(at: Vec2, value: number, kind: KoteKind, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -70,7 +71,7 @@ function appendKote(p: Project, at: Vec2, value: number, kind: KoteKind, ctx: Co categoryCode: ctx.defaultCategoryCode, geom: { shape: "kote", at, value, kind, rotation: 0 }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -101,7 +102,7 @@ export const koteCommand: Command = { const { at, kind } = s; return [ { phase: "point", lastPoint: null }, - { draft: null, done: true, commit: (p) => appendKote(p, at, input.value, kind, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendKote(at, input.value, kind, ctx)) }, ]; }, diff --git a/src/commands/cmds/leader.ts b/src/commands/cmds/leader.ts index 635fdb61..4c5f9a2a 100644 --- a/src/commands/cmds/leader.ts +++ b/src/commands/cmds/leader.ts @@ -22,11 +22,12 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const DEFAULT_TEXT_HEIGHT_M = 0.25; const MAX_BENDS = 4; @@ -53,14 +54,12 @@ interface LeaderAnchor extends CommandState { } type LeaderState = LeaderTarget | LeaderBend | LeaderAnchor; -function appendLeaderText( - p: Project, - id: string, +function appendLeaderText(id: string, at: Vec2, target: Vec2, bends: Vec2[], ctx: CommandContext, -): Project { +): CoreOp[] { const d: Drawing2D = { id, type: "drawing2d", @@ -76,7 +75,7 @@ function appendLeaderText( ...(bends.length > 0 ? { leaderBendPoints: bends } : {}), }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -143,7 +142,7 @@ export const leaderCommand: Command = { { draft: null, done: true, - commit: (p) => appendLeaderText(p, id, pt, target, bends, ctx), + commit: opsMutation(() => appendLeaderText(id, pt, target, bends, ctx)), focusDrawingId: id, }, ]; diff --git a/src/commands/cmds/line.ts b/src/commands/cmds/line.ts index ffd22127..71d602e1 100644 --- a/src/commands/cmds/line.ts +++ b/src/commands/cmds/line.ts @@ -36,6 +36,8 @@ import type { ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -81,7 +83,7 @@ function lineDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { } /** Hängt eine 2D-Linie ans Projekt (immutabel). Farbe/Strich erbt die Kategorie. */ -function appendLine(p: import("../types").Project, a: Vec2, b: Vec2, ctx: CommandContext) { +function appendLine(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -89,7 +91,7 @@ function appendLine(p: import("../types").Project, a: Vec2, b: Vec2, ctx: Comman categoryCode: ctx.defaultCategoryCode, geom: { shape: "line", a, b }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } export const lineCommand: Command = { @@ -117,7 +119,7 @@ export const lineCommand: Command = { } const a = s.a; const next: LineDrawing = { phase: "end", a: pt, cursor: pt, lastPoint: pt }; - return [next, { draft: lineDraft(pt, pt), commit: (p) => appendLine(p, a, pt, ctx) }]; + return [next, { draft: lineDraft(pt, pt), commit: opsMutation(() => appendLine(a, pt, ctx)) }]; }, onMove: (state, point): [CommandState, CommandResult] => { diff --git a/src/commands/cmds/mirror.ts b/src/commands/cmds/mirror.ts index 73b0c51a..ae438eec 100644 --- a/src/commands/cmds/mirror.ts +++ b/src/commands/cmds/mirror.ts @@ -7,12 +7,12 @@ // wie Move/Copy). Ist sie leer, ist nichts zu spiegeln: kurzer No-op mit Hinweis // („Nichts gewählt") und Beenden. // -// Der Commit nutzt den bestehenden, getesteten `commitTransform` (op:"mirror", +// Der Commit nutzt den bestehenden, getesteten `transformMutation` (op:"mirror", // mode:"copy") — er spiegelt Wände UND alle 2D-Formen immutabel an der Achse und // hängt das Spiegelbild als KOPIE an (das Original bleibt stehen). Das ist das // klassische Mirror „Kopie spiegeln" (Rhino/Vectorworks-Default). -import { commitTransform, hasTransformSelection, toTransformSel } from "../../tools/transform"; +import { transformMutation, hasTransformSelection, toTransformSel } from "../../tools/transform"; import { transformPreview } from "../../tools/transform"; import type { Command, @@ -132,7 +132,7 @@ export const mirrorCommand: Command = { { draft: null, done: true, - commit: (p) => commitTransform(p, toTransformSel(sel), "mirror", [a, pt], "copy", 1), + commit: transformMutation(toTransformSel(sel), "mirror", [a, pt], "copy", 1), }, ]; }, diff --git a/src/commands/cmds/move.ts b/src/commands/cmds/move.ts index 3b82d416..0de4a794 100644 --- a/src/commands/cmds/move.ts +++ b/src/commands/cmds/move.ts @@ -9,11 +9,11 @@ // einen zweiten, divergierenden Pick-Pfad für die Objektwahl aufzumachen; die // Selektion läuft schon sauber über die Plan-Ansicht/Store). // -// Der Commit nutzt den bestehenden, getesteten `commitTransform` (op:"move", +// Der Commit nutzt den bestehenden, getesteten `transformMutation` (op:"move", // mode:"move") statt eine zweite Verschiebe-Logik zu duplizieren — er bewegt // Wände UND alle 2D-Formen immutabel an die Endlage. -import { commitTransform, hasTransformSelection, toTransformSel } from "../../tools/transform"; +import { transformMutation, hasTransformSelection, toTransformSel } from "../../tools/transform"; import { transformPreview } from "../../tools/transform"; import type { Command, @@ -145,7 +145,7 @@ export const moveCommand: Command = { { draft: null, done: true, - commit: (p) => commitTransform(p, toTransformSel(sel), "move", [base, pt], "move", 1), + commit: transformMutation(toTransformSel(sel), "move", [base, pt], "move", 1), }, ]; }, diff --git a/src/commands/cmds/multiline.ts b/src/commands/cmds/multiline.ts index ed97ae3e..9de29102 100644 --- a/src/commands/cmds/multiline.ts +++ b/src/commands/cmds/multiline.ts @@ -27,10 +27,11 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -76,8 +77,8 @@ function multilinePairs(a: Vec2, b: Vec2, spacing: number, sign: number, count: return out; } -function appendMultiline(p: Project, a: Vec2, b: Vec2, spacing: number, sign: number, count: number, ctx: CommandContext): Project { - if (segLen(a, b) < EPS) return p; +function appendMultiline(a: Vec2, b: Vec2, spacing: number, sign: number, count: number, ctx: CommandContext): CoreOp[] { + if (segLen(a, b) < EPS) return []; const pairs = multilinePairs(a, b, spacing, sign, count); const copies: Drawing2D[] = pairs.map(([pa, pb]) => ({ id: uniqueId("dr2d"), @@ -86,7 +87,7 @@ function appendMultiline(p: Project, a: Vec2, b: Vec2, spacing: number, sign: nu categoryCode: ctx.defaultCategoryCode, geom: { shape: "line", a: pa, b: pb }, })); - return { ...p, drawings2d: [...p.drawings2d, ...copies] }; + return addItems("drawings2d", copies); } const COUNT_OPTION: CmdOption = { id: "count", labelKey: "cmd.multiline.count" }; @@ -169,7 +170,7 @@ export const multilineCommand: Command = { const { a, b } = s; return [ idle()[0], - { draft: null, done: true, commit: (p) => appendMultiline(p, a, b, lastSpacing, lastSign, lastCount, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendMultiline(a, b, lastSpacing, lastSign, lastCount, ctx)) }, ]; } if (input.kind === "point") { @@ -177,7 +178,7 @@ export const multilineCommand: Command = { const { a, b } = s; return [ idle()[0], - { draft: null, done: true, commit: (p) => appendMultiline(p, a, b, lastSpacing, lastSign, lastCount, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendMultiline(a, b, lastSpacing, lastSign, lastCount, ctx)) }, ]; } return [s, { draft: null }]; diff --git a/src/commands/cmds/offset.ts b/src/commands/cmds/offset.ts index 9ab6a2ea..71643afa 100644 --- a/src/commands/cmds/offset.ts +++ b/src/commands/cmds/offset.ts @@ -29,6 +29,8 @@ import type { Project, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const HIT_TOL = 0.25; // Modell-Meter: Pick-Toleranz für die Kurvenwahl @@ -183,11 +185,11 @@ function offsetDraftShapes(curve: Curve, d: number): DraftShape[] { return [{ kind: "poly", pts: tess, closed: curve.closed }]; } -function appendOffset(p: Project, src: Drawing2D, d: number): Project { +function appendOffset(src: Drawing2D, d: number): CoreOp[] { const geom = offsetGeom(src, d); - if (!geom) return p; + if (!geom) return []; const copy: Drawing2D = { ...src, id: uniqueId("dr2d"), geom }; - return { ...p, drawings2d: [...p.drawings2d, copy] }; + return addItems("drawings2d", [copy]); } // ── Zustand ─────────────────────────────────────────────────────────────────── @@ -316,7 +318,7 @@ function offsetSideInput( const d = sign * mag; return [ { phase: "done", lastPoint: null } as OffDone, - { draft: null, done: true, commit: (p) => appendOffset(p, src, d) }, + { draft: null, done: true, commit: opsMutation(() => appendOffset(src, d)) }, ]; } @@ -327,7 +329,7 @@ function offsetSideInput( const d = sign * lastDistance; return [ { phase: "done", lastPoint: null } as OffDone, - { draft: null, done: true, commit: (p) => appendOffset(p, src, d) }, + { draft: null, done: true, commit: opsMutation(() => appendOffset(src, d)) }, ]; } diff --git a/src/commands/cmds/opening.ts b/src/commands/cmds/opening.ts index 58edd854..6e9992c0 100644 --- a/src/commands/cmds/opening.ts +++ b/src/commands/cmds/opening.ts @@ -22,10 +22,11 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; /** Default-Ebene (Kategorie) für Öffnungen: „21" Türen/Fenster (Fallback: aktive). */ const OPENING_CATEGORY = "21"; @@ -183,7 +184,7 @@ function posDraft(s: OpPos): ToolDraft { } /** Hängt eine Öffnung ans Projekt (immutabel). */ -function appendOpening(p: Project, s: OpPos, ctx: CommandContext): Project { +function appendOpening(s: OpPos, ctx: CommandContext): CoreOp[] { const len = Math.hypot(s.end.x - s.start.x, s.end.y - s.start.y); const width = Math.max(0.1, Math.min(s.width, len)); const position = Math.max(0, Math.min(s.posAlong, Math.max(0, len - width))); @@ -208,8 +209,7 @@ function appendOpening(p: Project, s: OpPos, ctx: CommandContext): Project { ? { hinge: s.hinge, swing: s.side, openingDir: s.dir, swingAngle: s.swingAngle } : {}), }; - const openings = p.openings ? [...p.openings, opening] : [opening]; - return { ...p, openings }; + return addItems("openings", [opening]); } const idle = (from?: OpState): [CommandState, CommandResult] => [ @@ -307,7 +307,7 @@ export const openingCommand: Command = { const ns: OpPos = { ...s, posAlong: proj.t, cursor: pt }; return [ idle(s)[0], - { draft: null, done: true, commit: (p) => appendOpening(p, ns, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendOpening(ns, ctx)) }, ]; }, @@ -325,7 +325,7 @@ export const openingCommand: Command = { const ns = s; return [ idle(s)[0], - { draft: null, done: true, commit: (p) => appendOpening(p, ns, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendOpening(ns, ctx)) }, ]; } return idle(s); diff --git a/src/commands/cmds/pointmarker.ts b/src/commands/cmds/pointmarker.ts index 963d73e4..9c9fa15b 100644 --- a/src/commands/cmds/pointmarker.ts +++ b/src/commands/cmds/pointmarker.ts @@ -11,10 +11,11 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const PREVIEW_RADIUS = 0.08; // Modell-Meter, deckt sich mit POINTMARKER_RADIUS_M (drawing2d.ts) const PREVIEW_CROSS = 0.12; @@ -39,7 +40,7 @@ function pointDraft(at: Vec2): ToolDraft { return { preview, vertices: [at] }; } -function appendPointMarker(p: Project, at: Vec2, ctx: CommandContext): Project { +function appendPointMarker(at: Vec2, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -47,7 +48,7 @@ function appendPointMarker(p: Project, at: Vec2, ctx: CommandContext): Project { categoryCode: ctx.defaultCategoryCode, geom: { shape: "pointmarker", at }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -68,7 +69,7 @@ export const pointmarkerCommand: Command = { if (input.kind !== "point") return [s, { draft: null }]; return [ { phase: "point", lastPoint: null } as PointMarkerIdle, - { draft: null, done: true, commit: (p) => appendPointMarker(p, input.point, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendPointMarker(input.point, ctx)) }, ]; }, diff --git a/src/commands/cmds/polygon.ts b/src/commands/cmds/polygon.ts index e9011b71..0bc17917 100644 --- a/src/commands/cmds/polygon.ts +++ b/src/commands/cmds/polygon.ts @@ -35,11 +35,12 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const MIN_SIDES = 3; @@ -148,8 +149,8 @@ function edgeDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { return { preview: [{ kind: "poly", pts, closed: true }], vertices: [a], hud: segmentHud(a, cursor) }; } -function appendPolygon(p: Project, center: Vec2, r: number, dir: Vec2 | null, ctx: CommandContext): Project { - if (r < EPS) return p; +function appendPolygon(center: Vec2, r: number, dir: Vec2 | null, ctx: CommandContext): CoreOp[] { + if (r < EPS) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -157,11 +158,11 @@ function appendPolygon(p: Project, center: Vec2, r: number, dir: Vec2 | null, ct categoryCode: ctx.defaultCategoryCode, geom: { shape: "polyline", pts: polygonPts(center, r, lastSides, lastMode, dir), closed: true }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } -function appendPolygonFromEdge(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project { - if (dist(a, b) < EPS) return p; +function appendPolygonFromEdge(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] { + if (dist(a, b) < EPS) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -169,7 +170,7 @@ function appendPolygonFromEdge(p: Project, a: Vec2, b: Vec2, ctx: CommandContext categoryCode: ctx.defaultCategoryCode, geom: { shape: "polyline", pts: polygonFromEdge(a, b, lastSides), closed: true }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -247,7 +248,7 @@ export const polygonCommand: Command = { } const a = s.a; const b = input.point; - return [idle()[0], { draft: null, done: true, commit: (p) => appendPolygonFromEdge(p, a, b, ctx) }]; + return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendPolygonFromEdge(a, b, ctx)) }]; } // phase "radius" @@ -266,7 +267,7 @@ export const polygonCommand: Command = { const center = s.center; return [ idle()[0], - { draft: null, done: true, commit: (p) => appendPolygon(p, center, r, dir, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendPolygon(center, r, dir, ctx)) }, ]; }, diff --git a/src/commands/cmds/polyline.ts b/src/commands/cmds/polyline.ts index df330b1b..53e01cfc 100644 --- a/src/commands/cmds/polyline.ts +++ b/src/commands/cmds/polyline.ts @@ -29,10 +29,11 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -200,13 +201,11 @@ function polyDraft( } /** Hängt eine 2D-Polylinie ans Projekt (immutabel). Farbe/Strich erbt die Kategorie. */ -function appendPolyline( - p: Project, - pts: Vec2[], +function appendPolyline(pts: Vec2[], bulges: number[], closed: boolean, ctx: CommandContext, -): Project { +): CoreOp[] { // `bulge` nur mitschreiben, wenn wirklich ein Bogen dabei ist — ein reiner // Geradenzug bleibt damit bitgleich zu vorher (additives Feld). const hasArc = bulges.some((b) => Math.abs(b) > EPS); @@ -219,7 +218,7 @@ function appendPolyline( ? { shape: "polyline", pts, closed, bulge: bulges.slice(0, closed ? pts.length : pts.length - 1) } : { shape: "polyline", pts, closed }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } /** Ruhezustand; behält den zuletzt gewählten Schließ-Modus bei. */ @@ -312,7 +311,7 @@ export const polylineCommand: Command = { const bl = [...s.bulges, closingBulge(s)]; return [ { phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle, - { draft: null, done: true, commit: (p) => appendPolyline(p, pts, bl, true, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, bl, true, ctx)) }, ]; } return [ @@ -371,7 +370,7 @@ export const polylineCommand: Command = { const bl = [...s.bulges, newBulge]; return [ { phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle, - { draft: null, done: true, commit: (p) => appendPolyline(p, pts, bl, true, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, bl, true, ctx)) }, ]; } const points = [...s.points, pt]; @@ -411,7 +410,7 @@ export const polylineCommand: Command = { const bl = close ? [...s.bulges, closingBulge(s)] : s.bulges; return [ { phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle, - { draft: null, done: true, commit: (p) => appendPolyline(p, pts, bl, close, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, bl, close, ctx)) }, ]; } return idle(s.closed, s.arc, s.tangent); diff --git a/src/commands/cmds/ray.ts b/src/commands/cmds/ray.ts index dff99793..dc4e66ed 100644 --- a/src/commands/cmds/ray.ts +++ b/src/commands/cmds/ray.ts @@ -14,10 +14,11 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -67,7 +68,7 @@ function rayDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { return draft; } -function appendRay(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project { +function appendRay(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -75,7 +76,7 @@ function appendRay(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project { categoryCode: ctx.defaultCategoryCode, geom: { shape: "ray", a, b }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } export const rayCommand: Command = { @@ -100,7 +101,7 @@ export const rayCommand: Command = { const a = s.a; return [ { phase: "start", lastPoint: null }, - { draft: null, done: true, commit: (p) => appendRay(p, a, pt, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendRay(a, pt, ctx)) }, ]; }, diff --git a/src/commands/cmds/rect.ts b/src/commands/cmds/rect.ts index a0f11504..8eec65bd 100644 --- a/src/commands/cmds/rect.ts +++ b/src/commands/cmds/rect.ts @@ -41,11 +41,12 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; @@ -310,8 +311,8 @@ function riseDraft(a: Vec2, b: Vec2, cursor: Vec2 | null): ToolDraft { // ── Commit ─────────────────────────────────────────────────────────────────── /** Achsparalleles Rechteck als `shape:"rect"` (geschlossen behandelt). */ -function appendRect(p: Project, min: Vec2, max: Vec2, ctx: CommandContext): Project { - if (max.x - min.x < EPS || max.y - min.y < EPS) return p; // Null-Rechteck +function appendRect(min: Vec2, max: Vec2, ctx: CommandContext): CoreOp[] { + if (max.x - min.x < EPS || max.y - min.y < EPS) return []; // Null-Rechteck const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -319,7 +320,7 @@ function appendRect(p: Project, min: Vec2, max: Vec2, ctx: CommandContext): Proj categoryCode: ctx.defaultCategoryCode, geom: { shape: "rect", min, max }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } /** @@ -327,11 +328,11 @@ function appendRect(p: Project, min: Vec2, max: Vec2, ctx: CommandContext): Proj * — `shape:"rect"` kann nur achsparallel, deshalb hier ein Ring aus vier Ecken. * Downstream (Füllung/Offset) behandelt einen geschlossenen Polygonzug als Ring. */ -function appendRotated(p: Project, pts: Vec2[], ctx: CommandContext): Project { +function appendRotated(pts: Vec2[], ctx: CommandContext): CoreOp[] { // Fläche prüfen: entartete Rechtecke verwerfen. const w = segLen(pts[0], pts[1]); const h = segLen(pts[1], pts[2]); - if (w < EPS || h < EPS) return p; + if (w < EPS || h < EPS) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -339,7 +340,7 @@ function appendRotated(p: Project, pts: Vec2[], ctx: CommandContext): Project { categoryCode: ctx.defaultCategoryCode, geom: { shape: "polyline", pts, closed: true }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } /** @@ -350,9 +351,9 @@ function appendRotated(p: Project, pts: Vec2[], ctx: CommandContext): Project { * passt (`roundedRectPts` liefert dann `null`, z. B. bei einem entarteten * Rechteck). */ -function appendRectRounded(p: Project, corners: Vec2[], ctx: CommandContext): Project { +function appendRectRounded(corners: Vec2[], ctx: CommandContext): CoreOp[] { const rr = roundedRectPts(corners, lastRadius); - if (!rr) return p; + if (!rr) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -360,7 +361,7 @@ function appendRectRounded(p: Project, corners: Vec2[], ctx: CommandContext): Pr categoryCode: ctx.defaultCategoryCode, geom: { shape: "polyline", pts: rr.pts, closed: true, bulge: rr.bulge }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (method: RectMethod): [CommandState, CommandResult] => [ @@ -436,14 +437,14 @@ export const rectCommand: Command = { { draft: null, done: true, - commit: (p) => { + commit: opsMutation(() => { const g = method === "center" ? centerGeom(a, pt) : rectGeom(a, pt); if (lastRadius >= EPS) { const corners = [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }]; - return appendRectRounded(p, corners, ctx); + return appendRectRounded(corners, ctx); } - return appendRect(p, g.min, g.max, ctx); - }, + return appendRect(g.min, g.max, ctx); + }), }, ]; } @@ -456,10 +457,10 @@ export const rectCommand: Command = { { draft: null, done: true, - commit: (p) => { + commit: opsMutation(() => { const corners = rotatedCorners(a, b, pt); - return lastRadius >= EPS ? appendRectRounded(p, corners, ctx) : appendRotated(p, corners, ctx); - }, + return lastRadius >= EPS ? appendRectRounded(corners, ctx) : appendRotated(corners, ctx); + }), }, ]; }, diff --git a/src/commands/cmds/revcloud.ts b/src/commands/cmds/revcloud.ts index f193e50d..bc65d3d1 100644 --- a/src/commands/cmds/revcloud.ts +++ b/src/commands/cmds/revcloud.ts @@ -19,10 +19,11 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const CLOSE_HIT = 0.15; // Modell-Meter: Klick nahe Startpunkt schliesst den Zug @@ -62,9 +63,9 @@ function revcloudDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { return draft; } -function appendRevcloud(p: Project, points: Vec2[], closed: boolean, ctx: CommandContext): Project { +function appendRevcloud(points: Vec2[], closed: boolean, ctx: CommandContext): CoreOp[] { const expanded = revisionCloudPts(points, closed, lastArcSize); - if (!expanded) return p; + if (!expanded) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -72,7 +73,7 @@ function appendRevcloud(p: Project, points: Vec2[], closed: boolean, ctx: Comman categoryCode: ctx.defaultCategoryCode, geom: { shape: "polyline", pts: expanded.pts, closed, bulge: expanded.bulge }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -105,7 +106,7 @@ export const revcloudCommand: Command = { } if (input.id === "close" && s.phase === "next" && s.points.length >= 3) { const pts = s.points; - return [idle()[0], { draft: null, done: true, commit: (p) => appendRevcloud(p, pts, true, ctx) }]; + return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendRevcloud(pts, true, ctx)) }]; } return [s, { draft: null }]; } @@ -123,7 +124,7 @@ export const revcloudCommand: Command = { // Klick nahe Startpunkt (≥3 Punkte) → schliessen (committet als Ring). if (s.points.length >= 3 && segLen(s.points[0], pt) < CLOSE_HIT) { const pts = s.points; - return [idle()[0], { draft: null, done: true, commit: (p) => appendRevcloud(p, pts, true, ctx) }]; + return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendRevcloud(pts, true, ctx)) }]; } const points = [...s.points, pt]; const ns: RevcloudDrawing = { phase: "next", points, cursor: pt, lastPoint: pt }; @@ -142,7 +143,7 @@ export const revcloudCommand: Command = { const s = state as RevcloudState; if (s.phase === "next" && s.points.length >= 2) { const pts = s.points; - return [idle()[0], { draft: null, done: true, commit: (p) => appendRevcloud(p, pts, false, ctx) }]; + return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendRevcloud(pts, false, ctx)) }]; } return idle(); }, diff --git a/src/commands/cmds/roof.ts b/src/commands/cmds/roof.ts index b2666a8d..beda8d4a 100644 --- a/src/commands/cmds/roof.ts +++ b/src/commands/cmds/roof.ts @@ -20,10 +20,11 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; /** Default-Ebene (Kategorie) für Dächer („31 Dächer"). */ const ROOF_CATEGORY = "31"; @@ -93,10 +94,10 @@ function roofDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { } /** Hängt ein Dach ans Projekt (immutabel). Entartete Rechtecke werden verworfen. */ -function appendRoof(p: Project, a: Vec2, b: Vec2, shape: RoofShape, ctx: CommandContext): Project { +function appendRoof(a: Vec2, b: Vec2, shape: RoofShape, ctx: CommandContext): CoreOp[] { const w = Math.abs(b.x - a.x); const d = Math.abs(b.y - a.y); - if (w < 0.1 || d < 0.1) return p; + if (w < 0.1 || d < 0.1) return []; const roof: Roof = { id: uniqueId("RF"), type: "roof", @@ -111,8 +112,7 @@ function appendRoof(p: Project, a: Vec2, b: Vec2, shape: RoofShape, ctx: Command ridgeAxis: w >= d ? "x" : "y", thickness: 0.2, }; - const roofs = p.roofs ? [...p.roofs, roof] : [roof]; - return { ...p, roofs }; + return addItems("roofs", [roof]); } const idle = (shape: RoofShape = "sattel"): [CommandState, CommandResult] => [ @@ -157,7 +157,7 @@ export const roofCommand: Command = { const shape = s.shape; return [ { phase: "start", shape, lastPoint: null } as RoofIdle, - { draft: null, done: true, commit: (p) => appendRoof(p, a, b, shape, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendRoof(a, b, shape, ctx)) }, ]; }, diff --git a/src/commands/cmds/room.ts b/src/commands/cmds/room.ts index 222cbf5f..a76ec33b 100644 --- a/src/commands/cmds/room.ts +++ b/src/commands/cmds/room.ts @@ -31,10 +31,11 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -134,11 +135,10 @@ function defaultRoomName(ctx: CommandContext): string { } /** Hängt einen Raum ans Projekt (immutabel); entartete Umrisse werden verworfen. */ -function appendRoom(p: Project, boundary: Vec2[], ctx: CommandContext): Project { - if (boundary.length < 3 || polygonArea(boundary) < 1e-4) return p; +function appendRoom(boundary: Vec2[], ctx: CommandContext): CoreOp[] { + if (boundary.length < 3 || polygonArea(boundary) < 1e-4) return []; const room = buildRoom(ctx, boundary); - const rooms = p.rooms ? [...p.rooms, room] : [room]; - return { ...p, rooms }; + return addItems("rooms", [room]); } // ── Zustand ────────────────────────────────────────────────────────────────── @@ -254,7 +254,7 @@ export const roomCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null, mode: s.mode } as RoomIdle, - { draft: null, done: true, commit: (p) => appendRoom(p, pts, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendRoom(pts, ctx)) }, ]; } return [s, { draft: s.phase === "draw" ? manualDraft(s.points, s.cursor) : null }]; @@ -275,7 +275,7 @@ export const roomCommand: Command = { if (boundary && boundary.length >= 3) { return [ { phase: "start", lastPoint: null, mode: "inside" } as RoomIdle, - { draft: null, done: true, commit: (p) => appendRoom(p, boundary, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendRoom(boundary, ctx)) }, ]; } // Kein umschlossener Bereich getroffen → im Werkzeug bleiben (kein Commit). @@ -298,7 +298,7 @@ export const roomCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null, mode: s.mode } as RoomIdle, - { draft: null, done: true, commit: (p) => appendRoom(p, pts, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendRoom(pts, ctx)) }, ]; } const last = s.points[s.points.length - 1]; @@ -329,7 +329,7 @@ export const roomCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null, mode: s.mode } as RoomIdle, - { draft: null, done: true, commit: (p) => appendRoom(p, pts, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendRoom(pts, ctx)) }, ]; } return idle(s.mode); diff --git a/src/commands/cmds/rotate.ts b/src/commands/cmds/rotate.ts index 6b5b2e31..c63df93b 100644 --- a/src/commands/cmds/rotate.ts +++ b/src/commands/cmds/rotate.ts @@ -11,11 +11,11 @@ // // Die Auswahl kommt vorab über `ctx.selection` (erst selektieren, dann Befehl — // wie Move/Copy/Mirror). Gedreht wird über den bestehenden, getesteten -// `commitTransform` (op:"rotate", mode:"move") — er bewegt das ORIGINAL, es +// `transformMutation` (op:"rotate", mode:"move") — er bewegt das ORIGINAL, es // entsteht keine Kopie. import { - commitTransform, + transformMutation, hasTransformSelection, toTransformSel, transformPreview, @@ -125,7 +125,7 @@ export const rotateCommand: Command = { { draft: null, done: true, - commit: (p) => commitTransform(p, toTransformSel(sel), "rotate", pts, "move", 1), + commit: transformMutation(toTransformSel(sel), "rotate", pts, "move", 1), }, ]; } @@ -166,8 +166,7 @@ export const rotateCommand: Command = { { draft: null, done: true, - commit: (p) => - commitTransform(p, toTransformSel(sel), "rotate", [center, ref, pt], "move", 1), + commit: transformMutation(toTransformSel(sel), "rotate", [center, ref, pt], "move", 1), }, ]; }, diff --git a/src/commands/cmds/scale.ts b/src/commands/cmds/scale.ts index 44d6be48..31317253 100644 --- a/src/commands/cmds/scale.ts +++ b/src/commands/cmds/scale.ts @@ -15,7 +15,7 @@ // desselben Typs verändert — bewusste Grenze, s. PENDENZEN.md. import { - commitTransform, + transformMutation, hasTransformSelection, toTransformSel, transformPreview, @@ -110,7 +110,7 @@ export const scaleCommand: Command = { { draft: null, done: true, - commit: (p) => commitTransform(p, toTransformSel(sel), "scale", pts, "move", 1), + commit: transformMutation(toTransformSel(sel), "scale", pts, "move", 1), }, ]; } @@ -145,7 +145,7 @@ export const scaleCommand: Command = { { draft: null, done: true, - commit: (p) => commitTransform(p, toTransformSel(sel), "scale", [base, ref, pt], "move", 1), + commit: transformMutation(toTransformSel(sel), "scale", [base, ref, pt], "move", 1), }, ]; }, diff --git a/src/commands/cmds/scalebar.ts b/src/commands/cmds/scalebar.ts index 3790ea3a..569de532 100644 --- a/src/commands/cmds/scalebar.ts +++ b/src/commands/cmds/scalebar.ts @@ -13,10 +13,11 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const LENGTH_PRESETS = [0.5, 1, 2, 5, 10, 20, 50]; let lastLength = 1; @@ -59,7 +60,7 @@ function pointDraft(at: Vec2): ToolDraft { }; } -function appendScalebar(p: Project, at: Vec2, ctx: CommandContext): Project { +function appendScalebar(at: Vec2, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -67,7 +68,7 @@ function appendScalebar(p: Project, at: Vec2, ctx: CommandContext): Project { categoryCode: ctx.defaultCategoryCode, geom: { shape: "scalebar", at, segmentLength: lastLength, segments: lastSegments }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -96,7 +97,7 @@ export const scalebarCommand: Command = { return [s, { draft: null }]; } if (input.kind !== "point") return [s, { draft: null }]; - return [idle()[0], { draft: null, done: true, commit: (p) => appendScalebar(p, input.point, ctx) }]; + return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendScalebar(input.point, ctx)) }]; }, onMove: (state, point): [CommandState, CommandResult] => [state, { draft: pointDraft(point) }], diff --git a/src/commands/cmds/spline.ts b/src/commands/cmds/spline.ts index 0e9d1cfc..3b957061 100644 --- a/src/commands/cmds/spline.ts +++ b/src/commands/cmds/spline.ts @@ -25,10 +25,11 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const CLOSE_HIT = 0.08; // Modell-Meter: Klick nahe Startpunkt schließt den Zug @@ -80,7 +81,7 @@ function splineDraft(points: Vec2[], cursor: Vec2 | null, closed: boolean, mode: return draft; } -function appendSpline(p: Project, pts: Vec2[], closed: boolean, mode: CurveMode, ctx: CommandContext): Project { +function appendSpline(pts: Vec2[], closed: boolean, mode: CurveMode, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -88,7 +89,7 @@ function appendSpline(p: Project, pts: Vec2[], closed: boolean, mode: CurveMode, categoryCode: ctx.defaultCategoryCode, geom: { shape: "spline", pts, closed, mode }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (closed = false, curveMode: CurveMode = "fit"): [CommandState, CommandResult] => [ @@ -143,7 +144,7 @@ export const splineCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle, - { draft: null, done: true, commit: (p) => appendSpline(p, pts, true, s.curveMode, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendSpline(pts, true, s.curveMode, ctx)) }, ]; } return [s, { draft: splineDraft(s.points, s.cursor, s.closed, s.curveMode) }]; @@ -168,7 +169,7 @@ export const splineCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle, - { draft: null, done: true, commit: (p) => appendSpline(p, pts, true, s.curveMode, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendSpline(pts, true, s.curveMode, ctx)) }, ]; } const points = [...s.points, pt]; @@ -197,7 +198,7 @@ export const splineCommand: Command = { const close = s.closed && pts.length >= 3; return [ { phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle, - { draft: null, done: true, commit: (p) => appendSpline(p, pts, close, s.curveMode, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendSpline(pts, close, s.curveMode, ctx)) }, ]; } return idle(s.closed, s.curveMode); diff --git a/src/commands/cmds/stair.ts b/src/commands/cmds/stair.ts index 32a0a1a6..8c55f336 100644 --- a/src/commands/cmds/stair.ts +++ b/src/commands/cmds/stair.ts @@ -30,10 +30,11 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; /** Default-Ebene (Kategorie) für Treppen: „40" Treppen (Fallback: aktive). */ const STAIR_CATEGORY = "40"; @@ -241,7 +242,7 @@ function runDraft(s: StairRun, ctx: CommandContext): ToolDraft { } /** Hängt eine Treppe ans Projekt (immutabel) und aktualisiert die Defaults. */ -function appendStair(p: Project, s: StairRun, ctx: CommandContext): Project { +function appendStair(s: StairRun, ctx: CommandContext): CoreOp[] { const stair = buildStair(s, ctx); // Zuletzt genutzte Einstellungen für die nächste Treppe merken. stairDefaults.shape = s.shape; @@ -252,8 +253,7 @@ function appendStair(p: Project, s: StairRun, ctx: CommandContext): Project { stairDefaults.auftritt = s.auftritt; stairDefaults.steps = s.steps; stairDefaults.rise = s.rise; - const stairs = p.stairs ? [...p.stairs, stair] : [stair]; - return { ...p, stairs }; + return addItems("stairs", [stair]); } const idle = (from?: StairCmdState): [CommandState, CommandResult] => [ @@ -348,7 +348,7 @@ export const stairCommand: Command = { const ns: StairRun = { ...s, cursor: pt }; return [ idle(s)[0], - { draft: null, done: true, commit: (p) => appendStair(p, ns, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendStair(ns, ctx)) }, ]; }, @@ -365,7 +365,7 @@ export const stairCommand: Command = { const ns = s; return [ idle(s)[0], - { draft: null, done: true, commit: (p) => appendStair(p, ns, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendStair(ns, ctx)) }, ]; } return idle(s); diff --git a/src/commands/cmds/text.ts b/src/commands/cmds/text.ts index 65027aff..ec306206 100644 --- a/src/commands/cmds/text.ts +++ b/src/commands/cmds/text.ts @@ -10,7 +10,9 @@ import type { Drawing2D } from "../../model/types"; import { uniqueId } from "../../tools/types"; -import type { Command, CommandContext, CommandResult, CommandState, Project, Vec2 } from "../types"; +import type { Command, CommandContext, CommandResult, CommandState, Vec2 } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; /** Default-Schrifthöhe eines frei platzierten Texts in Modell-Metern. */ const DEFAULT_TEXT_HEIGHT_M = 0.25; @@ -20,7 +22,7 @@ interface TextIdle extends CommandState { } type TextState = TextIdle; -function appendEmptyText(p: Project, id: string, at: Vec2, ctx: CommandContext): Project { +function appendEmptyText(id: string, at: Vec2, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id, type: "drawing2d", @@ -28,7 +30,7 @@ function appendEmptyText(p: Project, id: string, at: Vec2, ctx: CommandContext): categoryCode: ctx.defaultCategoryCode, geom: { shape: "text", at, text: "", height: DEFAULT_TEXT_HEIGHT_M, angle: 0 }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -54,7 +56,7 @@ export const textCommand: Command = { { draft: null, done: true, - commit: (p) => appendEmptyText(p, id, at, ctx), + commit: opsMutation(() => appendEmptyText(id, at, ctx)), focusDrawingId: id, }, ]; diff --git a/src/commands/cmds/textbox.ts b/src/commands/cmds/textbox.ts index 804b87bd..38cc66e3 100644 --- a/src/commands/cmds/textbox.ts +++ b/src/commands/cmds/textbox.ts @@ -27,9 +27,10 @@ import type { CommandResult, CommandState, DraftShape, - Project, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; /** Default-Schrifthöhe einer Textspalte in Modell-Metern (= Baseline-Versatz vom Rahmen-Top). */ const DEFAULT_TEXT_HEIGHT_M = 0.25; @@ -84,7 +85,7 @@ function frameDraft(a: Vec2, cursor: Vec2): { preview: DraftShape[]; vertices: V }; } -function appendEmptyTextbox(p: Project, id: string, at: Vec2, width: number, ctx: CommandContext): Project { +function appendEmptyTextbox(id: string, at: Vec2, width: number, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id, type: "drawing2d", @@ -92,7 +93,7 @@ function appendEmptyTextbox(p: Project, id: string, at: Vec2, width: number, ctx categoryCode: ctx.defaultCategoryCode, geom: { shape: "text", at, text: "", height: DEFAULT_TEXT_HEIGHT_M, angle: 0, width }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -123,7 +124,7 @@ export const textboxCommand: Command = { { draft: null, done: true, - commit: (p) => appendEmptyTextbox(p, id, at, width, ctx), + commit: opsMutation(() => appendEmptyTextbox(id, at, width, ctx)), focusDrawingId: id, focusMinHeightM: heightM, }, diff --git a/src/commands/cmds/textpath.ts b/src/commands/cmds/textpath.ts index 0b1b2079..00b8bd9c 100644 --- a/src/commands/cmds/textpath.ts +++ b/src/commands/cmds/textpath.ts @@ -15,10 +15,11 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -59,7 +60,7 @@ function pathDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { return draft; } -function appendEmptyTextPath(p: Project, id: string, pts: Vec2[], ctx: CommandContext): Project { +function appendEmptyTextPath(id: string, pts: Vec2[], ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id, type: "drawing2d", @@ -67,7 +68,7 @@ function appendEmptyTextPath(p: Project, id: string, pts: Vec2[], ctx: CommandCo categoryCode: ctx.defaultCategoryCode, geom: { shape: "text", at: pts[0], text: "", height: DEFAULT_TEXT_HEIGHT_M, angle: 0, pathPts: pts }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -77,7 +78,7 @@ const idle = (): [CommandState, CommandResult] => [ function commitPath(pts: Vec2[], ctx: CommandContext): CommandResult { const id = uniqueId("dr2d"); - return { draft: null, done: true, commit: (p) => appendEmptyTextPath(p, id, pts, ctx), focusDrawingId: id }; + return { draft: null, done: true, commit: opsMutation(() => appendEmptyTextPath(id, pts, ctx)), focusDrawingId: id }; } export const textpathCommand: Command = { diff --git a/src/commands/cmds/wall.ts b/src/commands/cmds/wall.ts index c904fc44..6ee35578 100644 --- a/src/commands/cmds/wall.ts +++ b/src/commands/cmds/wall.ts @@ -31,6 +31,8 @@ import type { ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -109,7 +111,7 @@ function wallTypeForThickness( p: Project, base: WallType, thickness: number, -): { project: Project; wallTypeId: string } { +): { ops: CoreOp[]; wallTypeId: string } { const componentId = base.layers[0].componentId; const near = (a: number, b: number) => Math.abs(a - b) < 1e-4; const existing = p.wallTypes.find( @@ -118,13 +120,13 @@ function wallTypeForThickness( t.layers[0].componentId === componentId && near(t.layers[0].thickness, thickness), ); - if (existing) return { project: p, wallTypeId: existing.id }; + if (existing) return { ops: [], wallTypeId: existing.id }; const nt: WallType = { id: uniqueId("WT"), name: `${base.name} ${(thickness * 100).toFixed(0)} cm`, layers: [{ componentId, thickness }], }; - return { project: { ...p, wallTypes: [...p.wallTypes, nt] }, wallTypeId: nt.id }; + return { ops: addItems("wallTypes", [nt]), wallTypeId: nt.id }; } interface WallIdle extends CommandState { @@ -179,12 +181,12 @@ function appendWalls( pts: Vec2[], ctx: CommandContext, thickOverride: number | null, -): Project { +): CoreOp[] { const height = ctx.level.floorHeight && ctx.level.floorHeight > 0 ? ctx.level.floorHeight : DEFAULT_HEIGHT; // Dicke-Übersteuerung (nur einschichtig): passenden Wandtyp finden/erzeugen, // damit Plan/3D — die die Dicke aus dem Wandtyp lesen — korrekt darstellen. - let project = p; + let typeOps: CoreOp[] = []; let wallTypeId = activeWallTypeId(ctx); const base = activeWallType(ctx); if ( @@ -194,8 +196,8 @@ function appendWalls( thickOverride >= MIN_THICKNESS && Math.abs(thickOverride - wallTypeThickness(base)) > 1e-4 ) { - const r = wallTypeForThickness(project, base, thickOverride); - project = r.project; + const r = wallTypeForThickness(p, base, thickOverride); + typeOps = r.ops; wallTypeId = r.wallTypeId; } const newWalls: Wall[] = []; @@ -214,8 +216,8 @@ function appendWalls( height, }); } - if (newWalls.length === 0) return p; - return { ...project, walls: [...project.walls, ...newWalls] }; + if (newWalls.length === 0) return []; + return [...typeOps, ...addItems("walls", newWalls)]; } const idle = ( @@ -299,7 +301,7 @@ export const wallCommand: Command = { const to = s.thickOverride; return [ { phase: "start", lastPoint: null, thickOverride: to, single: s.single } as WallIdle, - { draft: null, done: true, commit: (p) => appendWalls(p, pts, ctx, to) }, + { draft: null, done: true, commit: opsMutation((p) => appendWalls(p, pts, ctx, to)) }, ]; } return idle(s.thickOverride, s.single); diff --git a/src/commands/cmds/wipeout.ts b/src/commands/cmds/wipeout.ts index d6d0d73f..2450767c 100644 --- a/src/commands/cmds/wipeout.ts +++ b/src/commands/cmds/wipeout.ts @@ -29,10 +29,11 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const CLOSE_HIT = 0.15; // Modell-Meter: Klick nahe Startpunkt schliesst den Zug @@ -59,7 +60,7 @@ function wipeoutDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { return draft; } -function appendWipeout(p: Project, points: Vec2[], ctx: CommandContext): Project { +function appendWipeout(points: Vec2[], ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -69,7 +70,7 @@ function appendWipeout(p: Project, points: Vec2[], ctx: CommandContext): Project background: MASK_COLOR, color: MASK_COLOR, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -100,7 +101,7 @@ export const wipeoutCommand: Command = { // Klick nahe Startpunkt (≥3 Punkte) → schliessen (committet). if (s.points.length >= 3 && segLen(s.points[0], pt) < CLOSE_HIT) { const pts = s.points; - return [idle()[0], { draft: null, done: true, commit: (p) => appendWipeout(p, pts, ctx) }]; + return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendWipeout(pts, ctx)) }]; } const points = [...s.points, pt]; const ns: WipeoutDrawing = { phase: "next", points, cursor: pt, lastPoint: pt }; @@ -120,7 +121,7 @@ export const wipeoutCommand: Command = { const s = state as WipeoutState; if (s.phase === "next" && s.points.length >= 3) { const pts = s.points; - return [idle()[0], { draft: null, done: true, commit: (p) => appendWipeout(p, pts, ctx) }]; + return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendWipeout(pts, ctx)) }]; } return idle(); }, diff --git a/src/commands/cmds/xline.ts b/src/commands/cmds/xline.ts index 3f415185..cb5d1d13 100644 --- a/src/commands/cmds/xline.ts +++ b/src/commands/cmds/xline.ts @@ -14,10 +14,11 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -66,7 +67,7 @@ function xlineDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { return draft; } -function appendXline(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project { +function appendXline(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -74,7 +75,7 @@ function appendXline(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project categoryCode: ctx.defaultCategoryCode, geom: { shape: "xline", a, b }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } export const xlineCommand: Command = { @@ -99,7 +100,7 @@ export const xlineCommand: Command = { const a = s.a; return [ { phase: "start", lastPoint: null }, - { draft: null, done: true, commit: (p) => appendXline(p, a, pt, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendXline(a, pt, ctx)) }, ]; }, diff --git a/src/state/applyChange.perf.test.ts b/src/state/applyChange.perf.test.ts new file mode 100644 index 00000000..09990769 --- /dev/null +++ b/src/state/applyChange.perf.test.ts @@ -0,0 +1,57 @@ +// [K4] S3 Messung: typische Hochfrequenz-Aktionen auf einem grossen Projekt (3000 Wände) über den +// Store — Griff ziehen (100 Schritte, ein Undo-Schritt), Auswahl verschieben (300 Wände, 20-mal), +// Eigenschaft tippen (100 Zeichen, ein Undo-Schritt). Werte gehen nach stderr (TODO [K4]); die +// Grenzen sind grosszügig (Container unter Last), geprüft wird vor allem das Ergebnis. +import { describe, expect, it } from "vitest"; +import { getState } from "./appStore"; +import { sampleProject } from "../model/sampleProject"; +import type { Project, Wall } from "../model/types"; + +const st = () => getState(); + +function bigProject(n: number): Project { + const base = sampleProject.walls; + const walls: Wall[] = Array.from({ length: n }, (_, i) => ({ + ...base[i % base.length], + id: `w${i}`, + start: { x: i, y: 0 }, + end: { x: i + 1, y: 0 }, + })); + return { ...structuredClone(sampleProject), walls }; +} + +describe("Messung Store-Aktionen, 3000 Wände", () => { + it("Griff ziehen, Auswahl verschieben, Eigenschaft tippen", () => { + st().setProject(bigProject(3000)); + st().clearHistory(); + const depth0 = st().undoDepth; + + // Griff ziehen: 100 Mausschritte, ein Undo-Schritt. + let t = performance.now(); + for (let i = 0; i < 100; i++) st().moveGripOf(null, "w1500", 0, { x: 1500 + i * 0.01, y: 0.5 }); + const gripMs = (performance.now() - t) / 100; + expect(st().project.walls[1500].start).toEqual({ x: 1500 + 99 * 0.01, y: 0.5 }); + expect(st().undoDepth).toBe(depth0 + 1); + + // Auswahl verschieben: 300 Wände, 20 Verschiebungen. + const ids = Array.from({ length: 300 }, (_, i) => `w${i * 10}`); + t = performance.now(); + for (let i = 0; i < 20; i++) { + st().commitTransformOn({ wallIds: ids, drawingId: null }, "move", [{ x: 0, y: 0 }, { x: 0, y: 0.1 }], "move", 1); + } + const moveMs = (performance.now() - t) / 20; + expect(st().project.walls[10].start.y).toBeCloseTo(2, 9); + expect(st().project.walls[11].start.y).toBe(0); + + // Eigenschaft tippen: 100 Tastenschritte mit coalesceKey. + t = performance.now(); + for (let i = 0; i < 100; i++) st().updateWall("w42", { height: 2.5 + i / 1000 }, "typing:w42"); + const typeMs = (performance.now() - t) / 100; + expect(st().project.walls[42].height).toBeCloseTo(2.599, 9); + + process.stderr.write( + `3000 Wände (Store): Griff ziehen ${gripMs.toFixed(2)} ms/Schritt, Auswahl verschieben (300) ${moveMs.toFixed(2)} ms, Eigenschaft tippen ${typeMs.toFixed(2)} ms\n`, + ); + expect(gripMs + moveMs + typeMs).toBeLessThan(200); + }); +}); diff --git a/src/state/applyChange.test.ts b/src/state/applyChange.test.ts new file mode 100644 index 00000000..c7e00ac5 --- /dev/null +++ b/src/state/applyChange.test.ts @@ -0,0 +1,177 @@ +// [K4] S3 zweite Etappe: Store-Aktionen erzeugen Ops direkt (`applyChange`, `opsMutation`) statt +// Projekt → Projekt + `diffToOps`. Geprüft: Ops gehen unverändert an den Kern (Verlauf, Prüfung), +// Leseansicht und Kern-Dokument bleiben gleich — auch über Zufallsfolgen der umgestellten +// Aktionen mit Undo bis zum Anfang und Redo bis zum Ende. +import { beforeEach, describe, expect, it } from "vitest"; +import { getState, setState } from "./appStore"; +import { storeDocument } from "./historySlice"; +import { sampleProject } from "../model/sampleProject"; +import type { Drawing2D, Project, Vec2 } from "../model/types"; +import { applyOps } from "../core/ops"; +import { opsMutation, patchItem, removeItems } from "../core/opsBuild"; + +const st = () => getState(); + +function rng(seed: number) { + let x = seed >>> 0; + return () => ((x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296); +} + +function drawings(r: () => number): Drawing2D[] { + const v = (): Vec2 => ({ x: Math.round(r() * 100) / 10, y: Math.round(r() * 100) / 10 }); + const base = { type: "drawing2d" as const, levelId: "eg", categoryCode: "20" }; + const geoms = [ + { shape: "line", a: v(), b: v() }, + { shape: "polyline", pts: [v(), v(), v(), v()], closed: true, bulge: [0, 0.3, 0, 0] }, + { shape: "polyline", pts: [v(), v(), v(), v()], closed: false }, + { shape: "rect", min: { x: 0, y: 0 }, max: { x: 2, y: 1 } }, + { shape: "circle", center: v(), r: 1.5 }, + { shape: "arc", center: v(), r: 1, a0: 0.2, a1: 2 }, + { shape: "text", at: v(), text: "A", height: 0.3, angle: 0 }, + { shape: "dimension", pts: [v(), v(), v()], offset: 0.5 }, + ] as Drawing2D["geom"][]; + return geoms.map((geom, i) => ({ ...base, id: `d${i}`, geom }) as Drawing2D); +} + +/** Kern-Dokument == TS-Leseansicht (JSON). */ +function expectMirror(): void { + const p = st().project; + expect(JSON.parse(storeDocument(p).json())).toEqual(JSON.parse(JSON.stringify(p))); +} + +beforeEach(() => { + st().setProject(structuredClone(sampleProject)); + st().clearHistory(); +}); + +describe("applyChange", () => { + it("Ops gehen ohne Differenz an den Kern: ein Undo-Schritt, Protokoll = genau diese Ops", () => { + const before = st().project; + const w = before.walls[0]; + const ops = patchItem(before, "walls", w.id, { height: 3.3 }); + st().applyChange(ops); + expect(st().project.walls[0].height).toBe(3.3); + // Unveränderte Elemente und Listen behalten ihre Identität. + expect(st().project.walls[1]).toBe(before.walls[1]); + expect(st().project.drawingLevels).toBe(before.drawingLevels); + expect(st().recentOps().at(-1)).toEqual(ops); + expect(st().undoDepth).toBe(1); + st().undo(); + expect(st().project.walls[0].height).toBe(w.height); + expectMirror(); + }); + + it("leere Ops: kein Schritt; NaN: abgelehnt, Projekt unverändert", () => { + const before = st().project; + st().applyChange([]); + st().applyChange((p) => patchItem(p, "walls", "gibt-es-nicht", { height: 1 })); + expect(st().project).toBe(before); + expect(st().undoDepth).toBe(0); + st().applyChange((p) => patchItem(p, "walls", p.walls[0].id, { height: NaN })); + expect(st().project).toBe(before); + expect(st().undoDepth).toBe(0); + }); + + it("coalesceKey: Serie = ein Schritt; setProject(opsMutation) nimmt die Ops direkt", () => { + const id = st().project.walls[0].id; + for (let i = 0; i < 50; i++) st().applyChange((p) => patchItem(p, "walls", id, { height: 2 + i / 100 }), "drag"); + expect(st().undoDepth).toBe(1); + const m = opsMutation((p) => removeItems(p, "walls", [id])); + st().setProject(m); + expect(st().recentOps().at(-1)).toEqual([{ kind: "remove", collection: "walls", ids: [id] }]); + expect(st().undoDepth).toBe(2); + st().undo(); + st().undo(); + expect(st().project.walls[0].height).toBe(sampleProject.walls[0].height); + expectMirror(); + }); + + it("groupChanges: mehrere Aktionen = ein Undo-Schritt", () => { + const p0 = st().project; + st().groupChanges(() => { + st().patchLevel(p0.drawingLevels[0].id, { linePoints: undefined, name: "X" }); + st().setProject(opsMutation((p) => removeItems(p, "walls", [p.walls[0].id, p.walls[1].id]))); + }); + expect(st().undoDepth).toBe(1); + st().undo(); + expect(st().project).toEqual(p0); + }); +}); + +describe("groupChanges mit Schlüssel", () => { + it("Griff-Zug mit mitgeführten Ecken: alle Mausschritte = ein Undo-Schritt", () => { + const p0 = st().project; + const [a, b] = p0.walls; + for (let i = 0; i < 30; i++) { + st().groupChanges(() => { + st().moveElementByOf(null, a.id, { x: 0.01, y: 0 }); + st().moveGripOf(null, b.id, 0, { x: b.start.x + (i + 1) * 0.01, y: b.start.y }); + }, `bodyDrag::${a.id}`); + } + expect(st().undoDepth).toBe(1); + st().undo(); + expect(st().project).toEqual(p0); + expectMirror(); + }); +}); + +describe("Zufallsfolgen der umgestellten Aktionen", () => { + it("Leseansicht = Kern, jede Aktion = applyOps(vorher, ihre Ops), Undo/Redo exakt", () => { + for (let seed = 1; seed <= 12; seed++) { + const r = rng(seed); + const start: Project = { ...structuredClone(sampleProject), drawings2d: drawings(r) }; + setState({ project: start }); + st().clearHistory(); + const v = (): Vec2 => ({ x: r() * 10, y: r() * 10 }); + let committed = 0; + for (let k = 0; k < 60; k++) { + const s = st(); + const p = s.project; + const wid = p.walls[Math.floor(r() * p.walls.length)]?.id ?? "x"; + const did = p.drawings2d[Math.floor(r() * p.drawings2d.length)]?.id ?? "x"; + const lid = p.drawingLevels[Math.floor(r() * p.drawingLevels.length)]?.id ?? "x"; + const cid = p.ceilings?.[0]?.id ?? "x"; + const rmid = p.rooms?.[0]?.id ?? "x"; + const idx = Math.floor(r() * 4); + const n = Math.floor(r() * 14); + const depth = s.undoDepth; + try { + switch (n) { + case 0: s.moveGripOf(null, wid, idx % 2, v()); break; + case 1: s.moveGripOf(did, null, idx % 2, v()); break; + case 2: s.moveElementByOf(did, null, v()); break; + case 3: s.moveEdgeOf(null, wid, 0, 1, v()); break; + case 4: s.updateWall(wid, { height: 2 + r() }); break; + case 5: s.setElementColor("drawing2d", did, "#abcdef"); break; + case 6: s.commitTransformOn({ wallIds: [wid], drawingId: did }, idx % 2 ? "move" : "rotate", [v(), v(), v()], idx < 2 ? "move" : "copy", 1); break; + case 7: s.moveCeilingBy(cid, v()); break; + case 8: s.moveRoomGrip(rmid, idx, v()); break; + case 9: s.toggleLevelVisible(lid); break; + case 10: s.patchLevel(lid, { floorHeight: 2.5 + r() }); break; + case 11: s.setWallThickness(wid, 0.1 + r() * 0.3); break; + case 12: s.resizeElement("drawing2d", did, 1 + r(), 1 + r(), { fx: 0, fy: 0 }); break; + case 13: s.setProject(opsMutation((q) => removeItems(q, "drawings2d", [did]))); break; + } + } catch { + continue; // ungültige Griff-Indizes (z. B. Kante einer kurzen Polylinie) — wie bisher + } + if (st().project !== p) { + committed++; + // Ein Schritt mehr — oder gleich viele, wenn dieselbe Griff-Serie verschmolzen wurde. + expect(st().undoDepth - depth).toBeGreaterThanOrEqual(0); + expect(st().undoDepth - depth).toBeLessThanOrEqual(1); + expect(st().project).toEqual(applyOps(p, st().recentOps().at(-1)!)); + } + } + expect(committed).toBeGreaterThan(30); + expectMirror(); + const end = JSON.stringify(st().project); + while (st().canUndo) st().undo(); + expect(JSON.stringify(st().project)).toBe(JSON.stringify(start)); + expectMirror(); + while (st().canRedo) st().redo(); + expect(JSON.stringify(st().project)).toBe(end); + expectMirror(); + } + }); +}); diff --git a/src/state/groupActions.test.ts b/src/state/groupActions.test.ts index 9ebb631f..41292723 100644 --- a/src/state/groupActions.test.ts +++ b/src/state/groupActions.test.ts @@ -7,6 +7,7 @@ import { describe, it, expect } from "vitest"; import { + activeGroupOps, addNewElementsToActiveGroup, applyGroupDimming, applyGroupDimmingToPlan, @@ -21,6 +22,9 @@ import { import type { Primitive } from "../plan/generatePlan/shared"; import { materializeUnderlay, type Plan } from "../plan/generatePlan"; import type { Drawing2D, Group, Project } from "../model/types"; +import { applyOps } from "../core/ops"; +import type { CoreOp } from "../core/ops"; +import { addItems, replaceItem } from "../core/opsBuild"; const EMPTY_MEM = { wallIds: [] as string[], @@ -261,6 +265,31 @@ describe("addNewElementsToActiveGroup", () => { }); }); +describe("activeGroupOps ([K4] S3: Ops statt Differenz)", () => { + const mk = (id: string): Group => ({ id, wallIds: ["w1"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: [] }); + const line = (id: string) => + ({ id, type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } } }) as Project["drawings2d"][number]; + const wall = (id: string) => ({ id, start: { x: 0, y: 0 }, end: { x: 1, y: 0 } }) as unknown as Project["walls"][number]; + + it("gleiches Ergebnis wie addNewElementsToActiveGroup, Zufall", () => { + let x = 11; + const r = () => ((x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296); + for (let n = 0; n < 200; n++) { + const before: Project = { ...project([mk("g1"), mk("g2")]), drawings2d: [line("d0")], walls: [wall("w0")] }; + const ops: CoreOp[] = []; + const k = Math.floor(r() * 4); + if (k >= 1) ops.push(...addItems("drawings2d", [line(`a${n}`), line(`b${n}`)], r() < 0.5 ? 0 : undefined)); + if (k >= 2) ops.push(...addItems("walls", [wall(`w${n}x`)])); + if (k >= 3) ops.push(replaceItem("drawings2d", { ...line("d0"), color: "#f00" })); + const path = r() < 0.2 ? [] : r() < 0.5 ? ["g1"] : ["g2", "g1", "gx"]; + const after = applyOps(before, ops); + const legacy = addNewElementsToActiveGroup(before, after, path); + const viaOps = applyOps(before, [...ops, ...activeGroupOps(before, ops, path)]); + expect(viaOps).toEqual(legacy); + } + }); +}); + describe("ungroup", () => { it("löst genau EIN Level auf; Untergruppen bleiben als eigene Gruppen bestehen", () => { const inner: Group = { id: "g1", wallIds: ["w1"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: [] }; diff --git a/src/state/groupActions.ts b/src/state/groupActions.ts index 978c9502..e7591800 100644 --- a/src/state/groupActions.ts +++ b/src/state/groupActions.ts @@ -9,6 +9,10 @@ import type { Drawing2D, Group, Project } from "../model/types"; import type { Plan, UnderlayGroup } from "../core"; import { uniqueId } from "../tools/types"; import type { Primitive } from "../core"; +import { applyOps } from "../core"; +import type { CoreOp } from "../core"; +import { itemsOf, patchItem } from "../core"; +import type { EntityCollection } from "../core"; /** Mitglieds-IDs je Elementart — dieselbe Form wie `Group`, ohne `id`/`name`/`groupIds`. */ export interface GroupMembership { @@ -292,6 +296,56 @@ export function addNewElementsToActiveGroup( }; } +/** Liste je Mitgliedsart. */ +const COLLECTION_OF: Record = { + wallIds: "walls", + drawingIds: "drawings2d", + ceilingIds: "ceilings", + roomIds: "rooms", + stairIds: "stairs", + columnIds: "columns", + roofIds: "roofs", + openingIds: "openings", +}; + +/** + * Wie {@link addNewElementsToActiveGroup}, für eine Änderung als Ops ([K4] S3): die zusätzlichen + * Ops, die die neu eingefügten Elemente (`add`-Ops) der aktiven Gruppe zuschlagen — ohne Differenz + * über alle Listen. Leer ohne aktive Gruppe oder ohne neue Elemente. + */ +export function activeGroupOps(before: Project, ops: readonly CoreOp[], groupPath: string[]): CoreOp[] { + if (groupPath.length === 0) return []; + const addedIds = new Set(); + const touched = new Set(); + for (const op of ops) { + if (op.kind !== "add") continue; + touched.add(op.collection); + for (const e of op.items) addedIds.add(e.id); + } + if (addedIds.size === 0) return []; + const after = applyOps(before, ops); + const activeId = groupPath[groupPath.length - 1]; + const g = (after.groups ?? []).find((x) => x.id === activeId); + if (!g) return []; + const added = { ...EMPTY_MEMBERSHIP }; + for (const k of KEYS) { + const coll = COLLECTION_OF[k]; + if (!touched.has(coll)) continue; + // Reihenfolge wie in der Liste (wie `newIds`); vorher vorhandene ids sind nie neu. + const existed = new Set(); + for (const e of itemsOf(before, coll)) { + const id = (e as { id: string }).id; + if (addedIds.has(id)) existed.add(id); + } + added[k] = itemsOf(after, coll) + .map((e) => (e as { id: string }).id) + .filter((id) => addedIds.has(id) && !existed.has(id)); + } + if (KEYS.every((k) => added[k].length === 0)) return []; + const merged: Group = { ...g, ...mergeMembership(g, added) }; + return patchItem(after, "groups", activeId, () => merged); +} + /** * Erzeugt eine neue Gruppe aus einer Mengen-Auswahl (+ optional bereits * gewählte Gruppen, die dabei als Untergruppen verschachtelt werden — „zwei diff --git a/src/state/projectSlice.ts b/src/state/projectSlice.ts index 6e5e940d..f48066b2 100644 --- a/src/state/projectSlice.ts +++ b/src/state/projectSlice.ts @@ -10,6 +10,15 @@ import { diffToOps } from "../core/ops"; import type { CoreOp } from "../core/ops"; +import { + addItems, + fieldOps, + isOpsMutation, + patchItem, + patchItems, + removeItems, + setField, +} from "../core"; import { withVertexType, type PolylineVertexType } from "../core"; import { sampleProject } from "../model/sampleProject"; import { @@ -37,7 +46,7 @@ import { PEN_FALLBACK_WEIGHT, } from "../model/penSets"; import { lineIntersect } from "../model/geometry"; -import { commitTransform } from "../tools/transform"; +import { transformOps } from "../tools/transform"; import type { CopyMode, TransformOp, TransformSelection } from "../tools/transform"; import { uniqueId } from "../tools/types"; import { centroid as roomCentroid } from "../core"; @@ -71,6 +80,12 @@ export interface ProjectSlice { * Implementierung unten. */ setProject: (next: Project | ((p: Project) => Project), coalesceKey?: string) => void; + /** + * Änderung direkt als Ops ([K4] S3): `ops` oder ein Op-Bauer auf dem aktuellen Projekt + * (`core/opsBuild.ts`). Geht ohne `diffToOps` an den Kern (Prüfung, Verlauf); sonst wie + * {@link setProject} (gleicher `coalesceKey` im Zeitfenster = ein Undo-Schritt). + */ + applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[]), coalesceKey?: string) => void; /** Die zuletzt angewendeten Ops (JSON-serialisierbar), jüngste zuletzt. */ recentOps: () => CoreOp[][]; @@ -447,17 +462,41 @@ export function createProjectSlice( const history = createHistorySlice(api as unknown as StoreApi); + // Kern-Commit einer Op-Folge auf `s.project` (Prüfung, Verlauf, Leseansicht nachführen). + // Verstösse werden zurückgerollt und gemeldet. + const commitOps = ( + s: { project: Project }, + ops: readonly CoreOp[], + coalesceKey: string | undefined, + ): Partial => { + if (ops.length === 0) return {}; + const doc = storeDocument(s.project); + const res = doc.commit(s.project, ops, coalesceKey, Date.now()); + if ("problems" in res) { + const problems = res.problems; + console.warn("Projektänderung verworfen:", problems); + queueMicrotask(() => get().notify(`${t("project.change.rejected")} ${problems[0]}`, "error")); + return {}; + } + opLog.push(ops.slice()); + if (opLog.length > OP_LOG_LIMIT) opLog.shift(); + return { project: res.project, ...historyPatch(doc) }; + }; + // Bequemer immutabler Projekt-Updater (wie setProject in App). Zweiter, // optionaler Parameter `coalesceKey`: NUR von den paar bekannten - // Hochfrequenz-Aktionen (Grip-Drag & Co., s. u.) gesetzt — alle anderen ~50 - // Aktionen in dieser Datei rufen `setProject(fn)` ohne Key auf und pushen - // damit IMMER diskret (kein Koaleszieren zwischen unterschiedlichen - // Aktionen möglich, auch nicht bei zufällig identischem Timing in Tests). + // Hochfrequenz-Aktionen (Grip-Drag & Co., s. u.) gesetzt — alle anderen + // Aktionen rufen ohne Key auf und pushen damit IMMER diskret (kein + // Koaleszieren zwischen unterschiedlichen Aktionen möglich, auch nicht bei + // zufällig identischem Timing in Tests). + // [K4] S3: Projekt → Projekt-Funktionen gehen über `diffToOps` (Adapter für die Aktionen, die noch + // nicht umgestellt sind); Funktionen aus `opsMutation` tragen ihre Ops mit und sparen die Differenz. const setProject = ( next: Project | ((p: Project) => Project), coalesceKey?: string, ) => set((s) => { + if (isOpsMutation(next)) return commitOps(s, next.toOps(s.project), coalesceKey); const wanted = typeof next === "function" ? (next as (p: Project) => Project)(s.project) : next; // No-Op-Schutz: echte Immutable-Updates liefern bei tatsächlicher @@ -467,22 +506,16 @@ export function createProjectSlice( if (wanted === s.project) return {}; // Das Projekt ändert sich NUR über Ops (core/ops.ts): die gewünschte Änderung wird in // eine Op-Folge übersetzt; der Kern prüft (NaN, doppelte ids), wendet an und zeichnet den - // Undo-Schritt auf. Verstösse werden zurückgerollt und gemeldet. - const ops = diffToOps(s.project, wanted); - if (ops.length === 0) return {}; - const doc = storeDocument(s.project); - const res = doc.commit(s.project, ops, coalesceKey, Date.now()); - if ("problems" in res) { - const problems = res.problems; - console.warn("Projektänderung verworfen:", problems); - queueMicrotask(() => get().notify(`${t("project.change.rejected")} ${problems[0]}`, "error")); - return {}; - } - opLog.push(ops); - if (opLog.length > OP_LOG_LIMIT) opLog.shift(); - return { project: res.project, ...historyPatch(doc) }; + // Undo-Schritt auf. + return commitOps(s, diffToOps(s.project, wanted), coalesceKey); }); + // Änderung direkt als Ops (ohne Differenz), s. `ProjectSlice.applyChange`. + const applyChange = ( + ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[]), + coalesceKey?: string, + ) => set((s) => commitOps(s, typeof ops === "function" ? ops(s.project) : ops, coalesceKey)); + return { ...history, @@ -493,31 +526,28 @@ export function createProjectSlice( project: sampleProject, setProject, + applyChange, recentOps: () => opLog.slice(), // ── Zeichnungsebenen ─────────────────────────────────────────────────── toggleLevelVisible: (id) => - setProject((p) => ({ - ...p, - drawingLevels: p.drawingLevels.map((z) => - z.id === id ? { ...z, visible: !z.visible } : z, - ), - })), + applyChange((p) => patchItem(p, "drawingLevels", id, (z) => ({ ...z, visible: !z.visible }))), patchActiveFloor: (patch) => { const activeLevelId = get().activeLevelId; - setProject((p) => ({ - ...p, - drawingLevels: recomputeFloorElevations( - p.drawingLevels.map((z) => - z.id === activeLevelId ? { ...z, ...patch } : z, + applyChange((p) => + fieldOps( + p, + "drawingLevels", + recomputeFloorElevations( + p.drawingLevels.map((z) => (z.id === activeLevelId ? { ...z, ...patch } : z)), ), ), - })); + ); }, addFloor: () => - setProject((p) => { + applyChange((p) => { const n = p.drawingLevels.filter((z) => z.kind === "floor").length + 1; const floor: DrawingLevel = { id: `floor-${Date.now()}`, @@ -528,14 +558,11 @@ export function createProjectSlice( floorHeight: 2.6, cutHeight: 1.0, }; - return { - ...p, - drawingLevels: recomputeFloorElevations([...p.drawingLevels, floor]), - }; + return fieldOps(p, "drawingLevels", recomputeFloorElevations([...p.drawingLevels, floor])); }), addDrawing: () => - setProject((p) => { + applyChange((p) => { const n = p.drawingLevels.filter((z) => z.kind === "drawing").length + 1; const drawing: DrawingLevel = { id: `drawing-${Date.now()}`, @@ -544,13 +571,13 @@ export function createProjectSlice( visible: true, locked: false, }; - return { ...p, drawingLevels: [...p.drawingLevels, drawing] }; + return addItems("drawingLevels", [drawing]); }), // Schnitt/Ansicht sind vorerst Platzhalter ohne Schnittlinie (linePoints // bleibt undefined, bis die Schnitt-UI existiert — siehe toSection.ts). addSection: () => - setProject((p) => { + applyChange((p) => { const n = p.drawingLevels.filter((z) => z.kind === "section").length + 1; const section: DrawingLevel = { id: `section-${Date.now()}`, @@ -559,11 +586,11 @@ export function createProjectSlice( visible: true, locked: false, }; - return { ...p, drawingLevels: [...p.drawingLevels, section] }; + return addItems("drawingLevels", [section]); }), addElevation: () => - setProject((p) => { + applyChange((p) => { const n = p.drawingLevels.filter((z) => z.kind === "elevation").length + 1; const elevation: DrawingLevel = { id: `elevation-${Date.now()}`, @@ -572,7 +599,7 @@ export function createProjectSlice( visible: true, locked: false, }; - return { ...p, drawingLevels: [...p.drawingLevels, elevation] }; + return addItems("drawingLevels", [elevation]); }), // Neue freie Zeichnungsebene mit explizitem Namen anlegen und ihre ID @@ -580,7 +607,7 @@ export function createProjectSlice( // (Dialog); leere Eingabe fällt auf den Default-Namen zurück. addDrawingLevel: (name) => { const id = `drawing-${Date.now()}`; - setProject((p) => { + applyChange((p) => { const n = p.drawingLevels.filter((z) => z.kind === "drawing").length + 1; const drawing: DrawingLevel = { id, @@ -589,30 +616,26 @@ export function createProjectSlice( visible: true, locked: false, }; - return { ...p, drawingLevels: [...p.drawingLevels, drawing] }; + return addItems("drawingLevels", [drawing]); }); return id; }, - importDrawings: (drawings) => - setProject((p) => - drawings.length - ? { ...p, drawings2d: [...p.drawings2d, ...drawings] } - : p, - ), + importDrawings: (drawings) => applyChange(addItems("drawings2d", drawings)), patchLevel: (id, patch) => - setProject((p) => ({ - ...p, - drawingLevels: recomputeFloorElevations( - p.drawingLevels.map((z) => (z.id === id ? { ...z, ...patch } : z)), + applyChange((p) => + fieldOps( + p, + "drawingLevels", + recomputeFloorElevations(p.drawingLevels.map((z) => (z.id === id ? { ...z, ...patch } : z))), ), - })), + ), duplicateLevel: (id) => - setProject((p) => { + applyChange((p) => { const i = p.drawingLevels.findIndex((z) => z.id === id); - if (i < 0) return p; + if (i < 0) return []; const src = p.drawingLevels[i]; const clone: DrawingLevel = { ...src, @@ -621,7 +644,7 @@ export function createProjectSlice( }; const next = [...p.drawingLevels]; next.splice(i + 1, 0, clone); - return { ...p, drawingLevels: recomputeFloorElevations(next) }; + return fieldOps(p, "drawingLevels", recomputeFloorElevations(next)); }), // Zeichnungsebene löschen (≥1 behalten). War es das aktive Geschoss, auf @@ -634,35 +657,27 @@ export function createProjectSlice( const fallback = project.drawingLevels.find((z) => z.id !== id); if (fallback) set({ activeLevelId: fallback.id }); } - setProject((p) => { + applyChange((p) => { const removedWallIds = new Set( p.walls.filter((w) => w.floorId === id).map((w) => w.id), ); - return { - ...p, - drawingLevels: recomputeFloorElevations( - p.drawingLevels.filter((z) => z.id !== id), - ), - walls: p.walls.filter((w) => w.floorId !== id), - ceilings: (p.ceilings ?? []).filter((c) => c.floorId !== id), - stairs: (p.stairs ?? []).filter((s) => s.floorId !== id), - rooms: (p.rooms ?? []).filter((r) => r.floorId !== id), - openings: (p.openings ?? []).filter( - (o) => !removedWallIds.has(o.hostWallId), - ), - }; + return [ + ...fieldOps(p, "drawingLevels", recomputeFloorElevations(p.drawingLevels.filter((z) => z.id !== id))), + ...removeItems(p, "walls", removedWallIds), + ...removeItems(p, "ceilings", (c) => c.floorId === id), + ...removeItems(p, "stairs", (s) => s.floorId === id), + ...removeItems(p, "rooms", (r) => r.floorId === id), + ...removeItems(p, "openings", (o) => removedWallIds.has(o.hostWallId)), + ]; }); }, // ── Ebenen (Kategorien) ──────────────────────────────────────────────── toggleCategoryVisible: (code) => - setProject((p) => ({ - ...p, - layers: toggleCategoryByCode(p.layers, code), - })), + applyChange((p) => fieldOps(p, "layers", toggleCategoryByCode(p.layers, code))), addCategory: () => - setProject((p) => { + applyChange((p) => { const code = nextFreeCode(p.layers); const category: LayerCategory = { code, @@ -672,17 +687,14 @@ export function createProjectSlice( visible: true, locked: false, }; - return { ...p, layers: [...p.layers, category] }; + return [setField("layers", [...p.layers, category])]; }), patchCategory: (code, patch) => - setProject((p) => ({ - ...p, - layers: patchCategoryByCode(p.layers, code, patch), - })), + applyChange((p) => fieldOps(p, "layers", patchCategoryByCode(p.layers, code, patch))), addSubCategory: (parentCode) => - setProject((p) => { + applyChange((p) => { const code = nextFreeCode(p.layers); const child: LayerCategory = { code, @@ -692,27 +704,27 @@ export function createProjectSlice( visible: true, locked: false, }; - return { ...p, layers: addChildByCode(p.layers, parentCode, child) }; + return fieldOps(p, "layers", addChildByCode(p.layers, parentCode, child)); }), duplicateCategory: (code) => - setProject((p) => { + applyChange((p) => { const src = findCategory(p.layers, code); - if (!src) return p; + if (!src) return []; const clone: LayerCategory = { ...src, code: nextFreeCode(p.layers), name: t("default.copySuffixLayer", { name: src.name }), children: undefined, }; - return { ...p, layers: insertAfterCode(p.layers, code, clone) }; + return fieldOps(p, "layers", insertAfterCode(p.layers, code, clone)); }), deleteCategory: (code) => - setProject((p) => { - if (flattenCategories(p.layers).length <= 1) return p; // letzte behalten + applyChange((p) => { + if (flattenCategories(p.layers).length <= 1) return []; // letzte behalten const src = findCategory(p.layers, code); - if (!src) return p; + if (!src) return []; const codes = new Set(flattenCategories([src]).map((c) => c.code)); const usedByWall = p.walls.some((w) => codes.has(w.categoryCode)); const usedByOpening = (p.openings ?? []).some((o) => @@ -720,18 +732,13 @@ export function createProjectSlice( ); if (usedByWall || usedByOpening) { get().notify(t("alert.layerInUse", { code: src.code, name: src.name }), "warning"); - return p; + return []; } - return { ...p, layers: removeByCode(p.layers, code) }; + return fieldOps(p, "layers", removeByCode(p.layers, code)); }), assignWallCategory: (wallId, code) => - setProject((p) => ({ - ...p, - walls: p.walls.map((w) => - w.id === wallId ? { ...w, categoryCode: code } : w, - ), - })), + applyChange((p) => patchItem(p, "walls", wallId, { categoryCode: code })), // ── Sichtbarkeits-Kombinationen ──────────────────────────────────────── snapshotLayerVisibility: () => { @@ -743,10 +750,7 @@ export function createProjectSlice( }, applyLayerVisibility: (codes) => - setProject((p) => ({ - ...p, - layers: applyVisibilityByCode(p.layers, codes), - })), + applyChange((p) => fieldOps(p, "layers", applyVisibilityByCode(p.layers, codes))), snapshotDrawingVisibility: () => { const out: Record = {}; @@ -755,12 +759,9 @@ export function createProjectSlice( }, applyDrawingVisibility: (ids) => - setProject((p) => ({ - ...p, - drawingLevels: p.drawingLevels.map((z) => - z.id in ids ? { ...z, visible: ids[z.id] } : z, - ), - })), + applyChange((p) => + patchItems(p, "drawingLevels", (z) => z.id in ids, (z) => ({ ...z, visible: ids[z.id] })), + ), // ── Ressourcen ───────────────────────────────────────────────────────── patchComponent: (id, patch) => @@ -1100,10 +1101,9 @@ export function createProjectSlice( })), insertDrawingPoint: (drawingId, segIndex, pt) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => { - if (d.id !== drawingId || d.geom.shape !== "polyline") return d; + applyChange((p) => + patchItem(p, "drawings2d", drawingId, (d) => { + if (d.geom.shape !== "polyline") return d; const g = d.geom; const n = g.pts.length; const last = segIndex === n - 1; @@ -1128,44 +1128,36 @@ export function createProjectSlice( : undefined; return { ...d, geom: { ...g, pts, ...(nextBulge ? { bulge: nextBulge } : {}) } }; }), - })), + ), setPolylineVertexType: (drawingId, index, type) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => { - if (d.id !== drawingId || d.geom.shape !== "polyline" || d.locked) return d; + applyChange((p) => + patchItem(p, "drawings2d", drawingId, (d) => { + if (d.geom.shape !== "polyline" || d.locked) return d; const g = d.geom; const bulge = withVertexType(g, index, type); const { bulge: _old, ...rest } = g; return { ...d, geom: bulge.some((b) => b !== 0) ? { ...rest, bulge } : rest }; }), - })), + ), deleteDrawingPoint: (drawingId, index) => - setProject((p) => { + applyChange((p) => { const d = p.drawings2d.find((x) => x.id === drawingId); - if (!d || d.geom.shape !== "polyline") return p; + if (!d || d.geom.shape !== "polyline") return []; const g = d.geom; const min = g.closed ? 4 : 3; if (g.pts.length < min) { get().notify(t("alert.polylineMinPoints"), "warning"); - return p; + return []; } - if (index < 0 || index >= g.pts.length) return p; + if (index < 0 || index >= g.pts.length) return []; const pts = g.pts.filter((_, i) => i !== index); // Zwei Segmente werden zu einem: der Bulge des ENTFERNTEN Segments // fällt weg, das verbleibende behält seinen Wert (die exakte // Bogenform lässt sich nicht erhalten, wenn ihr Stützpunkt entfällt). const bulge = g.bulge ? g.bulge.filter((_, i) => i !== index) : undefined; - return { - ...p, - drawings2d: p.drawings2d.map((x) => - x.id === drawingId - ? { ...x, geom: { ...g, pts, ...(bulge ? { bulge } : {}) } } - : x, - ), - }; + return patchItem(p, "drawings2d", drawingId, (x) => ({ ...x, geom: { ...g, pts, ...(bulge ? { bulge } : {}) } })); }), // ── Editier-Griffe ───────────────────────────────────────────────────── @@ -1173,129 +1165,91 @@ export function createProjectSlice( // (kein Draft/Commit-Muster wie bei den Zeichenwerkzeugen) — daher mit // coalesceKey, damit EIN Drag EINEN Undo-Schritt erzeugt statt vieler. moveGripOf: (drawingId, wallId, index, pt, scaleDenominator) => - setProject( + applyChange( (p) => moveGrip(p, drawingId, wallId, index, pt, scaleDenominator), `moveGripOf:${drawingId ?? ""}:${wallId ?? ""}:${index}`, ), moveElementByOf: (drawingId, wallId, delta) => - setProject( + applyChange( (p) => moveElementBy(p, drawingId, wallId, delta), `moveElementByOf:${drawingId ?? ""}:${wallId ?? ""}`, ), moveEdgeOf: (drawingId, wallId, aIndex, bIndex, delta) => - setProject( + applyChange( (p) => moveEdge(p, drawingId, wallId, aIndex, bIndex, delta), `moveEdgeOf:${drawingId ?? ""}:${wallId ?? ""}:${aIndex}:${bIndex}`, ), // ── Selektions-Attribute ─────────────────────────────────────────────── setElementColor: (kind, id, color) => - setProject((p) => { - if (kind === "drawing2d") { - return { - ...p, - drawings2d: p.drawings2d.map((d) => - d.id === id ? { ...d, color } : d, - ), - }; - } - return { - ...p, - walls: p.walls.map((w) => (w.id === id ? { ...w, color } : w)), - }; - }), + applyChange((p) => + kind === "drawing2d" ? patchItem(p, "drawings2d", id, { color }) : patchItem(p, "walls", id, { color }), + ), // Strichstärke gibt es als direktes Feld NUR auf Drawing2D; bei unbekannter // ID bleibt das Projekt unverändert (No-op). - setElementWeight: (id, weightMm) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => - d.id === id ? { ...d, weightMm } : d, - ), - })), + setElementWeight: (id, weightMm) => applyChange((p) => patchItem(p, "drawings2d", id, { weightMm })), // Füllschraffur NUR für Drawing2D; `null` entfernt die Schraffur (Feld weg). setElementFill: (id, hatchId) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => { - if (d.id !== id) return d; + applyChange((p) => + patchItem(p, "drawings2d", id, (d) => { if (hatchId === null) { const { hatchId: _omit, ...rest } = d; return rest; } return { ...d, hatchId }; }), - })), + ), // Vollton-Füllfarbe NUR für Drawing2D; `null` entfernt das Feld. setElementFillColor: (id, fillColor) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => { - if (d.id !== id) return d; + applyChange((p) => + patchItem(p, "drawings2d", id, (d) => { if (fillColor === null) { const { fillColor: _omit, ...rest } = d; return rest; } return { ...d, fillColor }; }), - })), + ), // Vordergrund-/Hintergrund-Override (Wand/Decke/Drawing2D); `null` löscht // das Feld (→ „Nach System", erbt wieder vom Bauteil/System). setElementForeground: (kind, id, value) => - setProject((p) => setOverrideField(p, kind, id, "foreground", value)), + applyChange((p) => setOverrideField(p, kind, id, "foreground", value)), setElementBackground: (kind, id, value) => - setProject((p) => setOverrideField(p, kind, id, "background", value)), + applyChange((p) => setOverrideField(p, kind, id, "background", value)), - updateDrawing2D: (id, patch) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => (d.id === id ? { ...d, ...patch } : d)), - })), + updateDrawing2D: (id, patch) => applyChange((p) => patchItem(p, "drawings2d", id, patch)), reorderDrawings: (ids, op) => - setProject((p) => ({ - ...p, - drawings2d: reorderDrawings2D(p.drawings2d, ids, op), - })), + applyChange((p) => fieldOps(p, "drawings2d", reorderDrawings2D(p.drawings2d, ids, op))), reorderDrawingLevels: (ids, op) => - setProject((p) => ({ - ...p, - drawingLevels: reorderDrawingLevelsArr(p.drawingLevels, ids, op), - })), + applyChange((p) => fieldOps(p, "drawingLevels", reorderDrawingLevelsArr(p.drawingLevels, ids, op))), // ── Größe (Resize um Anker) ──────────────────────────────────────────── resizeElement: (kind, id, w, h, anchor) => - setProject((p) => resizeElement(p, kind, id, w, h, anchor)), + applyChange((p) => resizeElement(p, kind, id, w, h, anchor)), // ── Transformation ───────────────────────────────────────────────────── commitTransformOn: (sel, op, points, copyMode, count) => - setProject((p) => commitTransform(p, sel, op, points, copyMode, count)), + applyChange((p) => transformOps(p, sel, op, points, copyMode, count)), // ── Wand-Attribute ───────────────────────────────────────────────────── - updateWall: (id, patch, coalesceKey) => - setProject( - (p) => ({ - ...p, - walls: p.walls.map((w) => (w.id === id ? { ...w, ...patch } : w)), - }), - coalesceKey, - ), + updateWall: (id, patch, coalesceKey) => applyChange((p) => patchItem(p, "walls", id, patch), coalesceKey), setWallThickness: (wallId, thickness) => - setProject((p) => setWallThickness(p, wallId, thickness)), + applyChange((p) => setWallThickness(p, wallId, thickness)), // ── Decken-Editieren ────────────────────────────────────────────────── // (coalesceKey: siehe Kommentar bei moveGripOf — auch hier läuft die // Mutation bei jedem Maus-Move-Schritt eines Drags.) moveCeilingGrip: (ceilingId, index, pt) => - setProject( + applyChange( (p) => mapCeiling(p, ceilingId, (c) => ({ ...c, outline: c.outline.map((v, i) => (i === index ? pt : v)), @@ -1304,7 +1258,7 @@ export function createProjectSlice( ), moveCeilingBy: (ceilingId, delta) => - setProject( + applyChange( (p) => mapCeiling(p, ceilingId, (c) => ({ ...c, outline: c.outline.map((v) => ({ x: v.x + delta.x, y: v.y + delta.y })), @@ -1313,7 +1267,7 @@ export function createProjectSlice( ), moveCeilingEdge: (ceilingId, aIndex, bIndex, delta) => - setProject( + applyChange( (p) => mapCeiling(p, ceilingId, (c) => ({ ...c, outline: movePolygonEdge(c.outline, aIndex, bIndex, delta, true), @@ -1322,37 +1276,25 @@ export function createProjectSlice( ), updateCeiling: (id, patch) => - setProject((p) => mapCeiling(p, id, (c) => ({ ...c, ...patch }))), + applyChange((p) => mapCeiling(p, id, (c) => ({ ...c, ...patch }))), setCeilingThickness: (ceilingId, thickness) => - setProject((p) => setCeilingThickness(p, ceilingId, thickness)), + applyChange((p) => setCeilingThickness(p, ceilingId, thickness)), // ── Öffnungs-Editieren ──────────────────────────────────────────────── - updateOpening: (id, patch) => - setProject((p) => ({ - ...p, - openings: (p.openings ?? []).map((o) => (o.id === id ? { ...o, ...patch } : o)), - })), + updateOpening: (id, patch) => applyChange((p) => patchItem(p, "openings", id, patch)), // ── Dach-Editieren ───────────────────────────────────────────────────── - updateRoof: (id, patch, coalesceKey) => - setProject( - (p) => ({ - ...p, - roofs: (p.roofs ?? []).map((r) => (r.id === id ? { ...r, ...patch } : r)), - }), - coalesceKey, - ), + updateRoof: (id, patch, coalesceKey) => applyChange((p) => patchItem(p, "roofs", id, patch), coalesceKey), // Dach-Eckgriff (3D): der gezogene Umriss-Eckpunkt `index` wandert auf `pt`; // die GEGENÜBERLIEGENDE Ecke bleibt fix → der Umriss bleibt ein achsparalleles // Rechteck (die Dach-Geometrie rechnet ohnehin auf der Bounding-Box). moveRoofGrip: (roofId, index, pt) => - setProject( - (p) => ({ - ...p, - roofs: (p.roofs ?? []).map((r) => { - if (r.id !== roofId || r.outline.length < 4) return r; + applyChange( + (p) => + patchItem(p, "roofs", roofId, (r) => { + if (r.outline.length < 4) return r; const opp = r.outline[(index + 2) % r.outline.length]; const x0 = Math.min(pt.x, opp.x); const x1 = Math.max(pt.x, opp.x); @@ -1368,28 +1310,24 @@ export function createProjectSlice( ], }; }), - }), `moveRoofGrip:${roofId}`, ), // Dach als Ganzes verschieben (Verschiebe-Griff). moveRoofBy: (roofId, delta) => - setProject( - (p) => ({ - ...p, - roofs: (p.roofs ?? []).map((r) => - r.id === roofId - ? { ...r, outline: r.outline.map((v) => ({ x: v.x + delta.x, y: v.y + delta.y })) } - : r, - ), - }), + applyChange( + (p) => + patchItem(p, "roofs", roofId, (r) => ({ + ...r, + outline: r.outline.map((v) => ({ x: v.x + delta.x, y: v.y + delta.y })), + })), `moveRoofBy:${roofId}`, ), // ── Treppen-Editieren ────────────────────────────────────────────────── // (coalesceKey: siehe Kommentar bei moveGripOf.) moveStairBy: (stairId, delta) => - setProject( + applyChange( (p) => mapStair(p, stairId, (s) => ({ ...s, @@ -1402,12 +1340,12 @@ export function createProjectSlice( ), updateStair: (id, patch) => - setProject((p) => mapStair(p, id, (s) => ({ ...s, ...patch }))), + applyChange((p) => mapStair(p, id, (s) => ({ ...s, ...patch }))), // ── Raum-Editieren ────────────────────────────────────────────────────── // (coalesceKey: siehe Kommentar bei moveGripOf.) moveRoomBy: (roomId, delta) => - setProject( + applyChange( (p) => mapRoom(p, roomId, (r) => ({ ...r, @@ -1425,7 +1363,7 @@ export function createProjectSlice( ), moveRoomGrip: (roomId, index, pt) => - setProject( + applyChange( (p) => mapRoom(p, roomId, (r) => ({ ...r, @@ -1435,7 +1373,7 @@ export function createProjectSlice( ), moveRoomEdge: (roomId, aIndex, bIndex, delta) => - setProject( + applyChange( (p) => mapRoom(p, roomId, (r) => ({ ...r, @@ -1445,10 +1383,10 @@ export function createProjectSlice( ), updateRoom: (id, patch) => - setProject((p) => mapRoom(p, id, (r) => ({ ...r, ...patch }))), + applyChange((p) => mapRoom(p, id, (r) => ({ ...r, ...patch }))), moveRoomStamp: (roomId, delta) => - setProject((p) => + applyChange((p) => mapRoom(p, roomId, (r) => { const base = r.stampAnchor ?? roomCentroid(r.boundary); return { @@ -1459,13 +1397,13 @@ export function createProjectSlice( ), setRoomStampAnchor: (roomId, anchor) => - setProject((p) => mapRoom(p, roomId, (r) => ({ ...r, stampAnchor: anchor }))), + applyChange((p) => mapRoom(p, roomId, (r) => ({ ...r, stampAnchor: anchor }))), setRoomStampDoc: (roomId, doc) => - setProject((p) => mapRoom(p, roomId, (r) => ({ ...r, stampDoc: doc }))), + applyChange((p) => mapRoom(p, roomId, (r) => ({ ...r, stampDoc: doc }))), setRoomStamp: (roomId, stamp) => - setProject((p) => mapRoom(p, roomId, (r) => ({ ...r, stamp }))), + applyChange((p) => mapRoom(p, roomId, (r) => ({ ...r, stamp }))), }; } @@ -1474,12 +1412,8 @@ function mapRoom( project: Project, roomId: string, fn: (r: import("../model/types").Room) => import("../model/types").Room, -): Project { - const rooms = project.rooms ?? []; - return { - ...project, - rooms: rooms.map((r) => (r.id === roomId ? fn(r) : r)), - }; +): CoreOp[] { + return patchItem(project, "rooms", roomId, fn); } /** Immutabler Map über eine Treppe (per ID); No-op ohne Treffer. */ @@ -1487,12 +1421,8 @@ function mapStair( project: Project, stairId: string, fn: (s: import("../model/types").Stair) => import("../model/types").Stair, -): Project { - const stairs = project.stairs ?? []; - return { - ...project, - stairs: stairs.map((s) => (s.id === stairId ? fn(s) : s)), - }; +): CoreOp[] { + return patchItem(project, "stairs", stairId, fn); } /** Immutabler Map über eine Decke (per ID); No-op ohne Treffer. */ @@ -1507,19 +1437,17 @@ function setOverrideField( id: string, field: "foreground" | "background", value: string | null, -): Project { +): CoreOp[] { const apply = (item: T): T => { - if (item.id !== id) return item; if (value === null) { const { [field]: _omit, ...rest } = item as Record; return rest as unknown as T; } return { ...item, [field]: value }; }; - if (kind === "wall") return { ...project, walls: project.walls.map(apply) }; - if (kind === "ceiling") - return { ...project, ceilings: (project.ceilings ?? []).map(apply) }; - return { ...project, drawings2d: project.drawings2d.map(apply) }; + if (kind === "wall") return patchItem(project, "walls", id, apply); + if (kind === "ceiling") return patchItem(project, "ceilings", id, apply); + return patchItem(project, "drawings2d", id, apply); } /** @@ -1609,12 +1537,8 @@ function mapCeiling( project: Project, ceilingId: string, fn: (c: import("../model/types").Ceiling) => import("../model/types").Ceiling, -): Project { - const ceilings = project.ceilings ?? []; - return { - ...project, - ceilings: ceilings.map((c) => (c.id === ceilingId ? fn(c) : c)), - }; +): CoreOp[] { + return patchItem(project, "ceilings", ceilingId, fn); } /** @@ -1627,12 +1551,12 @@ function setWallThickness( project: Project, wallId: string, thickness: number, -): Project { - if (!isFinite(thickness) || thickness <= 0) return project; +): CoreOp[] { + if (!isFinite(thickness) || thickness <= 0) return []; const wall = project.walls.find((w) => w.id === wallId); - if (!wall) return project; + if (!wall) return []; const wt = project.wallTypes.find((t) => t.id === wall.wallTypeId); - if (!wt || wt.layers.length === 0) return project; + if (!wt || wt.layers.length === 0) return []; const single = wt.layers.length === 1; const usedByOthers = project.walls.some( @@ -1641,14 +1565,7 @@ function setWallThickness( if (single && !usedByOthers) { // Direkt die Schichtdicke des (exklusiven, einschichtigen) Wandtyps setzen. - return { - ...project, - wallTypes: project.wallTypes.map((t) => - t.id === wt.id - ? { ...t, layers: [{ ...t.layers[0], thickness }] } - : t, - ), - }; + return patchItem(project, "wallTypes", wt.id, (t) => ({ ...t, layers: [{ ...t.layers[0], thickness }] })); } // Dedizierten einschichtigen Wandtyp erzeugen (erste Schicht klonen) und der @@ -1659,13 +1576,7 @@ function setWallThickness( name: t("default.wallTypeSingle", { thickness: thickness.toFixed(2) }), layers: [{ ...wt.layers[0], thickness }], }; - return { - ...project, - wallTypes: [...project.wallTypes, clone], - walls: project.walls.map((w) => - w.id === wallId ? { ...w, wallTypeId: id } : w, - ), - }; + return [...addItems("wallTypes", [clone]), ...patchItem(project, "walls", wallId, { wallTypeId: id })]; } /** @@ -1681,15 +1592,15 @@ function setCeilingThickness( project: Project, ceilingId: string, thickness: number, -): Project { - if (!isFinite(thickness) || thickness <= 0) return project; +): CoreOp[] { + if (!isFinite(thickness) || thickness <= 0) return []; const ceiling = (project.ceilings ?? []).find((c) => c.id === ceilingId); - if (!ceiling) return project; + if (!ceiling) return []; const activeId = ceiling.ceilingTypeId ?? ceiling.wallTypeId; const ct = (project.ceilingTypes ?? []).find((t) => t.id === ceiling.ceilingTypeId) ?? project.wallTypes.find((t) => t.id === ceiling.wallTypeId); - if (!ct || ct.layers.length === 0) return project; + if (!ct || ct.layers.length === 0) return []; const single = ct.layers.length === 1; const usedByOthers = (project.ceilings ?? []).some( @@ -1698,12 +1609,7 @@ function setCeilingThickness( if (single && !usedByOthers && ceiling.ceilingTypeId) { // Direkt die Schichtdicke des (exklusiven, einschichtigen) Deckentyps setzen. - return { - ...project, - ceilingTypes: (project.ceilingTypes ?? []).map((t) => - t.id === ct.id ? { ...t, layers: [{ ...t.layers[0], thickness }] } : t, - ), - }; + return patchItem(project, "ceilingTypes", ct.id, (t) => ({ ...t, layers: [{ ...t.layers[0], thickness }] })); } // Dedizierten einschichtigen Deckentyp erzeugen (erste Schicht klonen) und @@ -1714,13 +1620,10 @@ function setCeilingThickness( name: t("default.ceilingTypeSingle", { thickness: thickness.toFixed(2) }), layers: [{ ...ct.layers[0], thickness }], }; - return { - ...project, - ceilingTypes: [...(project.ceilingTypes ?? []), clone], - ceilings: (project.ceilings ?? []).map((c) => - c.id === ceilingId ? { ...c, ceilingTypeId: id, thickness: undefined } : c, - ), - }; + return [ + ...addItems("ceilingTypes", [clone]), + ...patchItem(project, "ceilings", ceilingId, (c) => ({ ...c, ceilingTypeId: id, thickness: undefined })), + ]; } // ── Resize (Skalierung auf Zielmaß um einen Anker) ─────────────────────────── @@ -1738,28 +1641,19 @@ function resizeElement( w: number, h: number, anchor: { fx: number; fy: number }, -): Project { +): CoreOp[] { if (kind === "drawing2d") { - return { - ...project, - drawings2d: project.drawings2d.map((d) => - d.id === id ? { ...d, geom: resizeGeom(d.geom, w, h, anchor) } : d, - ), - }; + return patchItem(project, "drawings2d", id, (d) => ({ ...d, geom: resizeGeom(d.geom, w, h, anchor) })); } - return { - ...project, - walls: project.walls.map((wall) => { - if (wall.id !== id) return wall; + return patchItem(project, "walls", id, (wall) => { const box = bbox2([wall.start, wall.end]); const { ax, ay, sx, sy } = scaleAround(box, w, h, anchor); const apply = (p: Vec2): Vec2 => ({ x: ax + (p.x - ax) * sx, y: ay + (p.y - ay) * sy, }); - return { ...wall, start: apply(wall.start), end: apply(wall.end) }; - }), - }; + return { ...wall, start: apply(wall.start), end: apply(wall.end) }; + }); } /** bbox einer Punktliste. */ @@ -2107,16 +2001,13 @@ function moveGrip( pt: Vec2, /** Papier-Massstab (1:N) — nur für den Masszahl-Griff, s. `drawingVertices`. */ scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR, -): Project { +): CoreOp[] { // Objekt-Sperre: gesperrte Elemente lassen sich anwählen, aber nicht // ziehen (s. Kommentar bei `onPlanSelect` in useMouseSelectionHandlers.ts). - if (drawingId && project.drawings2d.find((d) => d.id === drawingId)?.locked) return project; - if (wallId && project.walls.find((w) => w.id === wallId)?.locked) return project; + if (drawingId && project.drawings2d.find((d) => d.id === drawingId)?.locked) return []; + if (wallId && project.walls.find((w) => w.id === wallId)?.locked) return []; if (drawingId) { - return { - ...project, - drawings2d: project.drawings2d.map((d) => { - if (d.id !== drawingId) return d; + return patchItem(project, "drawings2d", drawingId, (d) => { const g = d.geom; if (g.shape === "line" || g.shape === "xline" || g.shape === "ray") { return { ...d, geom: index === 0 ? { ...g, a: pt } : { ...g, b: pt } }; @@ -2283,18 +2174,12 @@ function moveGrip( return { ...d, geom: { ...g, rx, ry } }; } return d; - }), - }; + }); } if (wallId) { - return { - ...project, - walls: project.walls.map((w) => - w.id === wallId ? { ...w, ...(index === 0 ? { start: pt } : { end: pt }) } : w, - ), - }; + return patchItem(project, "walls", wallId, (w) => ({ ...w, ...(index === 0 ? { start: pt } : { end: pt }) })); } - return project; + return []; } /** Verschiebt das selektierte Element (2D-Element ODER Wand) um `delta` (parallel). */ @@ -2303,16 +2188,13 @@ function moveElementBy( drawingId: string | null, wallId: string | null, delta: Vec2, -): Project { +): CoreOp[] { // Objekt-Sperre: s. Kommentar in `moveGrip` oben. - if (drawingId && project.drawings2d.find((d) => d.id === drawingId)?.locked) return project; - if (wallId && project.walls.find((w) => w.id === wallId)?.locked) return project; + if (drawingId && project.drawings2d.find((d) => d.id === drawingId)?.locked) return []; + if (wallId && project.walls.find((w) => w.id === wallId)?.locked) return []; const mv = (p: Vec2): Vec2 => ({ x: p.x + delta.x, y: p.y + delta.y }); if (drawingId) { - return { - ...project, - drawings2d: project.drawings2d.map((d) => { - if (d.id !== drawingId) return d; + return patchItem(project, "drawings2d", drawingId, (d) => { const g = d.geom; switch (g.shape) { case "line": @@ -2343,18 +2225,12 @@ function moveElementBy( default: return d; } - }), - }; + }); } if (wallId) { - return { - ...project, - walls: project.walls.map((w) => - w.id === wallId ? { ...w, start: mv(w.start), end: mv(w.end) } : w, - ), - }; + return patchItem(project, "walls", wallId, (w) => ({ ...w, start: mv(w.start), end: mv(w.end) })); } - return project; + return []; } /** @@ -2458,16 +2334,13 @@ function moveEdge( aIndex: number, bIndex: number, delta: Vec2, -): Project { +): CoreOp[] { // Objekt-Sperre: s. Kommentar in `moveGrip` oben. - if (drawingId && project.drawings2d.find((d) => d.id === drawingId)?.locked) return project; - if (wallId && project.walls.find((w) => w.id === wallId)?.locked) return project; + if (drawingId && project.drawings2d.find((d) => d.id === drawingId)?.locked) return []; + if (wallId && project.walls.find((w) => w.id === wallId)?.locked) return []; const mv = (p: Vec2): Vec2 => ({ x: p.x + delta.x, y: p.y + delta.y }); if (drawingId) { - return { - ...project, - drawings2d: project.drawings2d.map((d) => { - if (d.id !== drawingId) return d; + return patchItem(project, "drawings2d", drawingId, (d) => { const g = d.geom; if (g.shape === "line") { // Linie hat nur eine Kante [0,1] → das ganze Segment verschieben. @@ -2497,19 +2370,13 @@ function moveEdge( return { ...d, geom: { ...g, min: { x: minX, y: minY }, max: { x: maxX, y: maxY } } }; } return d; - }), - }; + }); } if (wallId) { // Wand: beide Enden gemeinsam → ganze Wand senkrecht verschieben. - return { - ...project, - walls: project.walls.map((w) => - w.id === wallId ? { ...w, start: mv(w.start), end: mv(w.end) } : w, - ), - }; + return patchItem(project, "walls", wallId, (w) => ({ ...w, start: mv(w.start), end: mv(w.end) })); } - return project; + return []; } // ── Immutable Tree-Helfer (verschoben aus App.tsx, 1:1) ────────────────────── diff --git a/src/state/useGripEditing.ts b/src/state/useGripEditing.ts index 5be6940b..1c200bd2 100644 --- a/src/state/useGripEditing.ts +++ b/src/state/useGripEditing.ts @@ -92,6 +92,11 @@ export function useGripEditing(opts: { moveRoomBy: (id: string, delta: Vec2) => void; moveCeilingBy: (id: string, delta: Vec2) => void; moveElementByOf: (drawingId: string | null, wallId: string | null, delta: Vec2) => void; + /** + * Fasst mehrere Änderungen zu EINEM Undo-Schritt zusammen ([K4] S3, Store `groupChanges`); mit + * Schlüssel schliessen die Mausschritte desselben Zugs an denselben Schritt an. + */ + groupChanges?: (fn: () => void, coalesceKey?: string) => void; }) { const { project, @@ -129,6 +134,7 @@ export function useGripEditing(opts: { moveCeilingBy, moveElementByOf, } = opts; + const groupChanges = opts.groupChanges ?? ((fn: () => void) => fn()); // Bewegpunkt (Move-Handle) einer Treppe: liegt auf der Treppe (Mitte des // ersten Laufs bei gerade/L, Zentrum bei Wendel) und verschiebt beim Ziehen @@ -1000,7 +1006,8 @@ export function useGripEditing(opts: { }; /** Ausstehenden Zug jetzt in das Projekt schreiben (EINE Mutation). */ - const commitPendingGrip = () => { + const commitPendingGrip = () => groupChanges(commitPendingGripChanges); + const commitPendingGripChanges = () => { const ph = pendingSheetHeightRef.current; pendingSheetHeightRef.current = null; if (ph) { @@ -1053,7 +1060,8 @@ export function useGripEditing(opts: { }; /** Aufgeschobenes Körper-Verschieben jetzt ins Projekt schreiben. */ - const commitPendingBody = () => { + const commitPendingBody = () => groupChanges(commitPendingBodyChanges); + const commitPendingBodyChanges = () => { const pwm = pendingWallMoveRef.current; pendingWallMoveRef.current = null; sheetDuRef.current = null; @@ -1436,16 +1444,21 @@ export function useGripEditing(opts: { setDraft({ preview: bodyPreviewShapes(), vertices: [], snap: null }); return; } - moveElementByOf(moveDrawingId, moveWallId, delta); // Beim ersten Move-Event die Koinzidenz-Gruppe einmalig bestimmen (Snapshot // VOR der ersten Mutation der Siblings). Danach inkrementell mitführen. if (moveCoincidentRef.current === null) { moveCoincidentRef.current = findMoveCoincident2D(moveDrawingId, moveWallId); } - for (const c of moveCoincidentRef.current) { - c.pos = { x: c.pos.x + delta.x, y: c.pos.y + delta.y }; - moveGripOf(c.drawingId, c.wallId, c.index, c.pos, scaleDenominator); - } + const coincident = moveCoincidentRef.current; + // Element + mitgeführte Ecken: je Mausschritt eine Gruppe, die Schritte desselben Zugs + // schliessen an denselben Undo-Schritt an. + groupChanges(() => { + moveElementByOf(moveDrawingId, moveWallId, delta); + for (const c of coincident) { + c.pos = { x: c.pos.x + delta.x, y: c.pos.y + delta.y }; + moveGripOf(c.drawingId, c.wallId, c.index, c.pos, scaleDenominator); + } + }, `bodyDrag:${moveDrawingId ?? ""}:${moveWallId ?? ""}`); }, // Kanten-Griff ziehen. Zwei Verhalten (Zielpunkt jeweils ABSOLUT relativ // zum ORIGINALEN Anker `edge.mid`, angewandt über applyEdgeToward — s. dort): diff --git a/src/state/useMouseSelectionHandlers.ts b/src/state/useMouseSelectionHandlers.ts index 3536d068..093e651f 100644 --- a/src/state/useMouseSelectionHandlers.ts +++ b/src/state/useMouseSelectionHandlers.ts @@ -5,6 +5,7 @@ // // Extrahiert aus App.tsx. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). +import { opsMutation, patchItem, removeItems } from "../core"; import type { Project, Vec2 } from "../model/types"; import type { CategoryDisplayResolver } from "../core"; import type { DisplayResolver } from "../viewport/Viewport3D"; @@ -168,14 +169,11 @@ export function useMouseSelectionHandlers(opts: { const id = editTextId; if (!id) return; setProject( - (p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => - d.id === id && d.geom.shape === "text" - ? { ...d, geom: { ...d.geom, doc, text: plainText(doc) } } - : d, + opsMutation((p) => + patchItem(p, "drawings2d", id, (d) => + d.geom.shape === "text" ? { ...d, geom: { ...d.geom, doc, text: plainText(doc) } } : d, ), - }), + ), `commitTextEdit:${id}`, ); }; @@ -186,15 +184,14 @@ export function useMouseSelectionHandlers(opts: { const closeTextEdit = () => { const id = editTextId; if (id) { - setProject((p) => { - const d = p.drawings2d.find((x) => x.id === id); - // `text` ist immer der Reintext-Spiegel von `doc` (s. commitTextEdit) — - // reicht daher allein als Leer-Test, egal ob `doc` je gesetzt wurde. - if (d && d.geom.shape === "text" && d.geom.text.trim() === "") { - return { ...p, drawings2d: p.drawings2d.filter((x) => x.id !== id) }; - } - return p; - }); + setProject( + opsMutation((p) => { + const d = p.drawings2d.find((x) => x.id === id); + // `text` ist immer der Reintext-Spiegel von `doc` (s. commitTextEdit) — + // reicht daher allein als Leer-Test, egal ob `doc` je gesetzt wurde. + return d && d.geom.shape === "text" && d.geom.text.trim() === "" ? removeItems(p, "drawings2d", [id]) : []; + }), + ); } setEditTextId(null); setEditTextMinHeightM(null); diff --git a/src/state/usePanelHostBase.ts b/src/state/usePanelHostBase.ts index c134ac5c..1014dd91 100644 --- a/src/state/usePanelHostBase.ts +++ b/src/state/usePanelHostBase.ts @@ -8,6 +8,7 @@ // Extrahiert aus App.tsx. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import { applyFillMode } from "./fillMode"; +import { opsMutation, patchItem } from "../core"; import { useMemo, type RefObject } from "react"; import type { DrawingLevel, Layout, Project } from "../model/types"; import { resolvePenColor } from "../model/penSets"; @@ -474,21 +475,19 @@ export function usePanelHostBase(opts: { }, onSetSelectionFillMode: (mode) => { if (selection?.kind !== "drawing2d") return; - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => (d.id === selection.id ? applyFillMode(d, p.hatches, mode) : d)), - })); + const id = selection.id; + setProject(opsMutation((p) => patchItem(p, "drawings2d", id, (d) => applyFillMode(d, p.hatches, mode)))); }, onSetSelectionFillOpacity: (opacity) => { if (selection?.kind === "drawing2d") - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => { - if (d.id !== selection.id) return d; - const { fillOpacity: _old, ...rest } = d; - return opacity >= 1 ? rest : { ...rest, fillOpacity: Math.max(0, opacity) }; - }), - })); + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", selection.id, (d) => { + const { fillOpacity: _old, ...rest } = d; + return opacity >= 1 ? rest : { ...rest, fillOpacity: Math.max(0, opacity) }; + }), + ), + ); }, onSetSelectionOpacity: (opacity) => { // Deckkraft eines 2D-Elements. Bei BILDERN bleibt es die Deckkraft der @@ -497,15 +496,13 @@ export function usePanelHostBase(opts: { // Füllungen wirkt (`Drawing2D.opacity`). Nur EIN Bedienfeld — welches // Feld gesetzt wird, entscheidet die Form. if (selection?.kind === "drawing2d") - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => { - if (d.id !== selection.id) return d; - return d.geom.shape === "image" - ? { ...d, geom: { ...d.geom, opacity } } - : { ...d, opacity }; - }), - })); + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", selection.id, (d) => + d.geom.shape === "image" ? { ...d, geom: { ...d.geom, opacity } } : { ...d, opacity }, + ), + ), + ); else if (selection?.kind === "layoutAnnotation" && activeLayout) patchOpenLayout(activeLayout.id, (l) => patchAnnotationInLayout(l, selection.id, { opacity }), @@ -571,44 +568,39 @@ export function usePanelHostBase(opts: { }, onAddColorToCustomPalette: (paletteId, hex) => addColorToCustomPalette(paletteId, hex), onSetDashScale: (drawingId, scale) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => (d.id === drawingId ? { ...d, dashScale: scale } : d)), - })), + setProject(opsMutation((p) => patchItem(p, "drawings2d", drawingId, { dashScale: scale }))), onSetDetailRefLabel: (drawingId, label) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => - d.id === drawingId && d.geom.shape === "detailref" - ? { ...d, geom: { ...d.geom, label } } - : d, + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => + d.geom.shape === "detailref" ? { ...d, geom: { ...d.geom, label } } : d, + ), ), - })), + ), onSetDetailRefSheetLayout: (drawingId, sheetLayoutId) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => { - if (d.id !== drawingId || d.geom.shape !== "detailref") return d; - const geom = { ...d.geom }; - if (sheetLayoutId) geom.sheetLayoutId = sheetLayoutId; - else delete geom.sheetLayoutId; - return { ...d, geom }; - }), - })), - onSetDetailRefSheetLabel: (drawingId, sheetLabel) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => - d.id === drawingId && d.geom.shape === "detailref" - ? { ...d, geom: { ...d.geom, sheetLabel } } - : d, + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => { + if (d.geom.shape !== "detailref") return d; + const geom = { ...d.geom }; + if (sheetLayoutId) geom.sheetLayoutId = sheetLayoutId; + else delete geom.sheetLayoutId; + return { ...d, geom }; + }), ), - })), + ), + onSetDetailRefSheetLabel: (drawingId, sheetLabel) => + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => + d.geom.shape === "detailref" ? { ...d, geom: { ...d.geom, sheetLabel } } : d, + ), + ), + ), onSetHatchPlacement: (drawingId, patch) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => { - if (d.id !== drawingId) return d; + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => { const next = { ...d }; // `null` = zurück auf die Ressource (Feld entfernen). if ("angleDeg" in patch) @@ -618,24 +610,23 @@ export function usePanelHostBase(opts: { if ("origin" in patch) patch.origin === null ? delete next.hatchOrigin : (next.hatchOrigin = patch.origin); return next; - }), - })), + }), + ), + ), onSetEndMarks: (drawingId, patch) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => - d.id === drawingId ? { ...d, endMarks: { ...d.endMarks, ...patch } } : d, + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => ({ ...d, endMarks: { ...d.endMarks, ...patch } })), ), - })), + ), onSetDimensionStyle: (drawingId, patch) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => - d.id === drawingId && d.geom.shape === "dimension" - ? { ...d, geom: { ...d.geom, ...patch } } - : d, + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => + d.geom.shape === "dimension" ? { ...d, geom: { ...d.geom, ...patch } } : d, + ), ), - })), + ), onSetSelectionBackgroundPen: (penId) => { if (!selection) return; const background = penId ? resolvePenColor(project, penId) : undefined; diff --git a/src/tools/transform.ts b/src/tools/transform.ts index 78de0f52..38aa450f 100644 --- a/src/tools/transform.ts +++ b/src/tools/transform.ts @@ -7,7 +7,7 @@ // P distribute — Original bleibt + N Kopien gleichmäßig zwischen Original und Ziel. // // Bezeichner englisch, UI-Text via t() (CONVENTIONS.md). Reine Funktionen + Geometrie; -// die App hält den State und wendet `commitTransform` immutabel an. +// die App hält den State und wendet die Ops aus `transformOps` an ([K4] S3). import { transformSolid } from "../core"; import type { @@ -32,6 +32,10 @@ import { drawingPreviewShapes } from "./drawingPreview"; import { mvGeom, reversesOrientation, scaleFactor, scaleGeom } from "../core"; import { uniqueId } from "./types"; import type { CommandSelection } from "../commands/types"; +import { applyOps } from "../core"; +import type { CoreOp } from "../core"; +import { addItems, opsMutation, patchItems } from "../core"; +import type { ProjectMutation } from "../core"; export type TransformOp = "move" | "rotate" | "mirror" | "scale"; export type CopyMode = "move" | "copy" | "array" | "distribute"; // U / I / O / P @@ -497,17 +501,20 @@ export function rotateGizmoShapes(center: Vec2, refPoint: Vec2, cursor: Vec2): D // ── Commit ─────────────────────────────────────────────────────────────────── -/** Wendet die Transformation immutabel auf das Projekt an (Original + Kopien). */ -export function commitTransform( +/** + * Die Transformation als Ops ([K4] S3): `replace` je bewegtem Original (nur bei „move"), `add` der + * Kopien je Liste. Liest nur die gewählten Elemente — keine Projekt-Differenz über alle Wände. + */ +export function transformOps( project: Project, sel: TransformSelection, op: TransformOp, pts: Vec2[], mode: CopyMode, count: number, -): Project { +): CoreOp[] { const items = gatherItems(project, sel, op); - if (items.length === 0) return project; + if (items.length === 0) return []; const wallIds = new Set(sel.wallIds); // Bei einer Skalierung müssen auch Grössenfelder (Radius/Schrifthöhe/…) // mitziehen — dafür `scaleGeom` statt `mvGeom` (s. dort); analog für @@ -517,18 +524,11 @@ export function commitTransform( const stairAt = (s: Stair, fn: (p: Vec2) => Vec2, t: number): Stair => mvStair(s, fn, op === "scale" ? scaleFactor(pts, t) : 1); - let walls = project.walls; - let drawings2d = project.drawings2d; - let extrudedSolids = project.extrudedSolids ?? []; - let columns = project.columns ?? []; - let ceilings = project.ceilings ?? []; - let roofs = project.roofs ?? []; - let stairs = project.stairs ?? []; - let rooms = project.rooms ?? []; const ceilingIds = new Set(sel.ceilingIds ?? []); const roofIds = new Set(sel.roofIds ?? []); const stairIds = new Set(sel.stairIds ?? []); const roomIds = new Set(sel.roomIds ?? []); + const ops: CoreOp[] = []; // U (move): Original an die Endlage (t=1) transformieren. Objekt-Sperre // (`locked`) überall mitgeprüft — dieselbe Semantik wie `gatherItems` @@ -537,13 +537,20 @@ export function commitTransform( // genau diese Art von Doppel-Pflege). if (movesOriginal(mode)) { const fn = transformFn(op, pts, 1); - walls = walls.map((w) => - wallIds.has(w.id) && !w.locked ? { ...w, start: fn(w.start), end: fn(w.end) } : w, + ops.push( + ...patchItems(project, "walls", (w) => wallIds.has(w.id) && !w.locked, (w) => ({ + ...w, + start: fn(w.start), + end: fn(w.end), + })), ); const moveDrawIds = drawingIdSet(sel); if (moveDrawIds.size > 0) { - drawings2d = drawings2d.map((d) => - moveDrawIds.has(d.id) && !d.locked ? { ...d, geom: geomAt(d.geom, fn, 1) } : d, + ops.push( + ...patchItems(project, "drawings2d", (d) => moveDrawIds.has(d.id) && !d.locked, (d) => ({ + ...d, + geom: geomAt(d.geom, fn, 1), + })), ); } if (sel.extrudedSolidId) { @@ -552,19 +559,21 @@ export function commitTransform( // nutzt) müssen mitziehen — sonst weicht das 3D-Volumen sichtbar von // der Grundriss-Kontur ab (nur `center` mitzuführen genügt nicht). const f1 = op === "scale" ? scaleFactor(pts, 1) : 1; - extrudedSolids = extrudedSolids.map((s) => (s.id === sel.extrudedSolidId ? transformSolid(s, fn, f1) : s)); + const solidId = sel.extrudedSolidId; + ops.push(...patchItems(project, "extrudedSolids", (s) => s.id === solidId, (s) => transformSolid(s, fn, f1))); } if (sel.columnId) { - columns = columns.map((c) => (c.id === sel.columnId && !c.locked ? mvColumn(c, fn) : c)); + const columnId = sel.columnId; + ops.push(...patchItems(project, "columns", (c) => c.id === columnId && !c.locked, (c) => mvColumn(c, fn))); } if (ceilingIds.size > 0) - ceilings = ceilings.map((c) => (ceilingIds.has(c.id) && !c.locked ? mvCeiling(c, fn) : c)); - if (roofIds.size > 0 && roofTransformAllowed(op)) { - roofs = roofs.map((r) => (roofIds.has(r.id) && !r.locked ? mvRoof(r, fn) : r)); - } + ops.push(...patchItems(project, "ceilings", (c) => ceilingIds.has(c.id) && !c.locked, (c) => mvCeiling(c, fn))); + if (roofIds.size > 0 && roofTransformAllowed(op)) + ops.push(...patchItems(project, "roofs", (r) => roofIds.has(r.id) && !r.locked, (r) => mvRoof(r, fn))); if (stairIds.size > 0) - stairs = stairs.map((s) => (stairIds.has(s.id) && !s.locked ? stairAt(s, fn, 1) : s)); - if (roomIds.size > 0) rooms = rooms.map((r) => (roomIds.has(r.id) && !r.locked ? mvRoom(r, fn) : r)); + ops.push(...patchItems(project, "stairs", (s) => stairIds.has(s.id) && !s.locked, (s) => stairAt(s, fn, 1))); + if (roomIds.size > 0) + ops.push(...patchItems(project, "rooms", (r) => roomIds.has(r.id) && !r.locked, (r) => mvRoom(r, fn))); } // Kopien anhängen (I/O/P bzw. mirror copy). @@ -614,16 +623,41 @@ export function commitTransform( } } } - - return { - ...project, - walls: newWalls.length ? [...walls, ...newWalls] : walls, - drawings2d: newDrawings.length ? [...drawings2d, ...newDrawings] : drawings2d, - extrudedSolids: newSolids.length ? [...extrudedSolids, ...newSolids] : extrudedSolids, - columns: newColumns.length ? [...columns, ...newColumns] : columns, - ceilings: newCeilings.length ? [...ceilings, ...newCeilings] : ceilings, - roofs: newRoofs.length ? [...roofs, ...newRoofs] : roofs, - stairs: newStairs.length ? [...stairs, ...newStairs] : stairs, - rooms: newRooms.length ? [...rooms, ...newRooms] : rooms, - }; + ops.push( + ...addItems("walls", newWalls), + ...addItems("drawings2d", newDrawings), + ...addItems("extrudedSolids", newSolids), + ...addItems("columns", newColumns), + ...addItems("ceilings", newCeilings), + ...addItems("roofs", newRoofs), + ...addItems("stairs", newStairs), + ...addItems("rooms", newRooms), + ); + return ops; +} + +/** Wendet die Transformation immutabel auf das Projekt an (Original + Kopien), über {@link transformOps}. */ +export function commitTransform( + project: Project, + sel: TransformSelection, + op: TransformOp, + pts: Vec2[], + mode: CopyMode, + count: number, +): Project { + return applyOps(project, transformOps(project, sel, op, pts, mode, count)); +} + +/** + * Wie {@link commitTransform}, als Projekt → Projekt-Funktion mit mitgeführten Ops (`opsMutation`) — + * für `CommandResult.commit`: `setProject` übergibt die Ops ohne Projekt-Differenz an den Kern. + */ +export function transformMutation( + sel: TransformSelection, + op: TransformOp, + pts: Vec2[], + mode: CopyMode, + count: number, +): ProjectMutation { + return opsMutation((p) => transformOps(p, sel, op, pts, mode, count)); }