From 3c576cc38760fc56f24055dfe76361099c903489 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 22:24:45 +0000 Subject: [PATCH] [K4][6][8] Editier-Befehle und Werkzeug-Commits liefern Ops direkt (trim, extend, fillet, chamfer, break, join, explode, align, autodim, defblock, georef, sectionline, solid, solidbool, voidbox, terrain, ceilingOpening, tools/) Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src/commands/cmds/align.ts | 7 +- src/commands/cmds/autodim.ts | 11 +- src/commands/cmds/break.ts | 14 +-- src/commands/cmds/ceilingOpening.ts | 18 ++-- src/commands/cmds/chamfer.ts | 13 ++- src/commands/cmds/defblock.ts | 22 ++-- src/commands/cmds/editOps.test.ts | 147 ++++++++++++++++++++++++++ src/commands/cmds/explode.ts | 5 +- src/commands/cmds/extend.ts | 15 ++- src/commands/cmds/fillet.ts | 13 ++- src/commands/cmds/georef.ts | 5 +- src/commands/cmds/join.ts | 13 +-- src/commands/cmds/sectionline.test.ts | 6 +- src/commands/cmds/sectionline.ts | 20 ++-- src/commands/cmds/solid.ts | 10 +- src/commands/cmds/solidbool.ts | 16 ++- src/commands/cmds/terrain.ts | 14 +-- src/commands/cmds/trim.ts | 16 +-- src/commands/cmds/voidbox.ts | 5 +- src/editors/align.test.ts | 7 +- src/editors/align.ts | 32 +++--- src/editors/explode.test.ts | 5 +- src/editors/explode.ts | 38 +++---- src/model/geoRebase.ts | 28 +++++ src/tools/tools.ts | 46 ++++---- 25 files changed, 354 insertions(+), 172 deletions(-) create mode 100644 src/commands/cmds/editOps.test.ts diff --git a/src/commands/cmds/align.ts b/src/commands/cmds/align.ts index c124e147..aa2be993 100644 --- a/src/commands/cmds/align.ts +++ b/src/commands/cmds/align.ts @@ -5,7 +5,8 @@ // // Die Modell-Logik liegt in `editors/align.ts`. -import { alignDrawings, distributeDrawings } from "../../editors/align"; +import { alignOps, distributeOps } from "../../editors/align"; +import { opsMutation } from "../../core"; import type { AlignMode, DistributeAxis } from "../../editors/align"; import type { CmdOption, @@ -62,13 +63,13 @@ export const alignCommand: Command = { const axis = input.id.slice(5) as DistributeAxis; return [ { phase: "pick", lastPoint: null } as AlignState, - { draft: null, done: true, commit: (p) => distributeDrawings(p, ids, axis) }, + { draft: null, done: true, commit: opsMutation((p) => distributeOps(p, ids, axis)) }, ]; } const mode = input.id as AlignMode; return [ { phase: "pick", lastPoint: null } as AlignState, - { draft: null, done: true, commit: (p) => alignDrawings(p, ids, mode) }, + { draft: null, done: true, commit: opsMutation((p) => alignOps(p, ids, mode)) }, ]; }, diff --git a/src/commands/cmds/autodim.ts b/src/commands/cmds/autodim.ts index f12cc21b..3e19d5f8 100644 --- a/src/commands/cmds/autodim.ts +++ b/src/commands/cmds/autodim.ts @@ -3,7 +3,7 @@ // (`geometry/autoDimensions.ts`). Ein erneuter Aufruf ersetzt die zuvor automatisch erzeugten // Ketten DIESES Geschosses (feste IDs), von Hand gezeichnete Bemassungen bleiben. -import { autoExteriorDimensions } from "../../core"; +import { addItems, autoExteriorDimensions, opsMutation, removeItems } from "../../core"; import type { Command, CommandContext, CommandResult, CommandState } from "../types"; const PREFIX = "autodim"; @@ -30,10 +30,11 @@ export const autodimCommand: Command = { return { draft: null, done: true, - commit: (p) => ({ - ...p, - drawings2d: [...p.drawings2d.filter((d) => !d.id.startsWith(own)), ...dims.map((d) => d.drawing)], - }), + // Frühere Ketten dieses Geschosses raus, neue hinten dran. + commit: opsMutation((p) => [ + ...removeItems(p, "drawings2d", (d) => d.id.startsWith(own)), + ...addItems("drawings2d", dims.map((d) => d.drawing)), + ]), }; }, diff --git a/src/commands/cmds/break.ts b/src/commands/cmds/break.ts index 75bcc84f..c5c18993 100644 --- a/src/commands/cmds/break.ts +++ b/src/commands/cmds/break.ts @@ -20,6 +20,8 @@ import type { Drawing2D } from "../../model/types"; import { uniqueId } from "../../tools/types"; +import { addItems, opsMutation, removeItems } from "../../core"; +import type { CoreOp } from "../../core"; import { breakCurve, nearestOnPolyline } from "../../core"; import { hasRealBulge } from "../../core"; import { chainToGeom, geomToCurve, isTrimmable, pickCurveAt } from "./trim"; @@ -41,20 +43,20 @@ function pickBreakable(project: Project, levelId: string, pt: Vec2): Drawing2D | return d; } -function applyBreak(p: Project, target: Drawing2D, p1: Vec2, p2: Vec2): Project { +function breakOps(p: Project, target: Drawing2D, p1: Vec2, p2: Vec2): CoreOp[] { const curve = geomToCurve(target.geom); - if (!curve) return p; + if (!curve) return []; const hit1 = nearestOnPolyline(curve.pts, false, p1); const hit2 = nearestOnPolyline(curve.pts, false, p2); - if (!hit1 || !hit2) return p; + if (!hit1 || !hit2) return []; const pieces = breakCurve(curve.pts, hit1, hit2); const replacements: Drawing2D[] = pieces.map((pts) => ({ ...target, id: uniqueId("dr2d"), geom: chainToGeom({ pts, closed: false }), })); - const others = p.drawings2d.filter((d) => d.id !== target.id); - return { ...p, drawings2d: [...others, ...replacements] }; + // Ziel raus, Stücke hinten dran. + return [...removeItems(p, "drawings2d", [target.id]), ...addItems("drawings2d", replacements)]; } /** Vorschau der Reststücke (für den Draft). */ @@ -104,7 +106,7 @@ export const breakCommand: Command = { } // phase "p2" const { target, p1 } = s; - return [idle()[0], { draft: null, done: true, commit: (p) => applyBreak(p, target, p1, input.point) }]; + return [idle()[0], { draft: null, done: true, commit: opsMutation((p) => breakOps(p, target, p1, input.point)) }]; }, onMove: (state, point): [CommandState, CommandResult] => { diff --git a/src/commands/cmds/ceilingOpening.ts b/src/commands/cmds/ceilingOpening.ts index e274e2b3..4f62a51d 100644 --- a/src/commands/cmds/ceilingOpening.ts +++ b/src/commands/cmds/ceilingOpening.ts @@ -8,7 +8,8 @@ // 1) „Erste Ecke der Aussparung:" → Punkt // 2) „Gegenecke:" → Live-Rechteck-Vorschau; Klick committet. -import { pointInOutline } from "../../core"; +import { opsMutation, patchItem, pointInOutline } from "../../core"; +import type { CoreOp } from "../../core"; import type { Command, CommandContext, @@ -63,10 +64,10 @@ function holeDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { * Rechteck vollständig enthält (alle 4 Ecken im Umriss). Entartete Rechtecke * und Rechtecke ausserhalb jeder Decke werden verworfen (Projekt unverändert). */ -function appendCeilingOpening(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project { +function ceilingOpeningOps(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] { const w = Math.abs(b.x - a.x); const d = Math.abs(b.y - a.y); - if (w < 0.05 || d < 0.05) return p; + if (w < 0.05 || d < 0.05) return []; const corners = rectCorners(a, b); const host = (p.ceilings ?? []).find( (c) => @@ -74,13 +75,8 @@ function appendCeilingOpening(p: Project, a: Vec2, b: Vec2, ctx: CommandContext) c.outline.length >= 3 && corners.every((pt) => pointInOutline(pt, c.outline)), ); - if (!host) return p; - return { - ...p, - ceilings: (p.ceilings ?? []).map((c) => - c.id === host.id ? { ...c, openings: [...(c.openings ?? []), corners] } : c, - ), - }; + if (!host) return []; + return patchItem(p, "ceilings", host.id, (c) => ({ ...c, openings: [...(c.openings ?? []), corners] })); } const idle = (): [CommandState, CommandResult] => [ @@ -117,7 +113,7 @@ export const ceilingOpeningCommand: Command = { const b = input.point; return [ { phase: "start", lastPoint: null } as HoleIdle, - { draft: null, done: true, commit: (p) => appendCeilingOpening(p, a, b, ctx) }, + { draft: null, done: true, commit: opsMutation((p) => ceilingOpeningOps(p, a, b, ctx)) }, ]; }, diff --git a/src/commands/cmds/chamfer.ts b/src/commands/cmds/chamfer.ts index 99fa2ee2..1d6d4f1c 100644 --- a/src/commands/cmds/chamfer.ts +++ b/src/commands/cmds/chamfer.ts @@ -9,6 +9,8 @@ // ist von Natur aus gerade, also ein exaktes (nicht approximiertes) Ergebnis. import type { Drawing2D, Drawing2DGeom } from "../../model/types"; +import { opsMutation, patchItem } from "../../core"; +import type { CoreOp } from "../../core"; import { hasRealBulge } from "../../core"; import { chamferCorner, type Chamfer } from "../../core"; import type { @@ -102,15 +104,12 @@ function chamferDraft(hit: CornerHit, d: number, at: Vec2 | null): ToolDraft { return draft; } -function commitChamfer(p: Project, hit: CornerHit, distance: number): Project { +function chamferOps(p: Project, hit: CornerHit, distance: number): CoreOp[] { const c = chamferFor(hit, distance); - if (!c) return p; // Distanz zu gross für die Schenkellänge, oder Ecke (fast) gerade → No-op + if (!c) return []; // Distanz zu gross für die Schenkellänge, oder Ecke (fast) gerade → No-op const pts = applyChamferPoints(hit, c); const geom: Drawing2DGeom = { shape: "polyline", pts, closed: hit.curve.closed }; - return { - ...p, - drawings2d: p.drawings2d.map((d) => (d.id === hit.drawing.id ? { ...d, geom } : d)), - }; + return patchItem(p, "drawings2d", hit.drawing.id, { geom }); } // ── Zustand ─────────────────────────────────────────────────────────────────── @@ -167,7 +166,7 @@ export const chamferCommand: Command = { else return [s, { draft: null }]; return [ { phase: "done", lastPoint: null } as ChamferDone, - { draft: null, done: true, commit: (p) => commitChamfer(p, s.hit, d) }, + { draft: null, done: true, commit: opsMutation((p) => chamferOps(p, s.hit, d)) }, ]; }, diff --git a/src/commands/cmds/defblock.ts b/src/commands/cmds/defblock.ts index 373ef5a3..8edf8572 100644 --- a/src/commands/cmds/defblock.ts +++ b/src/commands/cmds/defblock.ts @@ -11,7 +11,8 @@ // Leere/rein-block-Auswahl → No-Op (kein Commit). import type { BlockDef, Drawing2D } from "../../model/types"; -import { mvGeom } from "../../core"; +import { addItems, mvGeom, opsMutation, removeItems } from "../../core"; +import type { CoreOp } from "../../core"; import { uniqueId } from "../../tools/types"; import type { Command, @@ -32,11 +33,11 @@ function nextBlockName(p: Project): string { return `Block ${(p.blockDefs?.length ?? 0) + 1}`; } -function defineAndReplace(p: Project, ids: string[], at: Vec2, ctx: CommandContext): Project { +function defineOps(p: Project, ids: string[], at: Vec2, ctx: CommandContext): CoreOp[] { const idSet = new Set(ids); // Block-Instanzen als Quelle ausschliessen (keine verschachtelten Blöcke). const srcs = p.drawings2d.filter((d) => idSet.has(d.id) && d.geom.shape !== "block"); - if (srcs.length === 0) return p; + if (srcs.length === 0) return []; const toLocal = (pt: Vec2): Vec2 => ({ x: pt.x - at.x, y: pt.y - at.y }); const def: BlockDef = { id: uniqueId("blk"), @@ -50,13 +51,12 @@ function defineAndReplace(p: Project, ids: string[], at: Vec2, ctx: CommandConte categoryCode: ctx.defaultCategoryCode, geom: { shape: "block", blockDefId: def.id, at, rotation: 0 }, }; - const srcIds = new Set(srcs.map((d) => d.id)); - const rest = p.drawings2d.filter((d) => !srcIds.has(d.id)); - return { - ...p, - blockDefs: [...(p.blockDefs ?? []), def], - drawings2d: [...rest, instance], - }; + // Definition anhängen, Quellen raus, Instanz hinten dran. + return [ + ...addItems("blockDefs", [def]), + ...removeItems(p, "drawings2d", srcs.map((d) => d.id)), + ...addItems("drawings2d", [instance]), + ]; } interface DefblockState extends CommandState { @@ -81,7 +81,7 @@ export const defblockCommand: Command = { const ids = selectedDrawingIds(ctx.selection); if (ids.length === 0) return idle(); const at = input.point; - return [idle()[0], { draft: null, done: true, commit: (p) => defineAndReplace(p, ids, at, ctx) }]; + return [idle()[0], { draft: null, done: true, commit: opsMutation((p) => defineOps(p, ids, at, ctx)) }]; }, onMove: (state): [CommandState, CommandResult] => [state, { draft: null }], diff --git a/src/commands/cmds/editOps.test.ts b/src/commands/cmds/editOps.test.ts new file mode 100644 index 00000000..47a74a71 --- /dev/null +++ b/src/commands/cmds/editOps.test.ts @@ -0,0 +1,147 @@ +// Editier-Befehle liefern ihre Änderung als Ops ([K4] S3): Beispiele „applyOps(vorher, Ops) == erwartet" +// (die Fassung mit Projekt → Projekt wurde beim Umbau gegen die Ops-Fassung auf Zufallsprojekten verglichen). +import { describe, expect, it } from "vitest"; +import { sampleProject } from "../../model/sampleProject"; +import type { Drawing2D, Project } from "../../model/types"; +import type { Command, CommandContext, CmdInput } from "../types"; +import { explodeOps } from "../../editors/explode"; +import { translateOps, translateProject } from "../../model/geoRebase"; +import { applyOps } from "../../core/ops"; +import { isOpsMutation } from "../../core"; +import { joinCommand } from "./join"; +import { defblockCommand } from "./defblock"; +import { terrainCommand } from "./terrain"; +import { ceilingOpeningCommand } from "./ceilingOpening"; +import { breakCommand } from "./break"; +import { georefCommand } from "./georef"; + +const level = sampleProject.drawingLevels.find((l) => l.kind === "floor")!; +const line = (id: string, a: [number, number], b: [number, number]): Drawing2D => ({ + id, + type: "drawing2d", + levelId: level.id, + categoryCode: sampleProject.layers[0].code, + geom: { shape: "line", a: { x: a[0], y: a[1] }, b: { x: b[0], y: b[1] } }, +}); +const rect = (id: string): Drawing2D => ({ + ...line(id, [0, 0], [1, 1]), + geom: { shape: "rect", min: { x: 0, y: 0 }, max: { x: 2, y: 1 } }, +}); +const withDrawings = (ds: Drawing2D[], extra: Partial = {}): Project => ({ ...sampleProject, drawings2d: ds, ...extra }); + +function ctxOf(p: Project, ids: string[] = []): CommandContext { + return { + project: p, + level, + defaultCategoryCode: p.layers[0].code, + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: ids[0] ?? null, drawingIds: ids }, + }; +} + +/** Führt die Eingaben aus und liefert das Ergebnis der letzten Commit-Funktion. */ +function commitOf(cmd: Command, p: Project, inputs: CmdInput[], ids: string[] = []): { out: Project; viaOps: boolean } { + const ctx = ctxOf(p, ids); + let st = cmd.init(); + let fn: ((p: Project) => Project) | undefined = cmd.autoRun?.(ctx).commit; + for (const input of inputs) { + const [ns, res] = cmd.onInput(st, input, ctx); + st = ns; + if (res.commit) fn = res.commit; + } + return { out: fn ? fn(p) : p, viaOps: fn ? isOpsMutation(fn) : true }; +} + +describe("Editier-Befehle: Ops", () => { + it("explode: Teile stehen an der Stelle des Originals, Nachbarn unberührt", () => { + const p = withDrawings([line("a", [0, 0], [1, 0]), rect("r"), line("z", [5, 5], [6, 6])]); + const out = applyOps(p, explodeOps(p, ["r"])); + expect(out.drawings2d.map((d) => d.geom.shape)).toEqual(["line", "line", "line", "line", "line", "line"]); + expect(out.drawings2d[0]).toBe(p.drawings2d[0]); + expect(out.drawings2d[5]).toBe(p.drawings2d[2]); + expect(out.drawings2d.some((d) => d.id === "r")).toBe(false); + expect(explodeOps(p, ["a"])).toEqual([]); // Linie ist nicht zerlegbar + }); + + it("explode: zwei Originale in einer Folge (Positionen verschieben sich mit)", () => { + const p = withDrawings([rect("r1"), line("m", [0, 0], [1, 0]), rect("r2")]); + const out = applyOps(p, explodeOps(p, ["r1", "r2"])); + expect(out.drawings2d).toHaveLength(9); + expect(out.drawings2d[4].id).toBe("m"); + expect(out.drawings2d.filter((d) => d.geom.shape === "line")).toHaveLength(9); + }); + + it("join: Quellen raus, Polylinie hinten dran", () => { + const p = withDrawings([line("a", [0, 0], [1, 0]), line("x", [9, 9], [8, 8]), line("b", [1, 0], [1, 1])]); + const { out, viaOps } = commitOf(joinCommand, p, [], ["a", "b"]); + expect(viaOps).toBe(true); + expect(out.drawings2d.map((d) => d.id).slice(0, 1)).toEqual(["x"]); + expect(out.drawings2d).toHaveLength(2); + const g = out.drawings2d[1].geom; + expect(g.shape).toBe("polyline"); + }); + + it("defblock: Definition, Instanz hinten, Quellen weg", () => { + const p = withDrawings([line("a", [0, 0], [1, 0]), line("b", [1, 0], [1, 1]), line("c", [4, 4], [5, 5])], { blockDefs: undefined }); + const { out, viaOps } = commitOf(defblockCommand, p, [{ kind: "point", point: { x: 1, y: 1 } }], ["a", "b"]); + expect(viaOps).toBe(true); + expect(out.blockDefs).toHaveLength(1); + expect(out.blockDefs![0].geom2d).toHaveLength(2); + expect(out.drawings2d.map((d) => d.geom.shape)).toEqual(["line", "block"]); + }); + + it("break: Ziel raus, zwei Stücke hinten dran", () => { + const p = withDrawings([line("L", [0, 0], [10, 0]), line("o", [0, 5], [1, 5])]); + const { out } = commitOf(breakCommand, p, [ + { kind: "point", point: { x: 3, y: 0 } }, + { kind: "point", point: { x: 7, y: 0 } }, + ]); + expect(out.drawings2d.map((d) => d.id).slice(0, 1)).toEqual(["o"]); + expect(out.drawings2d).toHaveLength(3); + }); + + it("terrain: ohne Höhenlinien bleibt der Kontext leer (kein Commit-Fehler)", () => { + const none = commitOf(terrainCommand, withDrawings([], { context: [] }), [{ kind: "point", point: { x: 0, y: 0 } }]); + expect(none.out.context).toEqual([]); + }); + + it("ceilingOpening: Aussparung in die Decke, die das Rechteck enthält", () => { + const base = sampleProject.ceilings?.find((c) => c.floorId === level.id) ?? { + id: "c1", + type: "ceiling" as const, + floorId: level.id, + outline: [ + { x: 0, y: 0 }, + { x: 10, y: 0 }, + { x: 10, y: 10 }, + { x: 0, y: 10 }, + ], + ceilingTypeId: sampleProject.ceilingTypes?.[0]?.id ?? "x", + }; + const ceiling = { ...base, outline: [{ x: 0, y: 0 }, { x: 10, y: 0 }, { x: 10, y: 10 }, { x: 0, y: 10 }], openings: undefined }; + const p = { ...sampleProject, ceilings: [ceiling] } as Project; + const { out, viaOps } = commitOf(ceilingOpeningCommand, p, [ + { kind: "point", point: { x: 1, y: 1 } }, + { kind: "point", point: { x: 3, y: 3 } }, + ]); + expect(viaOps).toBe(true); + expect(out.ceilings![0].openings).toHaveLength(1); + expect(out.ceilings![0].openings![0]).toHaveLength(4); + // Rechteck ausserhalb: unverändert + const miss = commitOf(ceilingOpeningCommand, p, [ + { kind: "point", point: { x: 20, y: 20 } }, + { kind: "point", point: { x: 23, y: 23 } }, + ]); + expect(miss.out).toBe(p); + }); + + it("georef: Ops ergeben translateProject; Null-Verschiebung = keine Ops", () => { + expect(translateOps(sampleProject, 0, 0)).toEqual([]); + const viaOps = applyOps(sampleProject, translateOps(sampleProject, 12.5, -3)); + expect(viaOps).toEqual(translateProject(sampleProject, 12.5, -3)); + const { out } = commitOf(georefCommand, sampleProject, [{ kind: "point", point: { x: -12.5, y: 3 } }]); + expect(out).toEqual(translateProject(sampleProject, 12.5, -3)); + }); +}); diff --git a/src/commands/cmds/explode.ts b/src/commands/cmds/explode.ts index 86d1517a..e2bb1446 100644 --- a/src/commands/cmds/explode.ts +++ b/src/commands/cmds/explode.ts @@ -6,7 +6,8 @@ // bewusst NICHT zerlegt wird (Kreis/Ellipse/Spline/Text/…): diese Elemente // bleiben unverändert stehen, statt zu verschwinden. -import { explodeDrawings } from "../../editors/explode"; +import { explodeOps } from "../../editors/explode"; +import { opsMutation } from "../../core"; import type { Command, CommandContext, CommandResult, CommandSelection, CommandState } from "../types"; /** Gewählte 2D-Elemente (Mehrfachauswahl bevorzugt). */ @@ -31,7 +32,7 @@ export const explodeCommand: Command = { autoRun: (ctx: CommandContext): CommandResult => { const ids = selectedDrawingIds(ctx.selection); if (ids.length === 0) return { draft: null, done: true }; - return { draft: null, done: true, commit: (p) => explodeDrawings(p, ids) }; + return { draft: null, done: true, commit: opsMutation((p) => explodeOps(p, ids)) }; }, onInput: (): [CommandState, CommandResult] => done(), diff --git a/src/commands/cmds/extend.ts b/src/commands/cmds/extend.ts index e7c6eda8..3b223ff0 100644 --- a/src/commands/cmds/extend.ts +++ b/src/commands/cmds/extend.ts @@ -23,6 +23,8 @@ // Bezeichner englisch, Kommentare/UI deutsch (CONVENTIONS.md). import type { Drawing2D, Drawing2DGeom } from "../../model/types"; +import { opsMutation, patchItem } from "../../core"; +import type { CoreOp } from "../../core"; import { bulgePolylinePoints, hasRealBulge } from "../../core"; import { extendBulgeSegment, extendSegment, pointSegmentDistance, polylineEdges } from "../../core"; import type { @@ -145,12 +147,12 @@ function extendCurve(curve: Curve, cutters: Curve[], pick: Vec2): Curve | null { } /** Wendet Extend auf das Projekt an: ersetzt die getroffene Kurve durch ihre verlängerte Form. */ -function applyExtend(p: Project, target: Drawing2D, pick: Vec2): Project { +function extendOps(p: Project, target: Drawing2D, pick: Vec2): CoreOp[] { const curve = geomToOpenCurve(target.geom); - if (!curve) return p; + if (!curve) return []; const cutters = cuttersFor(p, target.levelId, target.id); const next = extendCurve(curve, cutters, pick); - if (!next) return p; + if (!next) return []; const geom: Drawing2DGeom = next.pts.length === 2 && target.geom.shape === "line" && !hasRealBulge(next.bulge) ? { shape: "line", a: next.pts[0], b: next.pts[1] } @@ -160,10 +162,7 @@ function applyExtend(p: Project, target: Drawing2D, pick: Vec2): Project { closed: false, ...(hasRealBulge(next.bulge) ? { bulge: next.bulge } : {}), }; - return { - ...p, - drawings2d: p.drawings2d.map((d) => (d.id === target.id ? { ...d, geom } : d)), - }; + return patchItem(p, "drawings2d", target.id, { geom }); } /** Vorschau-Form der verlängerten Kurve (für den Draft — Bogen tesselliert, s. `curveHitEdges`). */ @@ -215,7 +214,7 @@ export const extendCommand: Command = { const target = pickOpenCurveAt(ctx.project, ctx.level.id, input.point); if (!target) return [s, { draft: null }]; const pick = input.point; - return [s, { draft: null, commit: (p) => applyExtend(p, target, pick) }]; + return [s, { draft: null, commit: opsMutation((p) => extendOps(p, target, pick)) }]; }, onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { diff --git a/src/commands/cmds/fillet.ts b/src/commands/cmds/fillet.ts index eae0d120..836f9165 100644 --- a/src/commands/cmds/fillet.ts +++ b/src/commands/cmds/fillet.ts @@ -15,6 +15,8 @@ // einer polyline (kein reines Rechteck mehr). import type { Drawing2D, Drawing2DGeom } from "../../model/types"; +import { opsMutation, patchItem } from "../../core"; +import type { CoreOp } from "../../core"; import { bulgeFromSagittaPoint, hasRealBulge } from "../../core"; import { filletCorner, type Fillet } from "../../core"; import type { @@ -138,18 +140,15 @@ function filletDraft(hit: CornerHit, r: number, at: Vec2 | null): ToolDraft { return draft; } -function commitFillet(p: Project, hit: CornerHit, r: number): Project { +function filletOps(p: Project, hit: CornerHit, r: number): CoreOp[] { const f = filletFor(hit, r); - if (!f) return p; // Radius zu gross für die Schenkellänge, oder Ecke (fast) gerade → No-op + if (!f) return []; // Radius zu gross für die Schenkellänge, oder Ecke (fast) gerade → No-op const pts = applyFilletPoints(hit, f); const edgeCount = hit.curve.closed ? pts.length : pts.length - 1; const bulge = new Array(edgeCount).fill(0); bulge[hit.index] = filletBulge(f); // Kante tangentA→tangentB (an Position hit.index) const geom: Drawing2DGeom = { shape: "polyline", pts, closed: hit.curve.closed, bulge }; - return { - ...p, - drawings2d: p.drawings2d.map((d) => (d.id === hit.drawing.id ? { ...d, geom } : d)), - }; + return patchItem(p, "drawings2d", hit.drawing.id, { geom }); } // ── Zustand ─────────────────────────────────────────────────────────────────── @@ -200,7 +199,7 @@ export const filletCommand: Command = { else return [s, { draft: null }]; return [ { phase: "done", lastPoint: null } as FilletDone, - { draft: null, done: true, commit: (p) => commitFillet(p, s.hit, r) }, + { draft: null, done: true, commit: opsMutation((p) => filletOps(p, s.hit, r)) }, ]; }, diff --git a/src/commands/cmds/georef.ts b/src/commands/cmds/georef.ts index 401e1b46..ab8a9897 100644 --- a/src/commands/cmds/georef.ts +++ b/src/commands/cmds/georef.ts @@ -11,7 +11,8 @@ // // Ein-Klick-Befehl: der erste (einzige) Punkt committet sofort. -import { translateProject } from "../../model/geoRebase"; +import { translateOps } from "../../model/geoRebase"; +import { opsMutation } from "../../core"; import type { Command, CommandResult, @@ -53,7 +54,7 @@ export const georefCommand: Command = { { draft: null, done: true, - commit: (p: Project) => translateProject(p, -x, -y), + commit: opsMutation((p: Project) => translateOps(p, -x, -y)), }, ]; }, diff --git a/src/commands/cmds/join.ts b/src/commands/cmds/join.ts index 1cddcb3b..715558b7 100644 --- a/src/commands/cmds/join.ts +++ b/src/commands/cmds/join.ts @@ -8,6 +8,8 @@ import { joinDrawings } from "../../editors/splitJoin"; import type { Drawing2D } from "../../model/types"; +import { addItems, opsMutation, removeItems } from "../../core"; +import type { CoreOp } from "../../core"; import type { Command, CommandContext, @@ -23,14 +25,13 @@ function selectedDrawingIds(sel: CommandSelection): string[] { return sel.drawingId ? [sel.drawingId] : []; } -/** Ersetzt die gewählten Quell-Drawings durch das Join-Ergebnis (immutabel). */ -function applyJoin(project: Project, ids: string[]): Project { +/** Ops: die gewählten Quell-Drawings raus, das Join-Ergebnis hinten dran. */ +function joinOps(project: Project, ids: string[]): CoreOp[] { const idSet = new Set(ids); const srcs = project.drawings2d.filter((d) => idSet.has(d.id)); - if (srcs.length < 2) return project; // <2 → nichts zu verbinden + if (srcs.length < 2) return []; // <2 → nichts zu verbinden const joined: Drawing2D[] = joinDrawings(srcs); - const rest = project.drawings2d.filter((d) => !idSet.has(d.id)); - return { ...project, drawings2d: [...rest, ...joined] }; + return [...removeItems(project, "drawings2d", idSet), ...addItems("drawings2d", joined)]; } interface JoinState extends CommandState { @@ -54,7 +55,7 @@ export const joinCommand: Command = { autoRun: (ctx: CommandContext): CommandResult => { const ids = selectedDrawingIds(ctx.selection); if (ids.length < 2) return { draft: null, done: true }; - return { draft: null, done: true, commit: (p) => applyJoin(p, ids) }; + return { draft: null, done: true, commit: opsMutation((p) => joinOps(p, ids)) }; }, onInput: (): [CommandState, CommandResult] => done(), diff --git a/src/commands/cmds/sectionline.test.ts b/src/commands/cmds/sectionline.test.ts index 23b9c3b2..bb974ae1 100644 --- a/src/commands/cmds/sectionline.test.ts +++ b/src/commands/cmds/sectionline.test.ts @@ -3,9 +3,11 @@ import { describe, it, expect } from "vitest"; import { _test } from "./sectionline"; -import type { DrawingLevel, Project } from "../../model/types"; +import type { DrawingLevel, Project, Vec2 } from "../../model/types"; +import { applyOps } from "../../core/ops"; -const { commitLine, nextLevelName } = _test; +const { lineOps, nextLevelName } = _test; +const commitLine = (p: Project, a: Vec2, b: Vec2, kind: "section" | "elevation") => applyOps(p, lineOps(p, a, b, kind)); function projectWith(levels: DrawingLevel[]): Project { return { diff --git a/src/commands/cmds/sectionline.ts b/src/commands/cmds/sectionline.ts index d085ea65..847d07d6 100644 --- a/src/commands/cmds/sectionline.ts +++ b/src/commands/cmds/sectionline.ts @@ -18,6 +18,8 @@ import { t } from "../../i18n"; import type { DrawingLevel, DrawingLevelKind } from "../../model/types"; import { leftNormal, normalize, sub } from "../../model/geometry"; +import { addItems, opsMutation, patchItem } from "../../core"; +import type { CoreOp } from "../../core"; import type { Command, CommandResult, @@ -102,18 +104,12 @@ function nextLevelName(p: Project, kind: LineKind): string { * EINE Ebene der Art ohne Linie, wird sie belegt; sonst wird eine neue angelegt. * Entartete (zu kurze) Linien werden verworfen. */ -function commitLine(p: Project, a: Vec2, b: Vec2, kind: LineKind): Project { - if (Math.hypot(b.x - a.x, b.y - a.y) < 0.1) return p; +function lineOps(p: Project, a: Vec2, b: Vec2, kind: LineKind): CoreOp[] { + if (Math.hypot(b.x - a.x, b.y - a.y) < 0.1) return []; const line: [Vec2, Vec2] = [a, b]; const orphans = p.drawingLevels.filter((z) => z.kind === kind && !z.linePoints); if (orphans.length === 1) { - const targetId = orphans[0].id; - return { - ...p, - drawingLevels: p.drawingLevels.map((z) => - z.id === targetId ? { ...z, linePoints: line, directionSign: z.directionSign ?? 1 } : z, - ), - }; + return patchItem(p, "drawingLevels", orphans[0].id, (z) => ({ ...z, linePoints: line, directionSign: z.directionSign ?? 1 })); } const level: DrawingLevel = { id: `${kind}-${Date.now()}`, @@ -124,7 +120,7 @@ function commitLine(p: Project, a: Vec2, b: Vec2, kind: LineKind): Project { linePoints: line, directionSign: 1, }; - return { ...p, drawingLevels: [...p.drawingLevels, level] }; + return addItems("drawingLevels", [level]); } interface LineIdle extends CommandState { @@ -188,7 +184,7 @@ function makeCommand(name: string, startKind: LineKind): Command { const kind = s.kind; return [ { phase: "start", kind, lastPoint: null } as LineIdle, - { draft: null, done: true, commit: (p) => commitLine(p, a, b, kind) }, + { draft: null, done: true, commit: opsMutation((p) => lineOps(p, a, b, kind)) }, ]; }, @@ -210,4 +206,4 @@ export const sectionLineCommand: Command = makeCommand("sectionline", "section") export const viewLineCommand: Command = makeCommand("viewline", "elevation"); // Für Tests: die reinen Datenpfad-Helfer. -export const _test = { commitLine, nextLevelName, directionArrow }; +export const _test = { lineOps, nextLevelName, directionArrow }; diff --git a/src/commands/cmds/solid.ts b/src/commands/cmds/solid.ts index f56c955f..711ed578 100644 --- a/src/commands/cmds/solid.ts +++ b/src/commands/cmds/solid.ts @@ -13,6 +13,7 @@ // Der Körper steht auf der Geschoss-UK (Z = 0 lokal). import type { ExtrudedSolid } from "../../model/types"; +import { addItems, opsMutation } from "../../core"; import { uniqueId } from "../../tools/types"; import type { Command, @@ -20,7 +21,6 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; @@ -247,8 +247,8 @@ export const solidCommand: Command = { { draft: null, done: true, - commit: (p: Project) => { - if (!built) return p; + commit: opsMutation(() => { + if (!built) return []; const solid: ExtrudedSolid = { id: uniqueId("body"), type: "extrudedSolid", @@ -257,8 +257,8 @@ export const solidCommand: Command = { height: built.height, brep: { spec: built.spec, origin: built.points[0], label: built.label }, }; - return { ...p, extrudedSolids: [...(p.extrudedSolids ?? []), solid] }; - }, + return addItems("extrudedSolids", [solid]); + }), }, ]; }, diff --git a/src/commands/cmds/solidbool.ts b/src/commands/cmds/solidbool.ts index fc67ac1c..5e249292 100644 --- a/src/commands/cmds/solidbool.ts +++ b/src/commands/cmds/solidbool.ts @@ -10,7 +10,7 @@ import type { ExtrudedSolid, Vec2 } from "../../model/types"; import { getFloor } from "../../model/types"; import { uniqueId } from "../../tools/types"; -import { extrudedSolidSpec } from "../../core"; +import { addItems, extrudedSolidSpec, opsMutation, removeItems } from "../../core"; import type { Command, CommandResult, CommandState, CmdOption, Project, ToolDraft } from "../types"; export type SolidBoolOp = "union" | "difference" | "intersection"; @@ -167,17 +167,15 @@ export const solidBoolCommand: Command = { { draft: null, done: true, - commit: (p: Project) => { + commit: opsMutation((p) => { const a = (p.extrudedSolids ?? []).find((x) => x.id === firstId); const b = (p.extrudedSolids ?? []).find((x) => x.id === hit.id); - if (!a || !b) return p; + if (!a || !b) return []; const merged = combineSolids(p, a, b, op); - if (!merged) return p; - return { - ...p, - extrudedSolids: [...(p.extrudedSolids ?? []).filter((x) => x.id !== a.id && x.id !== b.id), merged], - }; - }, + if (!merged) return []; + // Beide Körper raus, das Ergebnis hinten dran. + return [...removeItems(p, "extrudedSolids", [a.id, b.id]), ...addItems("extrudedSolids", [merged])]; + }), }, ]; }, diff --git a/src/commands/cmds/terrain.ts b/src/commands/cmds/terrain.ts index 8d9c94df..9cb6809c 100644 --- a/src/commands/cmds/terrain.ts +++ b/src/commands/cmds/terrain.ts @@ -13,6 +13,8 @@ import { generateTerrainFromContours } from "../../model/terrain"; import type { ContextObject } from "../../model/types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; import type { Command, CommandResult, @@ -20,21 +22,21 @@ import type { Project, } from "../types"; -/** Hängt ein aus dem ersten ContourSet abgeleitetes TIN an (immutabel). */ -function appendTerrain(p: Project): Project { +/** Ops: hängt ein aus dem ersten ContourSet abgeleitetes TIN an `context` an. */ +function terrainOps(p: Project): CoreOp[] { const context: ContextObject[] = p.context ?? []; const set = context.find((o) => o.type === "contourSet"); - if (!set || set.type !== "contourSet") return p; + if (!set || set.type !== "contourSet") return []; const terrain = generateTerrainFromContours(set.contours); - if (terrain.indices.length === 0) return p; // kein sinnvolles TIN - return { ...p, context: [...context, terrain] }; + if (terrain.indices.length === 0) return []; // kein sinnvolles TIN + return addItems("context", [terrain]); } /** Ergebnis, das den Befehl sofort beendet und das TIN committet. */ const COMMIT_DONE: CommandResult = { draft: null, done: true, - commit: appendTerrain, + commit: opsMutation(terrainOps), }; const IDLE: CommandState = { phase: "idle", lastPoint: null }; diff --git a/src/commands/cmds/trim.ts b/src/commands/cmds/trim.ts index 74065890..022ebf1b 100644 --- a/src/commands/cmds/trim.ts +++ b/src/commands/cmds/trim.ts @@ -21,6 +21,8 @@ import type { Drawing2D, Drawing2DGeom } from "../../model/types"; import { bulgePolylinePoints, hasRealBulge } from "../../core"; import { uniqueId } from "../../tools/types"; +import { addItems, opsMutation, removeItems } from "../../core"; +import type { CoreOp } from "../../core"; import { pointSegmentDistance, polylineEdges, trimPolylineWithBulge, vecEqual } from "../../core"; import type { Command, @@ -165,13 +167,13 @@ function trimCurve( return trimPolylineWithBulge(curve.pts, curve.bulge, curve.closed, cutters, pick); } -function applyTrim( +function trimOps( p: Project, target: Drawing2D, pick: Vec2, -): Project { +): CoreOp[] { const curve = geomToCurve(target.geom); - if (!curve) return p; + if (!curve) return []; const cutters = cuttersFor(p, target.levelId, target.id).map((c) => ({ pts: c.pts, closed: c.closed, @@ -180,12 +182,12 @@ function applyTrim( const rest = trimCurve(curve, cutters, pick); // Echtes No-op: genau eine Kette, identisch (gleiche Punkte) zur Quelle → // nichts wurde weggeschnitten (kein Schnitt mit Cuttern). - if (rest.length === 1 && sameChain(rest[0], curve)) return p; + if (rest.length === 1 && sameChain(rest[0], curve)) return []; const replacements: Drawing2D[] = rest .filter((c) => c.pts.length >= 2) .map((c) => ({ ...target, id: uniqueId("dr2d"), geom: chainToGeom(c) })); - const others = p.drawings2d.filter((d) => d.id !== target.id); - return { ...p, drawings2d: [...others, ...replacements] }; + // Ziel raus, Reste hinten dran (wie bisher: `[...others, ...replacements]`). + return [...removeItems(p, "drawings2d", [target.id]), ...addItems("drawings2d", replacements)]; } /** Vorschau-Formen der NACH dem Trim verbleibenden Ketten (für den Draft — tesselliert, s. `DraftShape`). */ @@ -259,7 +261,7 @@ export const trimCommand: Command = { // Wiederholend: NICHT done — nach dem Commit bleibt „pick" aktiv. return [ s, - { draft: null, commit: (p) => applyTrim(p, target, pick) }, + { draft: null, commit: opsMutation((p) => trimOps(p, target, pick)) }, ]; }, diff --git a/src/commands/cmds/voidbox.ts b/src/commands/cmds/voidbox.ts index c243c9f3..ea9bfe90 100644 --- a/src/commands/cmds/voidbox.ts +++ b/src/commands/cmds/voidbox.ts @@ -6,8 +6,9 @@ // Beliebige Profile: Polylinie extrudieren und im Objekt-Panel „Abzugskörper" setzen. import type { ExtrudedSolid } from "../../model/types"; +import { addItems, opsMutation } from "../../core"; import { uniqueId } from "../../tools/types"; -import type { Command, CommandResult, CommandState, Project, ToolDraft, Vec2 } from "../types"; +import type { Command, CommandResult, CommandState, ToolDraft, Vec2 } from "../types"; type Step = "corner" | "corner2" | "height" | "offset"; @@ -83,7 +84,7 @@ function finish(s: VoidState, offset: number, levelId: string): [CommandState, C { draft: null, done: true, - commit: (p: Project) => (solid ? { ...p, extrudedSolids: [...(p.extrudedSolids ?? []), solid] } : p), + commit: opsMutation(() => (solid ? addItems("extrudedSolids", [solid]) : [])), }, ]; } diff --git a/src/editors/align.test.ts b/src/editors/align.test.ts index 45d932c0..5ce2f28f 100644 --- a/src/editors/align.test.ts +++ b/src/editors/align.test.ts @@ -1,10 +1,15 @@ /** Ausrichten und Verteilen der 2D-Auswahl. */ import { describe, expect, it } from "vitest"; -import { alignDrawings, distributeDrawings } from "./align"; +import { alignOps, distributeOps } from "./align"; +import type { AlignMode, DistributeAxis } from "./align"; +import { applyOps } from "../core/ops"; import { sampleProject } from "../model/sampleProject"; import type { Drawing2D, Project } from "../model/types"; +const alignDrawings = (p: Project, ids: string[], m: AlignMode) => applyOps(p, alignOps(p, ids, m)); +const distributeDrawings = (p: Project, ids: string[], a: DistributeAxis) => applyOps(p, distributeOps(p, ids, a)); + /** Rechtecke als Testobjekte: bbox ist direkt ablesbar. */ function rects(boxes: [string, number, number, number, number][]): Project { const drawings2d: Drawing2D[] = boxes.map(([id, x0, y0, x1, y1]) => ({ diff --git a/src/editors/align.ts b/src/editors/align.ts index 31aa04c6..92724a76 100644 --- a/src/editors/align.ts +++ b/src/editors/align.ts @@ -8,7 +8,8 @@ import type { Drawing2D, Project, Vec2 } from "../model/types"; import { geomBBox } from "../state/selectionInfo"; -import { mvGeom } from "../core"; +import { mvGeom, patchItems } from "../core"; +import type { CoreOp } from "../core"; /** Ausrichtungskante bzw. -achse. */ export type AlignMode = "left" | "right" | "centerX" | "top" | "bottom" | "centerY"; @@ -31,18 +32,15 @@ function boxesOf(project: Project, ids: string[]): Boxed[] { .map((d) => ({ d, ...geomBBox(d.geom) })); } -/** Verschiebt die genannten Elemente um je einen eigenen Vektor. */ -function moveBy(project: Project, deltas: Map): Project { - if (deltas.size === 0) return project; - return { - ...project, - drawings2d: project.drawings2d.map((d) => { - const delta = deltas.get(d.id); - if (!delta || (delta.x === 0 && delta.y === 0)) return d; - const fn = (p: Vec2): Vec2 => ({ x: p.x + delta.x, y: p.y + delta.y }); - return { ...d, geom: mvGeom(d.geom, fn) }; - }), - }; +/** Ops: verschiebt die genannten Elemente um je einen eigenen Vektor. */ +function moveBy(project: Project, deltas: Map): CoreOp[] { + if (deltas.size === 0) return []; + return patchItems(project, "drawings2d", (d) => deltas.has(d.id), (d) => { + const delta = deltas.get(d.id)!; + if (delta.x === 0 && delta.y === 0) return d; + const fn = (p: Vec2): Vec2 => ({ x: p.x + delta.x, y: p.y + delta.y }); + return { ...d, geom: mvGeom(d.geom, fn) }; + }); } /** @@ -53,9 +51,9 @@ function moveBy(project: Project, deltas: Map): Project { * Weniger als zwei Elemente ergeben keine Ausrichtung (nichts, woran man sich * ausrichten könnte) — das Projekt bleibt unverändert. */ -export function alignDrawings(project: Project, ids: string[], mode: AlignMode): Project { +export function alignOps(project: Project, ids: string[], mode: AlignMode): CoreOp[] { const boxes = boxesOf(project, ids); - if (boxes.length < 2) return project; + if (boxes.length < 2) return []; const minX = Math.min(...boxes.map((b) => b.minX)); const maxX = Math.max(...boxes.map((b) => b.maxX)); @@ -101,9 +99,9 @@ export function alignDrawings(project: Project, ids: string[], mode: AlignMode): * Unter drei Elementen gibt es nichts zu verteilen (die Äusseren bleiben ja * ohnehin stehen) — das Projekt bleibt unverändert. */ -export function distributeDrawings(project: Project, ids: string[], axis: DistributeAxis): Project { +export function distributeOps(project: Project, ids: string[], axis: DistributeAxis): CoreOp[] { const boxes = boxesOf(project, ids); - if (boxes.length < 3) return project; + if (boxes.length < 3) return []; const center = (b: Boxed) => (axis === "x" ? (b.minX + b.maxX) / 2 : (b.minY + b.maxY) / 2); const sorted = [...boxes].sort((a, b) => center(a) - center(b)); diff --git a/src/editors/explode.test.ts b/src/editors/explode.test.ts index c5a9f164..5208e067 100644 --- a/src/editors/explode.test.ts +++ b/src/editors/explode.test.ts @@ -5,7 +5,10 @@ */ import { describe, expect, it } from "vitest"; -import { explodeDrawings, explodeGeom } from "./explode"; +import { explodeGeom, explodeOps } from "./explode"; +import { applyOps } from "../core/ops"; + +const explodeDrawings = (p: Project, ids: string[]) => applyOps(p, explodeOps(p, ids)); import { sampleProject } from "../model/sampleProject"; import { bulgeArc } from "../geometry/bulge"; import type { Drawing2D, Drawing2DGeom, Project } from "../model/types"; diff --git a/src/editors/explode.ts b/src/editors/explode.ts index 5ab05aca..6eddb3cb 100644 --- a/src/editors/explode.ts +++ b/src/editors/explode.ts @@ -16,7 +16,8 @@ // unverändert stehen. Ebenso alles, was kein 2D-Element ist. import type { Drawing2D, Drawing2DGeom, Project, Vec2 } from "../model/types"; -import { bulgeArc } from "../core"; +import { bulgeArc, addItems } from "../core"; +import type { CoreOp } from "../core"; import { uniqueId } from "../tools/types"; /** Teilgeometrien EINES Elements, oder `null`, wenn es nicht zerlegbar ist. */ @@ -121,28 +122,27 @@ function mapPoints(geom: Drawing2DGeom, fn: (p: Vec2) => Vec2): Drawing2DGeom { * Die Reihenfolge im Array bleibt stabil — die Teile stehen an der Stelle des * Originals, damit sich die Zeichenreihenfolge (z-Anordnung) nicht ändert. */ -export function explodeDrawings(project: Project, ids: string[]): Project { +export function explodeOps(project: Project, ids: readonly string[]): CoreOp[] { const wanted = new Set(ids); - let changed = false; - const next: Drawing2D[] = []; + const dropped: string[] = []; + const inserts: { at: number; items: Drawing2D[] }[] = []; + let len = 0; // Länge der Liste nach dem Entfernen der zerlegten Originale = Position im Ergebnis for (const d of project.drawings2d) { - if (!wanted.has(d.id)) { - next.push(d); - continue; - } - const parts = explodeGeom(d.geom, project); + const parts = wanted.has(d.id) ? explodeGeom(d.geom, project) : null; if (!parts || parts.length === 0) { - next.push(d); + len++; continue; } - changed = true; - for (const geom of parts) { - // Stil-Eigenschaften der Quelle übernehmen; nur Identität und Geometrie - // sind neu. `hatchId`/Füllung bleiben bewusst dran: löst man ein - // gefülltes Rechteck auf, tragen die Linien sie zwar wirkungslos mit, - // aber es geht nichts verloren, falls der Nutzer sie wieder schliesst. - next.push({ ...d, id: uniqueId("dr2d"), geom }); - } + dropped.push(d.id); + // Stil-Eigenschaften der Quelle übernehmen; nur Identität und Geometrie sind neu. `hatchId`/Füllung + // bleiben bewusst dran: es geht nichts verloren, falls der Nutzer die Linien wieder schliesst. + const items = parts.map((geom): Drawing2D => ({ ...d, id: uniqueId("dr2d"), geom })); + inserts.push({ at: len, items }); + len += items.length; } - return changed ? { ...project, drawings2d: next } : project; + if (dropped.length === 0) return []; + // Originale in einem Zug raus, die Teile (aufsteigend) an ihrer Endposition wieder rein. + const ops: CoreOp[] = [{ kind: "remove", collection: "drawings2d", ids: dropped }]; + for (const ins of inserts) ops.push(...addItems("drawings2d", ins.items, ins.at)); + return ops; } diff --git a/src/model/geoRebase.ts b/src/model/geoRebase.ts index 1aed1d31..ec8b0c96 100644 --- a/src/model/geoRebase.ts +++ b/src/model/geoRebase.ts @@ -14,6 +14,8 @@ // // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). +import { replaceItem, setField } from "../core/opsBuild"; +import type { CoreOp } from "../core/ops"; import type { ContextObject, Contour, @@ -153,6 +155,32 @@ export function translateProject(project: Project, dx: number, dy: number): Proj }; } +/** Projekt-Listen, die {@link translateProject} verschiebt (jedes Element hat eine `id`). */ +const TRANSLATED_LISTS = [ + "walls", "ceilings", "roofs", "stairs", "rooms", "columns", "extrudedSolids", "drawings2d", "context", "drawingLevels", +] as const; + +/** + * Ops für {@link translateProject}: je geändertem Element ein `replace` (Reihenfolge und Identität + * unveränderter Elemente bleiben), `geoAnchor` als Feld. Das Ergebnis von `applyOps` ist gleich + * `translateProject(project, dx, dy)`. + */ +export function translateOps(project: Project, dx: number, dy: number): CoreOp[] { + const next = translateProject(project, dx, dy); + if (next === project) return []; + const ops: CoreOp[] = []; + for (const key of TRANSLATED_LISTS) { + const before = project[key] as readonly { id: string }[] | undefined; + const after = next[key] as readonly { id: string }[] | undefined; + if (!before || !after) continue; + after.forEach((e, i) => { + if (e !== before[i]) ops.push(replaceItem(key, e as never)); + }); + } + if (next.geoAnchor !== project.geoAnchor) ops.push(setField("geoAnchor", next.geoAnchor)); + return ops; +} + /** * Der LV95-Ursprung eines Projekts: die reale Landeskoordinate, die auf den * Modell-Nullpunkt (0,0) abgebildet wird. Aus `geoAnchor` abgeleitet diff --git a/src/tools/tools.ts b/src/tools/tools.ts index 55786ef7..fcc2a1be 100644 --- a/src/tools/tools.ts +++ b/src/tools/tools.ts @@ -4,7 +4,8 @@ import type { Ceiling, Drawing2D, Project, Vec2, Wall } from "../model/types"; import { wallTypeThickness } from "../model/types"; import { wallCorners } from "../model/geometry"; -import { normalizeOutline, ceilingArea } from "../core"; +import { addItems, ceilingArea, normalizeOutline, opsMutation } from "../core"; +import type { CoreOp } from "../core"; import type { DraftShape, Tool, ToolContext, ToolDraft, ToolId } from "./types"; import { uniqueId } from "./types"; @@ -72,8 +73,8 @@ function wallDraft(points: Vec2[], cursor: Vec2 | null, ctx: ToolContext): ToolD return draft; } -/** Hängt je Achssegment ein Wall des aktiven Typs ans Projekt (immutabel). */ -function appendWalls(project: Project, pts: Vec2[], ctx: ToolContext): Project { +/** Ops: hängt je Achssegment ein Wall des aktiven Typs an. */ +function appendWalls(pts: Vec2[], ctx: ToolContext): CoreOp[] { const height = ctx.level.floorHeight && ctx.level.floorHeight > 0 ? ctx.level.floorHeight : 2.6; const newWalls: Wall[] = []; @@ -92,8 +93,7 @@ function appendWalls(project: Project, pts: Vec2[], ctx: ToolContext): Project { height, }); } - if (newWalls.length === 0) return project; - return { ...project, walls: [...project.walls, ...newWalls] }; + return addItems("walls", newWalls); } const wallTool: Tool = { @@ -123,7 +123,7 @@ const wallTool: Tool = { const pts = s.points; return [ { phase: "idle" }, - { draft: null, done: true, commit: (proj) => appendWalls(proj, pts, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendWalls(pts, ctx)) }, ]; }, onCancel: () => [{ phase: "idle" }, { draft: null, done: true }], @@ -169,9 +169,9 @@ function ceilDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { return draft; } -function appendCeiling(project: Project, pts: Vec2[], ctx: ToolContext): Project { +function appendCeiling(project: Project, pts: Vec2[], ctx: ToolContext): CoreOp[] { const outline = normalizeOutline(pts); - if (!outline || ceilingArea(outline) < 1e-4) return project; + if (!outline || ceilingArea(outline) < 1e-4) return []; const hasCat = project.layers.some((c) => c.code === "30"); const c: Ceiling = { id: uniqueId("C"), @@ -181,7 +181,7 @@ function appendCeiling(project: Project, pts: Vec2[], ctx: ToolContext): Project outline, wallTypeId: ctx.activeWallTypeId, }; - return { ...project, ceilings: project.ceilings ? [...project.ceilings, c] : [c] }; + return addItems("ceilings", [c]); } const ceilingTool: Tool = { @@ -201,7 +201,7 @@ const ceilingTool: Tool = { // Klick auf den Startpunkt schließt den Umriss (ab 3 Punkten) und committet. if (s.points.length >= 3 && segLen(p.point, s.points[0]) < EPS) { const pts = s.points; - return [{ phase: "idle" }, { draft: null, done: true, commit: (proj) => appendCeiling(proj, pts, ctx) }]; + return [{ phase: "idle" }, { draft: null, done: true, commit: opsMutation((proj) => appendCeiling(proj, pts, ctx)) }]; } const points = [...s.points, p.point]; return [{ phase: "drawing", points, cursor: p.point }, { draft: ceilDraft(points, p.point) }]; @@ -217,7 +217,7 @@ const ceilingTool: Tool = { return [{ phase: "idle" }, { draft: null, done: true }]; } const pts = s.points; - return [{ phase: "idle" }, { draft: null, done: true, commit: (proj) => appendCeiling(proj, pts, ctx) }]; + return [{ phase: "idle" }, { draft: null, done: true, commit: opsMutation((proj) => appendCeiling(proj, pts, ctx)) }]; }, onCancel: () => [{ phase: "idle" }, { draft: null, done: true }], onUndoPoint: (state) => { @@ -318,7 +318,7 @@ function lineDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { return draft; } -function appendLine(project: Project, a: Vec2, b: Vec2, ctx: ToolContext): Project { +function appendLine(a: Vec2, b: Vec2, ctx: ToolContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -328,7 +328,7 @@ function appendLine(project: Project, a: Vec2, b: Vec2, ctx: ToolContext): Proje // Kein expliziter Linienstil → erbt Farbe/Strichstärke aus der aktiven Ebene // (Kategorie). Ein Linienstil-Picker kann das später überschreiben. }; - return { ...project, drawings2d: [...project.drawings2d, d] }; + return addItems("drawings2d", [d]); } const lineTool: Tool = { @@ -350,7 +350,7 @@ const lineTool: Tool = { const b = p.point; return [ { phase: "idle" }, - { draft: null, done: true, commit: (proj) => appendLine(proj, a, b, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendLine(a, b, ctx)) }, ]; }, onMove: (state, p) => { @@ -396,8 +396,8 @@ function polyDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { return draft; } -function appendPolyline(project: Project, pts: Vec2[], closed: boolean, ctx: ToolContext): Project { - if (pts.length < 2) return project; +function appendPolyline(pts: Vec2[], closed: boolean, ctx: ToolContext): CoreOp[] { + if (pts.length < 2) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -407,7 +407,7 @@ function appendPolyline(project: Project, pts: Vec2[], closed: boolean, ctx: Too // Kein expliziter Linienstil → erbt Farbe/Strichstärke aus der aktiven Ebene // (Kategorie). Ein Linienstil-Picker kann das später überschreiben. }; - return { ...project, drawings2d: [...project.drawings2d, d] }; + return addItems("drawings2d", [d]); } // Konstruktionslinie: Platzhalter-Werkzeug, gekoppelt an den `xline`-Befehl @@ -451,7 +451,7 @@ const polylineTool: Tool = { // Klick auf den Startpunkt schließt die Polylinie (ab 3 Punkten). if (s.points.length >= 3 && segLen(p.point, s.points[0]) < EPS) { const pts = s.points; - return [{ phase: "idle" }, { draft: null, done: true, commit: (proj) => appendPolyline(proj, pts, true, ctx) }]; + return [{ phase: "idle" }, { draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, true, ctx)) }]; } const points = [...s.points, p.point]; return [{ phase: "drawing", points, cursor: p.point }, { draft: polyDraft(points, p.point) }]; @@ -467,7 +467,7 @@ const polylineTool: Tool = { return [{ phase: "idle" }, { draft: null, done: true }]; } const pts = s.points; - return [{ phase: "idle" }, { draft: null, done: true, commit: (proj) => appendPolyline(proj, pts, false, ctx) }]; + return [{ phase: "idle" }, { draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, false, ctx)) }]; }, onCancel: () => [{ phase: "idle" }, { draft: null, done: true }], onUndoPoint: (state) => { @@ -513,10 +513,10 @@ function rectDraft(p0: Vec2, cursor: Vec2 | null): ToolDraft { return draft; } -function appendRect(project: Project, a: Vec2, b: Vec2, ctx: ToolContext): Project { +function appendRect(a: Vec2, b: Vec2, ctx: ToolContext): CoreOp[] { const min = { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y) }; const max = { x: Math.max(a.x, b.x), y: Math.max(a.y, b.y) }; - if (Math.abs(max.x - min.x) < EPS || Math.abs(max.y - min.y) < EPS) return project; + if (Math.abs(max.x - min.x) < EPS || Math.abs(max.y - min.y) < EPS) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -526,7 +526,7 @@ function appendRect(project: Project, a: Vec2, b: Vec2, ctx: ToolContext): Proje // Kein expliziter Linienstil → erbt Farbe/Strichstärke aus der aktiven Ebene // (Kategorie). Ein Linienstil-Picker kann das später überschreiben. }; - return { ...project, drawings2d: [...project.drawings2d, d] }; + return addItems("drawings2d", [d]); } const rectTool: Tool = { @@ -542,7 +542,7 @@ const rectTool: Tool = { } const a = s.p0; const b = p.point; - return [{ phase: "idle" }, { draft: null, done: true, commit: (proj) => appendRect(proj, a, b, ctx) }]; + return [{ phase: "idle" }, { draft: null, done: true, commit: opsMutation(() => appendRect(a, b, ctx)) }]; }, onMove: (state, p) => { const s = state as RectState;