From 3c576cc38760fc56f24055dfe76361099c903489 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 22:24:45 +0000 Subject: [PATCH 1/4] [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; From ebc805d6e8ec1e1431d5b521f2d0d49b221ca197 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 22:27:41 +0000 Subject: [PATCH 2/4] =?UTF-8?q?[K4][6][8]=20Einf=C3=BCgen,=20Gruppieren,?= =?UTF-8?q?=20Ungruppieren=20erzeugen=20Ops=20direkt=20(pasteElementClipbo?= =?UTF-8?q?ard,=20groupSelection,=20ungroup)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src/App.tsx | 5 +++-- src/editors/elementClipboard.test.ts | 6 +++-- src/editors/elementClipboard.ts | 33 ++++++++++++++-------------- src/state/groupActions.test.ts | 18 +++++++-------- src/state/groupActions.ts | 11 +++++----- src/state/useKeyboardShortcuts.ts | 21 +++++++++--------- 6 files changed, 49 insertions(+), 45 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index 64619482..7077c135 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -353,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 applyChange = useStore((s) => s.applyChange); const groupChanges = useStore((s) => s.groupChanges); const notify = useStore((s) => s.notify); const undo = useStore((s) => s.undo); @@ -1496,7 +1497,7 @@ export default function App() { }; useGroupShortcut( project, - setProject, + applyChange, { wallIds: selectedWallIds, drawingIds: selectedDrawingIds, @@ -1873,7 +1874,7 @@ export default function App() { setElementClipboard, activeLevelId, project, - setProject, + applyChange, { wallIds: setSelectedWallIds, drawingIds: setSelectedDrawingIds, diff --git a/src/editors/elementClipboard.test.ts b/src/editors/elementClipboard.test.ts index 18718a19..62c29c60 100644 --- a/src/editors/elementClipboard.test.ts +++ b/src/editors/elementClipboard.test.ts @@ -6,6 +6,7 @@ */ import { describe, it, expect } from "vitest"; import { collectElementClipboard, pasteElementClipboard, isClipboardEmpty } from "./elementClipboard"; +import { applyOps } from "../core/ops"; import type { ElementSelectionIds } from "./elementClipboard"; import type { Project, Wall, Opening, Ceiling } from "../model/types"; @@ -121,7 +122,8 @@ describe("pasteElementClipboard", () => { it("fügt Wand + Öffnung mit NEUEN, verknüpften IDs auf dem aktiven Geschoss ein", () => { const p = project(); const clip = collectElementClipboard(p, { ...emptySel(), wallIds: ["w1"] })!; - const { project: next, pastedIds } = pasteElementClipboard(p, clip, "og"); + const { ops, pastedIds } = pasteElementClipboard(clip, "og"); + const next = applyOps(p, ops); expect(next.walls.length).toBe(2); expect(next.openings!.length).toBe(2); const newWall = next.walls.find((w) => w.id === pastedIds.wallIds[0])!; @@ -137,7 +139,7 @@ describe("pasteElementClipboard", () => { it("Originale bleiben unverändert (immutabel)", () => { const p = project(); const clip = collectElementClipboard(p, { ...emptySel(), wallIds: ["w1"] })!; - pasteElementClipboard(p, clip, "og"); + pasteElementClipboard(clip, "og"); expect(p.walls.length).toBe(1); expect(p.walls[0].id).toBe("w1"); }); diff --git a/src/editors/elementClipboard.ts b/src/editors/elementClipboard.ts index 8e141eac..e954f728 100644 --- a/src/editors/elementClipboard.ts +++ b/src/editors/elementClipboard.ts @@ -31,6 +31,8 @@ import type { Wall, } from "../model/types"; import { uniqueId } from "../tools/types"; +import { addItems } from "../core"; +import type { CoreOp } from "../core"; /** Auswahl-IDs je Bauteil-Art, wie sie die 9 Auswahl-Kanäle des Stores liefern. */ export interface ElementSelectionIds { @@ -145,13 +147,12 @@ export interface PastedIds { /** * Fügt eine Zwischenablage ins Projekt ein: Klone mit neuen IDs auf dem * AKTIVEN Geschoss (`activeLevelId`), an denselben Modell-Koordinaten. Liefert - * das neue Projekt + die neuen IDs (für die Nachauswahl). + * die Ops (Anhängen je Liste) + die neuen IDs (für die Nachauswahl). */ export function pasteElementClipboard( - project: Project, clip: ElementClipboard, activeLevelId: string, -): { project: Project; pastedIds: PastedIds } { +): { ops: CoreOp[]; pastedIds: PastedIds } { const wallIdMap = new Map(); const newWalls: Wall[] = clip.walls.map((w) => { const id = uniqueId("W"); @@ -204,21 +205,21 @@ export function pasteElementClipboard( floorId: activeLevelId, })); - const next: Project = { - ...project, - walls: [...project.walls, ...newWalls], - drawings2d: [...project.drawings2d, ...newDrawings], - ceilings: [...(project.ceilings ?? []), ...newCeilings], - roofs: [...(project.roofs ?? []), ...newRoofs], - openings: [...(project.openings ?? []), ...newOpenings], - stairs: [...(project.stairs ?? []), ...newStairs], - rooms: [...(project.rooms ?? []), ...newRooms], - extrudedSolids: [...(project.extrudedSolids ?? []), ...newExtrudedSolids], - columns: [...(project.columns ?? []), ...newColumns], - }; + // Wände vor Öffnungen (Wirtswand zuerst), sonst Reihenfolge der Projekt-Listen. + const ops: CoreOp[] = [ + ...addItems("walls", newWalls), + ...addItems("drawings2d", newDrawings), + ...addItems("ceilings", newCeilings), + ...addItems("roofs", newRoofs), + ...addItems("openings", newOpenings), + ...addItems("stairs", newStairs), + ...addItems("rooms", newRooms), + ...addItems("extrudedSolids", newExtrudedSolids), + ...addItems("columns", newColumns), + ]; return { - project: next, + ops, pastedIds: { wallIds: newWalls.map((w) => w.id), drawingIds: newDrawings.map((d) => d.id), diff --git a/src/state/groupActions.test.ts b/src/state/groupActions.test.ts index 41292723..458e44e2 100644 --- a/src/state/groupActions.test.ts +++ b/src/state/groupActions.test.ts @@ -56,24 +56,24 @@ function project(groups: Group[]): Project { describe("groupSelection", () => { it("erzeugt eine Gruppe aus ≥2 gewählten Elementen", () => { const p = project([]); - const res = groupSelection(p, { ...EMPTY_MEM, wallIds: ["w1", "w2"] }, []); + const res = groupSelection({ ...EMPTY_MEM, wallIds: ["w1", "w2"] }, []); expect(res).not.toBeNull(); - expect(res!.project.groups).toHaveLength(1); - expect(res!.project.groups![0]).toMatchObject({ wallIds: ["w1", "w2"], groupIds: [] }); + const out = applyOps(p, res!.ops); + expect(out.groups).toHaveLength(1); + expect(out.groups![0]).toMatchObject({ wallIds: ["w1", "w2"], groupIds: [] }); }); it("weniger als 2 Elemente gruppiert nicht (Vectorworks-Konvention)", () => { - const p = project([]); - expect(groupSelection(p, { ...EMPTY_MEM, wallIds: ["w1"] }, [])).toBeNull(); - expect(groupSelection(p, EMPTY_MEM, [])).toBeNull(); + expect(groupSelection({ ...EMPTY_MEM, wallIds: ["w1"] }, [])).toBeNull(); + expect(groupSelection(EMPTY_MEM, [])).toBeNull(); }); it("bereits gewählte Gruppen werden als Untergruppen verschachtelt, nicht vermischt", () => { const inner: Group = { id: "g1", wallIds: ["w1"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: [] }; const p = project([inner]); - const res = groupSelection(p, { ...EMPTY_MEM, wallIds: ["w2"] }, ["g1"]); + const res = groupSelection({ ...EMPTY_MEM, wallIds: ["w2"] }, ["g1"]); expect(res).not.toBeNull(); - const outer = res!.project.groups!.find((g) => g.id === res!.groupId)!; + const outer = applyOps(p, res!.ops).groups!.find((g) => g.id === res!.groupId)!; expect(outer.wallIds).toEqual(["w2"]); expect(outer.groupIds).toEqual(["g1"]); }); @@ -297,7 +297,7 @@ describe("ungroup", () => { const p = project([inner, outer]); const res = ungroup(p, "g2"); expect(res).not.toBeNull(); - expect(res!.project.groups!.map((g) => g.id)).toEqual(["g1"]); // g2 weg, g1 bleibt + expect(applyOps(p, res!.ops).groups!.map((g) => g.id)).toEqual(["g1"]); // g2 weg, g1 bleibt expect(res!.members.wallIds).toEqual(["w2"]); expect(res!.subGroupIds).toEqual(["g1"]); }); diff --git a/src/state/groupActions.ts b/src/state/groupActions.ts index e7591800..a659e302 100644 --- a/src/state/groupActions.ts +++ b/src/state/groupActions.ts @@ -11,7 +11,7 @@ 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 { addItems, itemsOf, patchItem, removeItems } from "../core"; import type { EntityCollection } from "../core"; /** Mitglieds-IDs je Elementart — dieselbe Form wie `Group`, ohne `id`/`name`/`groupIds`. */ @@ -353,10 +353,9 @@ export function activeGroupOps(before: Project, ops: readonly CoreOp[], groupPat * ihre Mitglieder platt zu vermischen). Leere Auswahl → `null` (nichts zu tun). */ export function groupSelection( - project: Project, sel: GroupMembership, selectedGroupIds: string[], -): { project: Project; groupId: string } | null { +): { ops: CoreOp[]; groupId: string } | null { const totalCount = KEYS.reduce((n, k) => n + sel[k].length, 0) + selectedGroupIds.length; if (totalCount < 2) return null; // Gruppieren braucht ≥ 2 Elemente (Vectorworks-Konvention) @@ -373,7 +372,7 @@ export function groupSelection( openingIds: sel.openingIds, groupIds: [...selectedGroupIds], }; - return { project: { ...project, groups: [...(project.groups ?? []), g] }, groupId: id }; + return { ops: addItems("groups", [g]), groupId: id }; } /** @@ -386,11 +385,11 @@ export function groupSelection( export function ungroup( project: Project, groupId: string, -): { project: Project; members: GroupMembership; subGroupIds: string[] } | null { +): { ops: CoreOp[]; members: GroupMembership; subGroupIds: string[] } | null { const g = (project.groups ?? []).find((x) => x.id === groupId); if (!g) return null; return { - project: { ...project, groups: (project.groups ?? []).filter((x) => x.id !== groupId) }, + ops: removeItems(project, "groups", [groupId]), members: { wallIds: g.wallIds, drawingIds: g.drawingIds, diff --git a/src/state/useKeyboardShortcuts.ts b/src/state/useKeyboardShortcuts.ts index f160fe78..e8a755c3 100644 --- a/src/state/useKeyboardShortcuts.ts +++ b/src/state/useKeyboardShortcuts.ts @@ -18,6 +18,7 @@ import type { CopyMode, TransformOp } from "../tools/transform"; import type { CommandEngine } from "../commands/engine"; import type { CommandLineHandle } from "../ui/CommandLine"; import type { Drawing2D, Project, Vec2 } from "../model/types"; +import type { CoreOp } from "../core"; import { differenceDrawings, intersectionDrawings, unionDrawings } from "../editors/booleanOps"; import type { BooleanResult } from "../editors/booleanOps"; import { groupSelection, mergeMembership, ungroup, EMPTY_MEMBERSHIP } from "./groupActions"; @@ -548,7 +549,7 @@ export function useElementClipboardShortcut( setElementClipboard: (c: ElementClipboard | null) => void, activeLevelId: string, project: Project, - setProject: (next: Project | ((p: Project) => Project)) => void, + applyChange: (ops: readonly CoreOp[]) => void, setSelected: { wallIds: (ids: string[]) => void; drawingIds: (ids: string[]) => void; @@ -587,8 +588,8 @@ export function useElementClipboardShortcut( e.preventDefault(); const paste = (clip: ElementClipboard | null) => { if (!clip || isClipboardEmpty(clip)) return; - const { project: next, pastedIds } = pasteElementClipboard(project, clip, activeLevelId); - setProject(next); + const { ops, pastedIds } = pasteElementClipboard(clip, activeLevelId); + applyChange(ops); setSelected.wallIds(pastedIds.wallIds); setSelected.drawingIds(pastedIds.drawingIds); setSelected.ceilingIds(pastedIds.ceilingIds); @@ -764,7 +765,7 @@ export function useTransformShortcuts( */ export function useGroupShortcut( project: Project, - setProject: (updater: (p: Project) => Project) => void, + applyChange: (ops: readonly CoreOp[]) => void, currentSelection: GroupMembership, selectedGroupIds: string[], applySelection: (mem: GroupMembership, groupIds: string[]) => void, @@ -781,24 +782,24 @@ export function useGroupShortcut( // Ungruppieren: für jede gewählte Gruppe eine Hülle auflösen; ihre // direkten Mitglieder (+ Untergruppen) werden die neue Auswahl. if (selectedGroupIds.length === 0) return; - let p = project; + const ops: CoreOp[] = []; let members: GroupMembership = { ...EMPTY_MEMBERSHIP }; const newGroupIds: string[] = []; for (const gid of selectedGroupIds) { - const res = ungroup(p, gid); + const res = ungroup(project, gid); if (!res) continue; - p = res.project; + ops.push(...res.ops); members = mergeMembership(members, res.members); newGroupIds.push(...res.subGroupIds); } - setProject(() => p); + applyChange(ops); applySelection(members, newGroupIds); return; } // Gruppieren: aktuelle Auswahl (+ bereits gewählte Gruppen als Untergruppen). - const res = groupSelection(project, currentSelection, selectedGroupIds); + const res = groupSelection(currentSelection, selectedGroupIds); if (!res) return; - setProject(() => res.project); + applyChange(res.ops); applySelection(currentSelection, [res.groupId]); }; window.addEventListener("keydown", onKey); From fc41dcd9a62b3d945fa2ed6e3c18783592e51894 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 22:37:41 +0000 Subject: [PATCH 3/4] [K4][6][8] Panel-Aktionen, Typ-CRUD und App-Handler erzeugen Ops direkt (usePanelHostBase, useProjectActions, Split/Boolean/Sperren/Kategorien/Kollisionsmarken/Layout/Einstellungen); neuer Helfer replaceWithMany Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src/App.tsx | 105 ++++------- src/analysis/clash.test.ts | 7 +- src/analysis/clash.ts | 11 +- src/core/extra.ts | 2 +- src/core/opsBuild.test.ts | 22 +++ src/core/opsBuild.ts | 31 ++++ src/editors/explode.ts | 22 +-- src/editors/matchProps.test.ts | 7 +- src/editors/matchProps.ts | 26 ++- src/state/objectLock.test.ts | 8 +- src/state/objectLock.ts | 49 ++---- src/state/panelOps.test.ts | 198 +++++++++++++++++++++ src/state/usePanelHostBase.ts | 306 +++++++++------------------------ src/state/useProjectActions.ts | 138 ++++++--------- 14 files changed, 477 insertions(+), 455 deletions(-) create mode 100644 src/state/panelOps.test.ts diff --git a/src/App.tsx b/src/App.tsx index 7077c135..f0f8657a 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -61,7 +61,7 @@ import { MeshImportHost } from "./ui/MeshImportDialog"; import { openMeshFileDialog, requestMeshImport, splitMeshFiles } from "./state/meshImportStore"; import { formatMeshReport, isMeshFile } from "./io/meshImport"; import { projectGeoOrigin } from "./model/geoRebase"; -import { applyClashMarkers, runClashCheck } from "./analysis/clash"; +import { clashMarkerOps, runClashCheck } from "./analysis/clash"; import { checkForUpdate } from "./update/checkForUpdate"; import type { PlanViewHandle } from "./views/plan/PlanView"; import type { DisplayResolver } from "./viewport/Viewport3D"; @@ -157,9 +157,9 @@ import { usePanelHostBase } from "./state/usePanelHostBase"; import { useDockDragState } from "./state/useDockDragState"; import { useMouseSelectionHandlers } from "./state/useMouseSelectionHandlers"; import { activeGroupOps, addNewElementsToActiveGroup, containingGroupId, EMPTY_MEMBERSHIP } from "./state/groupActions"; -import { isOpsMutation, opsMutation, removeItems } from "./core"; +import { addItems, fieldOps, isOpsMutation, opsMutation, patchItem, patchItems, removeItems, replaceItem, replaceWithMany, setFieldIfChanged } from "./core"; import type { GroupMembership, MemberKind } from "./state/groupActions"; -import { isLocked, setLockedForMembers } from "./state/objectLock"; +import { isLocked, lockMembersOps } from "./state/objectLock"; import { useProjectFileActions } from "./state/useProjectFileActions"; import { useProjectActions } from "./state/useProjectActions"; import { @@ -202,7 +202,7 @@ import { unionDrawings, } from "./editors/booleanOps"; import type { BooleanResult } from "./editors/booleanOps"; -import { applyDrawingStyle, readDrawingStyle } from "./editors/matchProps"; +import { applyDrawingStyleOps, readDrawingStyle } from "./editors/matchProps"; // Globaler Store (Slices: project/selection/view/layout). import { useStore } from "./state/appStore"; @@ -1333,13 +1333,11 @@ export default function App() { if (ids.length === 0) return; const idSet = new Set(ids); const newIds: string[] = []; - setProject((p) => { - const out: typeof p.drawings2d = []; + applyChange((p) => { + newIds.length = 0; + const replacements = new Map(); for (const d of p.drawings2d) { - if (!idSet.has(d.id)) { - out.push(d); - continue; - } + if (!idSet.has(d.id)) continue; const others: PolyForm[] = []; for (const o of p.drawings2d) { if (o.id === d.id || o.levelId !== d.levelId) continue; @@ -1348,9 +1346,10 @@ export default function App() { } const pieces = splitDrawing(d, others); for (const piece of pieces) newIds.push(piece.id); - out.push(...pieces); + replacements.set(d.id, pieces); } - return { ...p, drawings2d: out }; + // Jedes Quell-Drawing wird an derselben Stelle durch seine Teile ersetzt. + return replaceWithMany(p, "drawings2d", replacements); }); setSelectedDrawingIds(newIds); setSelectedWallIds([]); @@ -1389,13 +1388,7 @@ export default function App() { const result = op(srcs); if (result.replacedIds.length === 0) return; // <2 geschlossene → No-op const replaced = new Set(result.replacedIds); - setProject((p) => ({ - ...p, - drawings2d: [ - ...p.drawings2d.filter((d) => !replaced.has(d.id)), - ...result.created, - ], - })); + applyChange((p) => [...removeItems(p, "drawings2d", replaced), ...addItems("drawings2d", result.created)]); setSelectedDrawingIds(result.created.map((d) => d.id)); setSelectedWallIds([]); }; @@ -1410,7 +1403,7 @@ export default function App() { }; const pasteDrawingStyle = () => { if (!drawingStyleClipboard || selectedDrawingIds.length === 0) return; - setProject((p) => applyDrawingStyle(p, selectedDrawingIds, drawingStyleClipboard)); + applyChange((p) => applyDrawingStyleOps(p, selectedDrawingIds, drawingStyleClipboard)); }; // Objekt sperren/entsperren (Kontextmenü) — wirkt auf die GANZE aktuelle @@ -1436,7 +1429,7 @@ export default function App() { selectionLockIds.every(([kind, id]) => isLocked(project, kind, id)); const toggleSelectionLock = () => { if (selectionLockIds.length === 0) return; - setProject((p) => setLockedForMembers(p, selectionLockMembers, !selectionAllLocked)); + applyChange((p) => lockMembersOps(p, selectionLockMembers, !selectionAllLocked)); }; // Ebene(n) der Auswahl ausblenden / isolieren (Kontextmenü). Nur bei geöffnetem @@ -1456,12 +1449,12 @@ export default function App() { const hideSelectionLayers = () => { if (selectionLayerCodes.length === 0) return; const codes = new Set(selectionLayerCodes); - setProject((p) => ({ ...p, layers: setCategoriesVisible(p.layers, codes, false) })); + applyChange((p) => fieldOps(p, "layers", setCategoriesVisible(p.layers, codes, false))); }; const isolateSelectionLayers = () => { if (selectionLayerCodes.length === 0) return; const codes = new Set(selectionLayerCodes); - setProject((p) => ({ ...p, layers: isolateCategories(p.layers, codes) })); + applyChange((p) => fieldOps(p, "layers", isolateCategories(p.layers, codes))); }; // „Nicht drucken"/„Drucken" (Kontextmenü) — nur `Drawing2D` kennt @@ -1473,12 +1466,7 @@ export default function App() { const toggleSelectionNoPrint = () => { if (selectedDrawingIds.length === 0) return; const next = !selectionAllNoPrint; - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => - selectedDrawingIds.includes(d.id) ? { ...d, noPrint: next } : d, - ), - })); + applyChange((p) => patchItems(p, "drawings2d", selectedDrawingIds, (d) => ({ ...d, noPrint: next }))); }; // Ctrl/Cmd+G / Ctrl/Cmd+Shift+G = Gruppieren/Auflösen (Vectorworks-artig, @@ -1567,18 +1555,17 @@ export default function App() { const edgeIndex = nearestEdgeIndex(src.geom, model); if (edgeIndex === null) return; let removed = false; - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.flatMap((d) => { - if (d.id !== drawingId) return [d]; - const next = cutSegment(d, edgeIndex); - if (next === null) { - removed = true; - return []; - } - return [next]; - }), - })); + applyChange((p) => { + removed = false; + const d = p.drawings2d.find((x) => x.id === drawingId); + if (!d) return []; + const next = cutSegment(d, edgeIndex); + if (next === null) { + removed = true; + return removeItems(p, "drawings2d", [drawingId]); + } + return [replaceItem("drawings2d", next)]; + }); if (removed) setSelectedDrawingIds([]); }; @@ -1721,7 +1708,7 @@ export default function App() { moveRoomStamp, setRoomStampDoc, setRoomStamp, - } = useProjectActions(setProject, notify, planViewRef); + } = useProjectActions(applyChange, notify, planViewRef); // IFC-Import: erst die Wahl Mesh/Bauteile (`IfcImportDialog`), dann [B3] Kontext-Meshes // (`io/ifcImport.ts`) oder [B4] echte Bauteile (`io/ifcElements.ts`, übernommen über setProject). @@ -2483,7 +2470,7 @@ export default function App() { const p0 = project; runClashCheck(p0) .then((clashes) => { - setProject((p) => applyClashMarkers(p, clashes, activeCategoryCode)); + applyChange((p) => clashMarkerOps(p, clashes, activeCategoryCode)); // window.alert ist im Tauri-WKWebView wirkungslos → Toast. notify( clashes.length === 0 @@ -2714,13 +2701,7 @@ export default function App() { ? (project.layouts ?? []).find((l) => l.id === activeLayoutId) : undefined; const patchOpenLayout = (id: string, fn: (l: Layout) => Layout, coalesceKey?: string) => - setProject( - (p) => ({ - ...p, - layouts: (p.layouts ?? []).map((l) => (l.id === id ? fn(l) : l)), - }), - coalesceKey, - ); + applyChange((p) => patchItem(p, "layouts", id, fn), coalesceKey); // ── Effektive Darstellung für die Hauptansicht ──────────────────────────── // 3D: Geschosse nach dem Modus des Zeichnungsebenen-Panels, Kategorien nach @@ -2793,10 +2774,7 @@ export default function App() { // hält es (falls offen) synchron zu den betroffenen Feldern, wendet dessen // Befehle auf die echten Setter an (siehe native/settingsWindow.ts). const setScaleLineWeights = (on: boolean) => - setProject((p) => { - const { scaleLineWeights: _old, ...rest } = p; - return on ? { ...rest, scaleLineWeights: true } : rest; - }); + applyChange((p) => setFieldIfChanged(p, "scaleLineWeights", on ? true : undefined)); useSettingsWindowHost( { themeMode, @@ -2811,8 +2789,7 @@ export default function App() { onThemeModeChange: setThemeMode, onMarqueeColorChange: setMarqueeColor, onSnapColorChange: setSnapColor, - onReferenceElevationChange: (n) => - setProject((p) => ({ ...p, referenceElevationMasl: n })), + onReferenceElevationChange: (n) => applyChange((p) => setFieldIfChanged(p, "referenceElevationMasl", n)), onScaleLineWeightsChange: setScaleLineWeights, onOfflineChange, onApplyLayout: (l) => setLayout(reconcileLayout(l)), @@ -2841,7 +2818,7 @@ export default function App() { // Standort-Import als eigenes natives Fenster — s. native/contextImportWindow.ts. useContextImportWindowHost(project.geoAnchor, { onImport: (objs) => addContextObjectsAndFit(objs as ContextObject[]), - onSetGeoAnchor: (anchor) => setProject((p) => ({ ...p, geoAnchor: anchor })), + onSetGeoAnchor: (anchor) => applyChange((p) => setFieldIfChanged(p, "geoAnchor", anchor)), }); // Zeichnungsebenen-Manager als eigenes natives Fenster (DOSSIER-Rhino- @@ -3182,6 +3159,7 @@ export default function App() { const baseHost = usePanelHostBase({ project, setProject, + applyChange, activeLevelId, setActiveLevelId, activeLevel, @@ -3527,14 +3505,7 @@ export default function App() { onPlanColorMode={setPlanColorMode} shadowsAvailable={activeLevel.kind === "elevation"} shadows={activeLevel.shadows ?? false} - onShadows={(v) => - setProject((p) => ({ - ...p, - drawingLevels: p.drawingLevels.map((z) => - z.id === activeLevel.id ? { ...z, shadows: v } : z, - ), - })) - } + onShadows={(v) => applyChange((p) => patchItem(p, "drawingLevels", activeLevel.id, { shadows: v }))} combos={{ // Ebenen-Kombinationen: Speichern = Snapshot des Layer-Baums → // localStorage; Laden = Map lesen → Sichtbarkeits-Flags anwenden. @@ -4040,9 +4011,7 @@ export default function App() { snapColor={snapColor} onSnapColorChange={setSnapColor} referenceElevationMasl={project.referenceElevationMasl} - onReferenceElevationChange={(n) => - setProject((p) => ({ ...p, referenceElevationMasl: n })) - } + onReferenceElevationChange={(n) => applyChange((p) => setFieldIfChanged(p, "referenceElevationMasl", n))} scaleLineWeights={project.scaleLineWeights === true} onScaleLineWeightsChange={setScaleLineWeights} offline={offline} diff --git a/src/analysis/clash.test.ts b/src/analysis/clash.test.ts index cd820220..b330e91d 100644 --- a/src/analysis/clash.test.ts +++ b/src/analysis/clash.test.ts @@ -1,6 +1,11 @@ import { describe, expect, it } from "vitest"; import { sampleProject } from "../model/sampleProject"; -import { applyClashMarkers, candidatePairs, clashItems, CLASH_MARKER_PREFIX } from "./clash"; +import { candidatePairs, clashItems, clashMarkerOps, CLASH_MARKER_PREFIX } from "./clash"; +import { applyOps } from "../core/ops"; +import type { Project } from "../model/types"; +import type { Clash } from "./clash"; + +const applyClashMarkers = (p: Project, clashes: Clash[], cat: string) => applyOps(p, clashMarkerOps(p, clashes, cat)); import type { ClashItem } from "./clash"; const it0 = (id: string, kind: ClashItem["kind"]): ClashItem => ({ id, kind, spec: { kind: "cuboid", min: [0, 0, 0], max: [1, 1, 1] } }); diff --git a/src/analysis/clash.ts b/src/analysis/clash.ts index 09c5aa48..2468fa72 100644 --- a/src/analysis/clash.ts +++ b/src/analysis/clash.ts @@ -7,6 +7,8 @@ // macht daraus rote Markierungen (Kreis + Text, nicht druckend) auf dem passenden Geschoss. import type { Drawing2D, Project, Vec2 } from "../model/types"; +import { addItems, removeItems } from "../core/opsBuild"; +import type { CoreOp } from "../core/ops"; import { getFloor } from "../model/types"; import { projectToModel3d } from "../plan/toWalls3d"; import { extrudedSolidSpec } from "../plan/extrudedSolidSpec"; @@ -152,8 +154,7 @@ export function floorAtElevation(project: Project, z: number): string | null { } /** Ersetzt alte Kollisions-Marker durch neue (Kreis + Beschriftung, rot, nicht druckend). */ -export function applyClashMarkers(project: Project, clashes: Clash[], categoryCode: string): Project { - const keep = project.drawings2d.filter((d) => !d.id.startsWith(CLASH_MARKER_PREFIX)); +export function clashMarkerOps(project: Project, clashes: Clash[], categoryCode: string): CoreOp[] { const markers: Drawing2D[] = []; clashes.forEach((c, k) => { const levelId = floorAtElevation(project, c.center[2]); @@ -168,5 +169,9 @@ export function applyClashMarkers(project: Project, clashes: Clash[], categoryCo geom: { shape: "text", at: { x: at.x + 0.45, y: at.y + 0.1 }, text: `K${k + 1}${vol}`, height: 0.2, angle: 0 }, }); }); - return { ...project, drawings2d: [...keep, ...markers] }; + // Frühere Marken raus, neue hinten dran. + return [ + ...removeItems(project, "drawings2d", (d) => d.id.startsWith(CLASH_MARKER_PREFIX)), + ...addItems("drawings2d", markers), + ]; } diff --git a/src/core/extra.ts b/src/core/extra.ts index 9c8a5556..3e9726d2 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -50,5 +50,5 @@ export { readPdfVectorPage, pdfPageToImport, pdfPageInfo, pdfMetersPerPt, isPdfF export type { PdfVectorPage, PdfVectorPath, PdfVectorText } from "../io/pdfVector"; export { readMesh, meshObjectsToImportedMeshes, formatMeshReport, isMeshFile, MESH_UNITS, MESH_UNIT_SCALE } from "../io/meshImport"; export type { MeshObject, MeshImportReport, MeshUnit, MeshUp, MeshPlacement } from "../io/meshImport"; -export { addItems, fieldOps, findItem, isOpsMutation, itemsOf, opsMutation, patchItem, patchItems, removeItems, replaceItem, setField, setFieldIfChanged } from "./opsBuild"; +export { addItems, fieldOps, findItem, isOpsMutation, itemsOf, opsMutation, patchItem, patchItems, removeItems, replaceItem, replaceWithMany, setField, setFieldIfChanged } from "./opsBuild"; export type { EntityCollection, EntityOf, ProjectMutation } from "./opsBuild"; diff --git a/src/core/opsBuild.test.ts b/src/core/opsBuild.test.ts index 083aa8c3..8a453988 100644 --- a/src/core/opsBuild.test.ts +++ b/src/core/opsBuild.test.ts @@ -11,6 +11,7 @@ import { patchItem, patchItems, removeItems, + replaceWithMany, setField, setFieldIfChanged, } from "./opsBuild"; @@ -83,6 +84,27 @@ describe("Op-Bauhelfer", () => { expect(findItem(sampleProject, "walls", first)).toBe(sampleProject.walls[0]); }); + it("replaceWithMany = flatMap über die Liste (Teile an der Stelle des Originals), Zufall", () => { + for (let seed = 1; seed <= 300; seed++) { + const p = project(seed); + const r = rng(seed + 7); + const map = new Map(); + for (const w of p.walls) { + const k = r(); + if (k < 0.25) map.set(w.id, []); // entfernen + else if (k < 0.5) map.set(w.id, [{ ...w, id: `${w.id}a` }, { ...w, id: `${w.id}b`, height: 9 }]); // teilen + else if (k < 0.6) map.set(w.id, [w]); // unverändert + else if (k < 0.7) map.set(w.id, [{ ...w, height: 1 }]); // ersetzen + } + const expected = { ...p, walls: p.walls.flatMap((w) => map.get(w.id) ?? [w]) }; + const out = applyOps(p, replaceWithMany(p, "walls", map)); + expect(out.walls).toEqual(expected.walls); + // Unveränderte Elemente behalten ihre Identität. + for (const w of p.walls) if (!map.has(w.id) || map.get(w.id)![0] === w) expect(out.walls.includes(w)).toBe(true); + } + expect(replaceWithMany(project(1), "walls", new Map())).toEqual([]); + }); + it("setField / setFieldIfChanged", () => { expect(setField("name", "X")).toEqual({ kind: "setField", key: "name", value: "X" }); expect(setField("geoAnchor", undefined)).toEqual({ kind: "setField", key: "geoAnchor" }); diff --git a/src/core/opsBuild.ts b/src/core/opsBuild.ts index 81005b91..841c6e66 100644 --- a/src/core/opsBuild.ts +++ b/src/core/opsBuild.ts @@ -105,6 +105,37 @@ export function removeItems( return drop.length ? [{ kind: "remove", collection, ids: drop }] : []; } +/** + * Ersetzt Elemente durch je eine Liste neuer Elemente AN DERSELBEN STELLE (Zeichenreihenfolge bleibt; + * leere Liste = Element entfernen). Ein Eintrag, der nur das Original selbst enthält (gleiche + * Referenz), ändert nichts. Ein `remove` für alle ersetzten, danach je ein `add` an der Endposition + * (aufsteigend), sodass `applyOps` die Liste so liefert, als wäre sie in einem Zug neu aufgebaut worden. + */ +export function replaceWithMany( + p: Project, + collection: K, + replacements: ReadonlyMap[]>, +): CoreOp[] { + const dropped: string[] = []; + const inserts: { at: number; items: readonly EntityOf[] }[] = []; + let len = 0; // Länge der Liste nach dem Entfernen = Position im Ergebnis + for (const e of itemsOf(p, collection)) { + const id = (e as { id: string }).id; + const items = replacements.get(id); + if (items === undefined || (items.length === 1 && items[0] === e)) { + len++; + continue; + } + dropped.push(id); + if (items.length > 0) inserts.push({ at: len, items }); + len += items.length; + } + if (dropped.length === 0) return []; + const ops: CoreOp[] = [{ kind: "remove", collection, ids: dropped }]; + for (const ins of inserts) ops.push(...addItems(collection, ins.items, ins.at)); + return ops; +} + /** Setzt ein Projekt-Feld (`undefined` ⇒ Feld entfernen). */ export function setField(key: K, value: Project[K] | undefined): CoreOp { return value === undefined ? { kind: "setField", key } : { kind: "setField", key, value }; diff --git a/src/editors/explode.ts b/src/editors/explode.ts index 6eddb3cb..e67954fe 100644 --- a/src/editors/explode.ts +++ b/src/editors/explode.ts @@ -16,7 +16,7 @@ // unverändert stehen. Ebenso alles, was kein 2D-Element ist. import type { Drawing2D, Drawing2DGeom, Project, Vec2 } from "../model/types"; -import { bulgeArc, addItems } from "../core"; +import { bulgeArc, replaceWithMany } from "../core"; import type { CoreOp } from "../core"; import { uniqueId } from "../tools/types"; @@ -124,25 +124,13 @@ function mapPoints(geom: Drawing2DGeom, fn: (p: Vec2) => Vec2): Drawing2DGeom { */ export function explodeOps(project: Project, ids: readonly string[]): CoreOp[] { const wanted = new Set(ids); - 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 + const replacements = new Map(); for (const d of project.drawings2d) { const parts = wanted.has(d.id) ? explodeGeom(d.geom, project) : null; - if (!parts || parts.length === 0) { - len++; - continue; - } - dropped.push(d.id); + if (!parts || parts.length === 0) continue; // 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; + replacements.set(d.id, parts.map((geom): Drawing2D => ({ ...d, id: uniqueId("dr2d"), geom }))); } - 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; + return replaceWithMany(project, "drawings2d", replacements); } diff --git a/src/editors/matchProps.test.ts b/src/editors/matchProps.test.ts index ae813f91..b4976c08 100644 --- a/src/editors/matchProps.test.ts +++ b/src/editors/matchProps.test.ts @@ -1,10 +1,15 @@ /** „Eigenschaften übertragen" für 2D-Elemente. */ import { describe, expect, it } from "vitest"; -import { applyDrawingStyle, readDrawingStyle } from "./matchProps"; +import { applyDrawingStyleOps, readDrawingStyle } from "./matchProps"; +import type { DrawingStyle } from "./matchProps"; +import { applyOps } from "../core/ops"; + import { sampleProject } from "../model/sampleProject"; import type { Drawing2D, Project } from "../model/types"; +const applyDrawingStyle = (p: Project, ids: string[], style: DrawingStyle) => applyOps(p, applyDrawingStyleOps(p, ids, style)); + function proj(...ds: Partial[]): Project { return { ...sampleProject, diff --git a/src/editors/matchProps.ts b/src/editors/matchProps.ts index d5419a48..8b3f9b81 100644 --- a/src/editors/matchProps.ts +++ b/src/editors/matchProps.ts @@ -12,6 +12,8 @@ // sie mitnehmen wollte, verschöbe das Element ungewollt in eine andere Ebene. import type { Drawing2D, Project } from "../model/types"; +import { patchItems } from "../core"; +import type { CoreOp } from "../core"; /** Die übertragbaren Stil-Felder eines 2D-Elements. */ export type DrawingStyle = Pick< @@ -84,19 +86,15 @@ export function readDrawingStyle(d: Drawing2D): DrawingStyle { * Ortsbezug (ein Ankerpunkt im Modell), kein Aussehen — am Ziel läge das * Muster sonst an einer sinnlosen Stelle. */ -export function applyDrawingStyle(project: Project, ids: string[], style: DrawingStyle): Project { +export function applyDrawingStyleOps(project: Project, ids: string[], style: DrawingStyle): CoreOp[] { const wanted = new Set(ids); - if (wanted.size === 0) return project; - return { - ...project, - drawings2d: project.drawings2d.map((d) => { - if (!wanted.has(d.id)) return d; - const next: Record = { ...d }; - for (const k of STYLE_KEYS) { - if (style[k] === undefined) delete next[k]; - else next[k] = style[k]; - } - return next as unknown as Drawing2D; - }), - }; + if (wanted.size === 0) return []; + return patchItems(project, "drawings2d", wanted, (d) => { + const next: Record = { ...d }; + for (const k of STYLE_KEYS) { + if (style[k] === undefined) delete next[k]; + else next[k] = style[k]; + } + return next as unknown as Drawing2D; + }); } diff --git a/src/state/objectLock.test.ts b/src/state/objectLock.test.ts index 4ed2ef46..c9d993bd 100644 --- a/src/state/objectLock.test.ts +++ b/src/state/objectLock.test.ts @@ -3,9 +3,15 @@ import { describe, it, expect } from "vitest"; import { sampleProject } from "../model/sampleProject"; -import { isLocked, setLocked, setLockedForMembers } from "./objectLock"; +import { isLocked, lockMembersOps, lockOps } from "./objectLock"; +import type { MemberKind } from "./groupActions"; +import { applyOps } from "../core/ops"; import type { Project, Wall, Drawing2D } from "../model/types"; +const setLocked = (p: Project, kind: MemberKind, id: string, locked: boolean) => applyOps(p, lockOps(p, kind, id, locked)); +const setLockedForMembers = (p: Project, m: Partial>, locked: boolean) => + applyOps(p, lockMembersOps(p, m, locked)); + const wall: Wall = { id: "w1", type: "wall", diff --git a/src/state/objectLock.ts b/src/state/objectLock.ts index b8e97731..024aa7dc 100644 --- a/src/state/objectLock.ts +++ b/src/state/objectLock.ts @@ -11,6 +11,8 @@ // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import type { Project } from "../model/types"; +import { patchItem } from "../core"; +import type { CoreOp } from "../core"; import type { MemberKind } from "./groupActions"; /** Ist das Element (Art + ID) gesperrt? `false` für unbekannte/fehlende IDs. */ @@ -35,40 +37,25 @@ export function isLocked(project: Project, kind: MemberKind, id: string): boolea } } -/** Setzt die Sperre eines Elements (immutabel); unbekannte IDs sind ein No-Op. */ -export function setLocked(project: Project, kind: MemberKind, id: string, locked: boolean): Project { +/** Ops: setzt die Sperre eines Elements; unbekannte IDs sind ein No-Op (keine Ops). */ +export function lockOps(project: Project, kind: MemberKind, id: string, locked: boolean): CoreOp[] { switch (kind) { case "wallIds": - return { ...project, walls: project.walls.map((w) => (w.id === id ? { ...w, locked } : w)) }; + return patchItem(project, "walls", id, { locked }); case "drawingIds": - return { - ...project, - drawings2d: project.drawings2d.map((d) => (d.id === id ? { ...d, locked } : d)), - }; + return patchItem(project, "drawings2d", id, { locked }); case "ceilingIds": - return { - ...project, - ceilings: (project.ceilings ?? []).map((c) => (c.id === id ? { ...c, locked } : c)), - }; + return patchItem(project, "ceilings", id, { locked }); case "roomIds": - return { ...project, rooms: (project.rooms ?? []).map((r) => (r.id === id ? { ...r, locked } : r)) }; + return patchItem(project, "rooms", id, { locked }); case "stairIds": - return { - ...project, - stairs: (project.stairs ?? []).map((s) => (s.id === id ? { ...s, locked } : s)), - }; + return patchItem(project, "stairs", id, { locked }); case "columnIds": - return { - ...project, - columns: (project.columns ?? []).map((c) => (c.id === id ? { ...c, locked } : c)), - }; + return patchItem(project, "columns", id, { locked }); case "roofIds": - return { ...project, roofs: (project.roofs ?? []).map((r) => (r.id === id ? { ...r, locked } : r)) }; + return patchItem(project, "roofs", id, { locked }); case "openingIds": - return { - ...project, - openings: (project.openings ?? []).map((o) => (o.id === id ? { ...o, locked } : o)), - }; + return patchItem(project, "openings", id, { locked }); } } @@ -77,16 +64,14 @@ export function setLocked(project: Project, kind: MemberKind, id: string, locked * Zug (ein Undo-Schritt für "Auswahl sperren/entsperren", nicht einer je * Element). Reihenfolge/Struktur wie `MemberKind` — jedes Feld optional. */ -export function setLockedForMembers( +export function lockMembersOps( project: Project, members: Partial>, locked: boolean, -): Project { - let next = project; +): CoreOp[] { + const ops: CoreOp[] = []; for (const kind of Object.keys(members) as MemberKind[]) { - for (const id of members[kind] ?? []) { - next = setLocked(next, kind, id, locked); - } + for (const id of members[kind] ?? []) ops.push(...lockOps(project, kind, id, locked)); } - return next; + return ops; } diff --git a/src/state/panelOps.test.ts b/src/state/panelOps.test.ts new file mode 100644 index 00000000..9b7edd19 --- /dev/null +++ b/src/state/panelOps.test.ts @@ -0,0 +1,198 @@ +// Typ-CRUD (`useProjectActions`) und Panel-Aktionen (`usePanelHostBase`) liefern ihre Änderung als Ops +// ([K4] S3): „applyOps(vorher, Ops) == erwartetes Ergebnis". Beim Umbau wurden dieselben Schritte +// gegen die alte setProject-Fassung (git HEAD) verglichen: Typ-CRUD und 46 Panel-Aktionen, gleich. +// Die Hooks laufen hier über `renderToString` (kein DOM nötig) und geben ihre Closures heraus. +import { describe, expect, it } from "vitest"; +import { createElement } from "react"; +import { renderToString } from "react-dom/server"; +import { sampleProject } from "../model/sampleProject"; +import type { Project } from "../model/types"; +import { applyOps } from "../core/ops"; +import type { CoreOp } from "../core/ops"; +import { useProjectActions } from "./useProjectActions"; +import { usePanelHostBase } from "./usePanelHostBase"; + +/* eslint-disable @typescript-eslint/no-explicit-any */ +function capture(f: () => T): T { + let out: T | undefined; + renderToString( + createElement(() => { + out = f(); + return null; + }), + ); + return out as T; +} + +/** Platzhalter für die vielen Zustandsfelder, die die getesteten Aktionen nicht anfassen. */ +function deepStub(): any { + const fn = function () { + return undefined; + }; + return new Proxy(fn, { + get: (_t, k) => (k === Symbol.toPrimitive ? () => "" : k === "then" ? undefined : deepStub()), + apply: () => undefined, + }); +} +function stubObj(over: Record): any { + return new Proxy(over, { + get: (t, k) => (k in t ? (t as any)[k] : typeof k === "symbol" ? undefined : deepStub()), + }); +} + +/** Zustandshalter: Ops anwenden wie der Store. */ +function holder(start: Project) { + const h = { + p: start, + notes: [] as string[], + applyChange: (c: readonly CoreOp[] | ((p: Project) => readonly CoreOp[])) => { + h.p = applyOps(h.p, typeof c === "function" ? c(h.p) : c); + }, + }; + return h; +} + +describe("useProjectActions: Typ-CRUD über Ops", () => { + it("Anlegen, Ändern, geschütztes Löschen, Stil speichern", () => { + const h = holder({ ...sampleProject, doorTypes: [], windowTypes: [], stairTypes: [], roofTypes: [] }); + const a = capture(() => useProjectActions(h.applyChange, (m) => h.notes.push(m), { current: null })); + const wt = h.p.wallTypes[0].id; + const nWall = h.p.wallTypes.length; + + a.addWallType(); + expect(h.p.wallTypes).toHaveLength(nWall + 1); + expect(h.p.wallTypes[nWall].layers).toHaveLength(1); + a.patchWallType(wt, { name: "Neu" }); + expect(h.p.wallTypes[0].name).toBe("Neu"); + a.deleteWallType(wt); // wird von Wänden verwendet + expect(h.p.wallTypes).toHaveLength(nWall + 1); + expect(h.notes).toHaveLength(1); + a.deleteWallType(h.p.wallTypes[nWall].id); + expect(h.p.wallTypes).toHaveLength(nWall); + + a.addDoorType(); + a.addWindowType(); + a.addStairType(); + a.addRoofType(); + a.addCeilingType(); + expect([h.p.doorTypes!.length, h.p.windowTypes!.length, h.p.stairTypes!.length, h.p.roofTypes!.length]).toEqual([1, 1, 1, 1]); + a.patchDoorType(h.p.doorTypes![0].id, { name: "T" }); + expect(h.p.doorTypes![0].name).toBe("T"); + + const opening = (h.p.openings ?? [])[0]; + if (opening) { + a.saveOpeningStyle(opening.id, "Mein Stil"); + const after = h.p.openings!.find((o) => o.id === opening.id)!; + const list = opening.kind === "door" ? h.p.doorTypes! : h.p.windowTypes!; + expect(list.some((t) => t.id === after.typeId && t.name === "Mein Stil")).toBe(true); + } + + a.setOverrideRules([]); + expect(h.p.overrideRules).toEqual([]); + a.deleteDoorType(h.p.doorTypes![0].id); + expect(h.p.doorTypes!.some((d) => d.name === "T")).toBe(false); + }); +}); + +const L0 = sampleProject.drawingLevels[0].id; +const base: Project = { + ...sampleProject, + columns: [ + { id: "col1", type: "column", floorId: L0, categoryCode: "20", position: { x: 1, y: 1 }, height: 3, rotation: 0, profile: { kind: "rect", width: 0.3, depth: 0.3 } }, + { id: "col2", type: "column", floorId: L0, categoryCode: "20", position: { x: 3, y: 1 }, height: 3, rotation: 0, profile: { kind: "round", radius: 0.2 } }, + ] as any, + extrudedSolids: [{ id: "ex1", type: "extrudedSolid", levelId: L0, points: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }], height: 1 }] as any, + context: [{ id: "img1", type: "image", min: { x: 0, y: 0 }, max: { x: 1, y: 1 }, opacity: 1 }] as any, + viewSnapshots: [{ id: "vs-1", name: "A", state: {} }, { id: "vs-2", name: "B", state: {} }] as any, + viewSnapshotFolders: [{ id: "vsf-1", name: "F" }] as any, + layouts: [{ id: "lay-1", name: "L1", masterId: "mas-1" }, { id: "lay-2", name: "L2" }] as any, + masterLayouts: [{ id: "mas-1", name: "M1" }] as any, + layoutFolders: [{ id: "folder-1", name: "LF" }, { id: "mfolder-1", name: "MF", kind: "master" }] as any, +}; + +function host(h: ReturnType, selection: any) { + (globalThis as any).requestAnimationFrame = () => 0; + return capture(() => + usePanelHostBase({ + project: h.p, + setProject: (n: any) => { + h.p = typeof n === "function" ? n(h.p) : n; + }, + applyChange: h.applyChange, + activeLevelId: L0, + setActiveLevelId: () => {}, + setViewType: () => {}, + activeLevel: sampleProject.drawingLevels[0], + viewType: "grundriss", + selection, + projectActions: stubObj({ snapshotLayerVisibility: () => ({}), snapshotDrawingVisibility: () => ({}), applyLayerVisibility: () => {}, applyDrawingVisibility: () => {} }), + selectionState: stubObj({ selectedContextObjectIds: [] }), + toolState: stubObj({}), + topBarState: stubObj({}), + dialogState: stubObj({ setActiveLayoutId: () => {} }), + contextMenuState: stubObj({}), + engineView: { commandName: null }, + planViewRef: { current: null }, + dxfInputRef: { current: null }, + activeLayout: undefined, + patchOpenLayout: () => {}, + } as any), + ) as any; +} + +describe("usePanelHostBase: Panel-Aktionen über Ops", () => { + it("Stützen, Extrusionen, Kontext-Bild", () => { + const h = holder(base); + host(h, { kind: "column", id: "col1" }).onSetColumnWidth(0.5); + expect((h.p.columns![0].profile as any).width).toBe(0.5); + host(h, { kind: "column", id: "col2" }).onSetColumnWidth(0.5); // runde Stütze: keine Breite + expect(h.p.columns![1].profile).toEqual({ kind: "round", radius: 0.2 }); + host(h, { kind: "column", id: "col1" }).onSetColumnProfileKind("round"); + expect(h.p.columns![0].profile).toEqual({ kind: "round", radius: 0.25 }); + host(h, { kind: "column", id: "col1" }).onSetColumnRotation(90); + expect(h.p.columns![0].rotation).toBeCloseTo(Math.PI / 2, 12); + host(h, { kind: "column", id: "col1" }).onSetSelectionLevel("og"); + expect(h.p.columns![0].floorId).toBe("og"); + expect(h.p.columns![1]).toBe(base.columns![1]); // unberührt: gleiche Referenz + host(h, { kind: "extrudedSolid", id: "ex1" }).onSetExtrudedSolidHeight(2.5); + host(h, { kind: "extrudedSolid", id: "ex1" }).onSetExtrudedSolidSubtract(true); + expect(h.p.extrudedSolids![0]).toMatchObject({ height: 2.5, operation: "subtract" }); + host(h, { kind: "contextObject", id: "img1" }).onSetSelectionOpacity(0.4); + expect((h.p.context![0] as any).opacity).toBe(0.4); + host(h, null).onSetGeoAnchor({ lv95: { e: 1, n: 2 }, model: { x: 0, y: 0 } }); + expect(h.p.geoAnchor).toEqual({ lv95: { e: 1, n: 2 }, model: { x: 0, y: 0 } }); + }); + + it("Ausschnitte und Ordner", () => { + const h = holder(base); + const a = host(h, null); + a.onRenameViewSnapshot("vs-1", " Neu A "); + expect(h.p.viewSnapshots![0].name).toBe("Neu A"); + a.onMoveViewSnapshotToFolder("vs-2", "vsf-1"); + expect((h.p.viewSnapshots![1] as any).folderId).toBe("vsf-1"); + const id = a.onCaptureViewSnapshot("Neu", "vsf-1"); + expect(h.p.viewSnapshots!.at(-1)!.id).toBe(id); + a.onDeleteViewSnapshot("vs-2"); + expect(h.p.viewSnapshots!.map((s) => s.id)).toEqual(["vs-1", id]); + a.onDeleteViewSnapshotFolder("vsf-1"); + expect(h.p.viewSnapshotFolders).toEqual([]); + }); + + it("Layouts, Masterlayouts, Layout-Ordner", () => { + const h = holder(base); + const a = host(h, null); + a.onRenameLayout("lay-2", "Z"); + expect(h.p.layouts![1].name).toBe("Z"); + a.onDeleteMasterLayout("mas-1"); // löst die Bindung der Layouts + expect(h.p.masterLayouts).toEqual([]); + expect(h.p.layouts![0].masterId).toBeUndefined(); + a.onDeleteLayout("lay-1"); + expect(h.p.layouts!.map((l) => l.id)).toEqual(["lay-2"]); + const id = a.onCreateLayout({ paper: "a4", orientation: "portrait", folderId: "folder-1" }); + expect(h.p.layouts!.at(-1)).toMatchObject({ id, folderId: "folder-1" }); + a.onMoveLayoutToFolder("lay-2", "folder-1"); + expect((h.p.layouts![0] as any).folderId).toBe("folder-1"); + a.onDeleteLayoutFolder("folder-1"); + expect(h.p.layoutFolders!.map((f) => f.id)).toEqual(["mfolder-1"]); + }); +}); diff --git a/src/state/usePanelHostBase.ts b/src/state/usePanelHostBase.ts index 1014dd91..e1c2e334 100644 --- a/src/state/usePanelHostBase.ts +++ b/src/state/usePanelHostBase.ts @@ -8,7 +8,8 @@ // Extrahiert aus App.tsx. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import { applyFillMode } from "./fillMode"; -import { opsMutation, patchItem } from "../core"; +import { addItems, fieldOps, opsMutation, patchItem, patchItems, removeItems, setFieldIfChanged } from "../core"; +import type { CoreOp } from "../core"; import { useMemo, type RefObject } from "react"; import type { DrawingLevel, Layout, Project } from "../model/types"; import { resolvePenColor } from "../model/penSets"; @@ -107,6 +108,8 @@ function captureCameraState( export function usePanelHostBase(opts: { project: Project; setProject: (updater: (p: Project) => Project) => void; + /** Änderung direkt als Ops ([K4] S3), s. `ProjectSlice.applyChange`. */ + applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[]), coalesceKey?: string) => void; activeLevelId: string; setActiveLevelId: (id: string) => void; activeLevel: DrawingLevel; @@ -226,6 +229,7 @@ export function usePanelHostBase(opts: { const { project, setProject, + applyChange, activeLevelId, setActiveLevelId, activeLevel, @@ -508,26 +512,20 @@ export function usePanelHostBase(opts: { patchAnnotationInLayout(l, selection.id, { opacity }), ); else if (selection?.kind === "contextObject") - setProject((p) => ({ - ...p, - context: (p.context ?? []).map((o) => - o.id === selection.id && o.type === "image" ? { ...o, opacity } : o, - ), - })); + applyChange((p) => + patchItem(p, "context", selection.id, (o) => (o.type === "image" ? { ...o, opacity } : o)), + ); }, onSetSelectionImageFilters: (filters) => { // Nur Kontext-Objekt-Bilder tragen `filters` (s. `ContextImage`) — // gemergt mit den bestehenden Werten (Teil-Update, ein Slider ändert // nur SEINEN eigenen Wert). if (selection?.kind !== "contextObject") return; - setProject((p) => ({ - ...p, - context: (p.context ?? []).map((o) => - o.id === selection.id && o.type === "image" - ? { ...o, filters: { ...o.filters, ...filters } } - : o, + applyChange((p) => + patchItem(p, "context", selection.id, (o) => + o.type === "image" ? { ...o, filters: { ...o.filters, ...filters } } : o, ), - })); + ); }, onSetSelectionForeground: (color) => { // Vordergrund-Override: Wand, Decke oder Drawing2D. @@ -708,12 +706,7 @@ export function usePanelHostBase(opts: { case "room": updateRoom(id, { categoryCode: code }); break; case "drawing2d": updateDrawing2D(id, { categoryCode: code }); break; case "column": - setProject((p) => ({ - ...p, - columns: (p.columns ?? []).map((c) => - c.id === id ? { ...c, categoryCode: code } : c, - ), - })); + applyChange((p) => patchItem(p, "columns", id, { categoryCode: code })); break; default: break; // extrudedSolid/door: keine Kategorie am Element } @@ -729,20 +722,10 @@ export function usePanelHostBase(opts: { case "room": updateRoom(id, { floorId: levelId }); break; case "drawing2d": updateDrawing2D(id, { levelId }); break; case "extrudedSolid": - setProject((p) => ({ - ...p, - extrudedSolids: (p.extrudedSolids ?? []).map((s) => - s.id === id ? { ...s, levelId } : s, - ), - })); + applyChange((p) => patchItem(p, "extrudedSolids", id, { levelId })); break; case "column": - setProject((p) => ({ - ...p, - columns: (p.columns ?? []).map((c) => - c.id === id ? { ...c, floorId: levelId } : c, - ), - })); + applyChange((p) => patchItem(p, "columns", id, { floorId: levelId })); break; default: break; // opening: Ebene kommt aus der Wirts-Wand } @@ -1003,74 +986,42 @@ export function usePanelHostBase(opts: { onSetExtrudedSolidHeight: (height) => { if (selection?.kind !== "extrudedSolid" || !(height > 0)) return; const id = selection.id; - setProject((p) => ({ - ...p, - extrudedSolids: (p.extrudedSolids ?? []).map((s) => - s.id === id ? { ...s, height } : s, - ), - })); + applyChange((p) => patchItem(p, "extrudedSolids", id, { height })); }, onSetExtrudedSolidTaper: (taper) => { if (selection?.kind !== "extrudedSolid") return; const clamped = Math.min(1, Math.max(0, taper)); const id = selection.id; - setProject((p) => ({ - ...p, - extrudedSolids: (p.extrudedSolids ?? []).map((s) => - s.id === id ? { ...s, taper: clamped } : s, - ), - })); + applyChange((p) => patchItem(p, "extrudedSolids", id, { taper: clamped })); }, onSetExtrudedSolidCornerRadius: (radius) => { if (selection?.kind !== "extrudedSolid") return; const r = Math.max(0, radius); const id = selection.id; - setProject((p) => ({ - ...p, - extrudedSolids: (p.extrudedSolids ?? []).map((s) => - s.id === id ? { ...s, cornerRadius: r > 0 ? r : undefined } : s, - ), - })); + applyChange((p) => patchItem(p, "extrudedSolids", id, { cornerRadius: r > 0 ? r : undefined })); }, onSetExtrudedSolidChamfer: (chamfer) => { if (selection?.kind !== "extrudedSolid") return; const c = Math.max(0, chamfer); const id = selection.id; - setProject((p) => ({ - ...p, - extrudedSolids: (p.extrudedSolids ?? []).map((s) => - s.id === id ? { ...s, chamfer: c > 0 ? c : undefined } : s, - ), - })); + applyChange((p) => patchItem(p, "extrudedSolids", id, { chamfer: c > 0 ? c : undefined })); }, onSetExtrudedSolidSubtract: (subtract) => { if (selection?.kind !== "extrudedSolid") return; const id = selection.id; - setProject((p) => ({ - ...p, - extrudedSolids: (p.extrudedSolids ?? []).map((s) => - s.id === id ? { ...s, operation: subtract ? ("subtract" as const) : undefined } : s, - ), - })); + applyChange((p) => patchItem(p, "extrudedSolids", id, { operation: subtract ? ("subtract" as const) : undefined })); }, onSetExtrudedSolidBaseOffset: (offset) => { if (selection?.kind !== "extrudedSolid" || !Number.isFinite(offset)) return; const id = selection.id; - setProject((p) => ({ - ...p, - extrudedSolids: (p.extrudedSolids ?? []).map((s) => - s.id === id ? { ...s, baseOffset: Math.abs(offset) > 1e-9 ? offset : undefined } : s, - ), - })); + applyChange((p) => patchItem(p, "extrudedSolids", id, { baseOffset: Math.abs(offset) > 1e-9 ? offset : undefined })); }, // ── Stützen-Attribute (Tragwerk; nur bei selektierter Stütze) ────────── onSetColumnProfileKind: (kind) => { if (selection?.kind !== "column") return; const id = selection.id; - setProject((p) => ({ - ...p, - columns: (p.columns ?? []).map((c) => { - if (c.id !== id) return c; + applyChange((p) => + patchItem(p, "columns", id, (c) => { if (kind === c.profile.kind) return c; // Profil-Typ wechseln: sinnvolles Mass aus dem bisherigen ableiten. if (kind === "round") { @@ -1078,65 +1029,50 @@ export function usePanelHostBase(opts: { c.profile.kind === "rect" ? Math.max(c.profile.width, c.profile.depth) / 2 : c.profile.radius; - return { ...c, profile: { kind: "round", radius: r } }; + return { ...c, profile: { kind: "round" as const, radius: r } }; } const side = c.profile.kind === "round" ? c.profile.radius * 2 : 0.3; - return { ...c, profile: { kind: "rect", width: side, depth: side } }; + return { ...c, profile: { kind: "rect" as const, width: side, depth: side } }; }), - })); + ); }, onSetColumnWidth: (width) => { if (selection?.kind !== "column" || !(width > 0)) return; const id = selection.id; - setProject((p) => ({ - ...p, - columns: (p.columns ?? []).map((c) => - c.id === id && c.profile.kind === "rect" - ? { ...c, profile: { ...c.profile, width } } - : c, + applyChange((p) => + patchItem(p, "columns", id, (c) => + c.profile.kind === "rect" ? { ...c, profile: { ...c.profile, width } } : c, ), - })); + ); }, onSetColumnDepth: (depth) => { if (selection?.kind !== "column" || !(depth > 0)) return; const id = selection.id; - setProject((p) => ({ - ...p, - columns: (p.columns ?? []).map((c) => - c.id === id && c.profile.kind === "rect" - ? { ...c, profile: { ...c.profile, depth } } - : c, + applyChange((p) => + patchItem(p, "columns", id, (c) => + c.profile.kind === "rect" ? { ...c, profile: { ...c.profile, depth } } : c, ), - })); + ); }, onSetColumnRadius: (radius) => { if (selection?.kind !== "column" || !(radius > 0)) return; const id = selection.id; - setProject((p) => ({ - ...p, - columns: (p.columns ?? []).map((c) => - c.id === id && c.profile.kind === "round" - ? { ...c, profile: { ...c.profile, radius } } - : c, + applyChange((p) => + patchItem(p, "columns", id, (c) => + c.profile.kind === "round" ? { ...c, profile: { ...c.profile, radius } } : c, ), - })); + ); }, onSetColumnHeight: (height) => { if (selection?.kind !== "column" || !(height > 0)) return; const id = selection.id; - setProject((p) => ({ - ...p, - columns: (p.columns ?? []).map((c) => (c.id === id ? { ...c, height } : c)), - })); + applyChange((p) => patchItem(p, "columns", id, { height })); }, onSetColumnRotation: (deg) => { if (selection?.kind !== "column" || !Number.isFinite(deg)) return; const id = selection.id; const rotation = (deg * Math.PI) / 180; - setProject((p) => ({ - ...p, - columns: (p.columns ?? []).map((c) => (c.id === id ? { ...c, rotation } : c)), - })); + applyChange((p) => patchItem(p, "columns", id, { rotation })); }, // ── Site-/Kontext-Schicht ────────────────────────────────────────────── contextObjects: project.context ?? [], @@ -1146,7 +1082,7 @@ export function usePanelHostBase(opts: { onRemoveContextObjects: removeContextObjects, onGenerateTerrain: generateTerrain, onSetGeoAnchor: (anchor) => { - setProject((p) => ({ ...p, geoAnchor: anchor })); + applyChange((p) => setFieldIfChanged(p, "geoAnchor", anchor)); }, onImportDxf: () => dxfInputRef.current?.click(), onStartGeoref: () => onRunCommand("georef"), @@ -1234,10 +1170,7 @@ export function usePanelHostBase(opts: { // Neuer Ausschnitt landet im aktiven Ordner (falls das Panel einen // mitgibt), sonst auf der Wurzelebene — additiv (folderId optional). const full = folderId ? { ...snap, folderId } : snap; - setProject((p) => ({ - ...p, - viewSnapshots: [...(p.viewSnapshots ?? []), full], - })); + applyChange(addItems("viewSnapshots", [full])); return full.id; }, @@ -1272,10 +1205,7 @@ export function usePanelHostBase(opts: { ...captureCameraState(planViewRef, viewType), }; const snap = captureViewSnapshot(`vs-${Date.now()}`, name, st); - setProject((p) => ({ - ...p, - viewSnapshots: [...(p.viewSnapshots ?? []), snap], - })); + applyChange(addItems("viewSnapshots", [snap])); setSelectedViewSnapshotId(snap.id); return snap.id; }, @@ -1298,13 +1228,9 @@ export function usePanelHostBase(opts: { setScaleDenominator(st.scaleDenominator); applyLayerVisibility(st.layerVisibility); applyDrawingVisibility(st.drawingVisibility); - setProject((p) => ({ - ...p, - overrideRules: applyOverrideRuleEnabled( - p.overrideRules ?? [], - st.enabledOverrideRuleIds, - ), - })); + applyChange((p) => + fieldOps(p, "overrideRules", applyOverrideRuleEnabled(p.overrideRules ?? [], st.enabledOverrideRuleIds)), + ); requestAnimationFrame(() => { planViewRef.current?.applyScale(st.scaleDenominator); // Kamera NACH `applyScale` restaurieren (nicht statt): `applyScale` @@ -1326,19 +1252,11 @@ export function usePanelHostBase(opts: { onRenameViewSnapshot: (id: string, name: string) => { const trimmed = name.trim(); if (!trimmed) return; - setProject((p) => ({ - ...p, - viewSnapshots: (p.viewSnapshots ?? []).map((s) => - s.id === id ? { ...s, name: trimmed } : s, - ), - })); + applyChange((p) => patchItem(p, "viewSnapshots", id, { name: trimmed })); }, onDeleteViewSnapshot: (id: string) => { - setProject((p) => ({ - ...p, - viewSnapshots: (p.viewSnapshots ?? []).filter((s) => s.id !== id), - })); + applyChange((p) => removeItems(p, "viewSnapshots", [id])); if (selectedViewSnapshotId === id) setSelectedViewSnapshotId(null); }, @@ -1352,51 +1270,31 @@ export function usePanelHostBase(opts: { t("viewsnap.folder.defaultName"), parentId, ); - setProject((p) => ({ - ...p, - viewSnapshotFolders: [...(p.viewSnapshotFolders ?? []), folder], - })); + applyChange(addItems("viewSnapshotFolders", [folder])); return id; }, onRenameViewSnapshotFolder: (id, name) => { const trimmed = name.trim(); if (!trimmed) return; - setProject((p) => ({ - ...p, - viewSnapshotFolders: (p.viewSnapshotFolders ?? []).map((f) => - f.id === id ? { ...f, name: trimmed } : f, - ), - })); + applyChange((p) => patchItem(p, "viewSnapshotFolders", id, { name: trimmed })); }, onDeleteViewSnapshotFolder: (id) => { - setProject((p) => { + applyChange((p) => { const { folders, snapshots } = deleteViewSnapshotFolder( id, p.viewSnapshotFolders ?? [], p.viewSnapshots ?? [], ); - return { ...p, viewSnapshotFolders: folders, viewSnapshots: snapshots }; + return [...fieldOps(p, "viewSnapshotFolders", folders), ...fieldOps(p, "viewSnapshots", snapshots)]; }); }, onMoveViewSnapshotToFolder: (snapshotId, folderId) => { - setProject((p) => ({ - ...p, - viewSnapshots: moveSnapshotToFolder( - p.viewSnapshots ?? [], - snapshotId, - folderId, - ), - })); + applyChange((p) => fieldOps(p, "viewSnapshots", moveSnapshotToFolder(p.viewSnapshots ?? [], snapshotId, folderId))); }, onMoveViewSnapshotFolder: (folderId, parentId) => { - setProject((p) => ({ - ...p, - viewSnapshotFolders: moveViewSnapshotFolder( - p.viewSnapshotFolders ?? [], - folderId, - parentId, - ), - })); + applyChange((p) => + fieldOps(p, "viewSnapshotFolders", moveViewSnapshotFolder(p.viewSnapshotFolders ?? [], folderId, parentId)), + ); }, // Footer-Bar des Ausschnitte-Panels: die aktuell „angewählte" Id plus @@ -1414,67 +1312,40 @@ export function usePanelHostBase(opts: { // Anlegen öffnet es direkt; Löschen schliesst es, falls es das offene trifft. onAddLayout: (name, paper, orientation) => { const lay = createLayout(`lay-${Date.now()}`, name, paper, orientation); - setProject((p) => ({ ...p, layouts: [...(p.layouts ?? []), lay] })); + applyChange(addItems("layouts", [lay])); setActiveLayoutId(lay.id); }, onRenameLayout: (id, name) => { - setProject((p) => ({ - ...p, - layouts: (p.layouts ?? []).map((l) => - l.id === id ? { ...l, name } : l, - ), - })); + applyChange((p) => patchItem(p, "layouts", id, { name })); }, onDeleteLayout: (id) => { - setProject((p) => ({ - ...p, - layouts: (p.layouts ?? []).filter((l) => l.id !== id), - })); + applyChange((p) => removeItems(p, "layouts", [id])); setActiveLayoutId((cur) => (cur === id ? null : cur)); }, onOpenLayout: (id) => setActiveLayoutId(id), onAddMasterLayout: (name) => { const m = createMasterLayout(`mas-${Date.now()}`, name, "a4", "portrait"); - setProject((p) => ({ - ...p, - masterLayouts: [...(p.masterLayouts ?? []), m], - })); + applyChange(addItems("masterLayouts", [m])); }, onRenameMasterLayout: (id, name) => { - setProject((p) => ({ - ...p, - masterLayouts: (p.masterLayouts ?? []).map((m) => - m.id === id ? { ...m, name } : m, - ), - })); + applyChange((p) => patchItem(p, "masterLayouts", id, { name })); }, onDeleteMasterLayout: (id) => { // Master löschen UND Bindungen der Layouts lösen (masterId → undefined). - setProject((p) => ({ - ...p, - masterLayouts: (p.masterLayouts ?? []).filter((m) => m.id !== id), - layouts: (p.layouts ?? []).map((l) => - l.masterId === id ? { ...l, masterId: undefined } : l, - ), - })); + applyChange((p) => [ + ...removeItems(p, "masterLayouts", [id]), + ...patchItems(p, "layouts", (l) => l.masterId === id, (l) => ({ ...l, masterId: undefined })), + ]); }, onPatchMasterLayout: (id, patch) => { - setProject((p) => ({ - ...p, - masterLayouts: (p.masterLayouts ?? []).map((m) => - m.id === id ? { ...m, ...patch } : m, - ), - })); + applyChange((p) => patchItem(p, "masterLayouts", id, patch)); }, // ── Layouts-Baum (Ordner) + Erstell-Dialoge (DOSSIER A3) ──────────── onAddLayoutFolder: (parentId) => { const id = `folder-${Date.now()}`; const folder = createLayoutFolder(id, t("layouts.folder.defaultName"), parentId); - setProject((p) => ({ - ...p, - layoutFolders: [...(p.layoutFolders ?? []), folder], - })); + applyChange(addItems("layoutFolders", [folder])); return id; }, onAddMasterFolder: (parentId) => { @@ -1485,38 +1356,30 @@ export function usePanelHostBase(opts: { parentId, "master", ); - setProject((p) => ({ - ...p, - layoutFolders: [...(p.layoutFolders ?? []), folder], - })); + applyChange(addItems("layoutFolders", [folder])); return id; }, onDeleteMasterFolder: (id) => { - setProject((p) => { + applyChange((p) => { const { folders, masters } = deleteMasterFolder( id, p.layoutFolders ?? [], p.masterLayouts ?? [], ); - return { ...p, layoutFolders: folders, masterLayouts: masters }; + return [...fieldOps(p, "layoutFolders", folders), ...fieldOps(p, "masterLayouts", masters)]; }); }, onRenameLayoutFolder: (id, name) => { - setProject((p) => ({ - ...p, - layoutFolders: (p.layoutFolders ?? []).map((f) => - f.id === id ? { ...f, name } : f, - ), - })); + applyChange((p) => patchItem(p, "layoutFolders", id, { name })); }, onDeleteLayoutFolder: (id) => { - setProject((p) => { + applyChange((p) => { const { folders, layouts } = deleteLayoutFolder( id, p.layoutFolders ?? [], p.layouts ?? [], ); - return { ...p, layoutFolders: folders, layouts }; + return [...fieldOps(p, "layoutFolders", folders), ...fieldOps(p, "layouts", layouts)]; }); }, onCreateLayout: (opts) => { @@ -1538,7 +1401,7 @@ export function usePanelHostBase(opts: { ? { customWidthMm, customHeightMm } : {}), }; - setProject((p) => ({ ...p, layouts: [...(p.layouts ?? []), full] })); + applyChange(addItems("layouts", [full])); return id; }, onCreateMasterLayout: (opts) => { @@ -1555,10 +1418,7 @@ export function usePanelHostBase(opts: { custom, ); const full = opts.folderId ? { ...m, folderId: opts.folderId } : m; - setProject((p) => ({ - ...p, - masterLayouts: [...(p.masterLayouts ?? []), full], - })); + applyChange(addItems("masterLayouts", [full])); return id; }, onExportFolderPdf: (folderId) => { @@ -1569,20 +1429,12 @@ export function usePanelHostBase(opts: { }); }, onMoveLayoutToFolder: (layoutId, folderId) => { - setProject((p) => ({ - ...p, - layouts: moveLayoutToFolder(p.layouts ?? [], layoutId, folderId), - })); + applyChange((p) => fieldOps(p, "layouts", moveLayoutToFolder(p.layouts ?? [], layoutId, folderId))); }, onMoveFolderToFolder: (folderId, parentId) => { - setProject((p) => ({ - ...p, - layoutFolders: moveFolderToFolder( - p.layoutFolders ?? [], - folderId, - parentId, - ), - })); + applyChange((p) => + fieldOps(p, "layoutFolders", moveFolderToFolder(p.layoutFolders ?? [], folderId, parentId)), + ); }, }; return value; diff --git a/src/state/useProjectActions.ts b/src/state/useProjectActions.ts index c60a2911..d4e5d661 100644 --- a/src/state/useProjectActions.ts +++ b/src/state/useProjectActions.ts @@ -1,6 +1,6 @@ // Bündelt Projekt-Mutationen als (referenzstabile) Store-Actions plus die // Ressourcen-Typ-CRUD (Wand-/Decken-/Dach-/Tür-/Fenster-/Treppentyp), die -// direkt über `setProject` laufen (kein eigener Slice). Löschen ist je Typ +// direkt über `applyChange` (Ops) laufen (kein eigener Slice). Löschen ist je Typ // geschützt, solange ein Element ihn per `typeId`/`wallTypeId`/… referenziert. // Nur aus App() herausgezogen, um die Funktion zu entlasten — reine // Zustands-/Aktions-Bündelung, keine Verhaltensänderung. @@ -9,6 +9,8 @@ import type { RefObject } from "react"; import { useStore } from "./appStore"; +import { addItems, fieldOps, patchItem, removeItems } from "../core"; +import type { CoreOp } from "../core"; import { t } from "../i18n"; import type { CeilingType, @@ -56,11 +58,11 @@ function contextObjectsBounds(objs: ContextObject[]): Vec2[] | null { } export function useProjectActions( - // `setProject`/`notify` kommen als Parameter herein statt erneut via + // `applyChange`/`notify` kommen als Parameter herein statt erneut via // useStore geholt zu werden: beide werden schon früher in App() gebraucht // (Command-Engine/Grips, vor dieser Sektion) und bleiben dort deklariert — // sonst gäbe es die Store-Action zweimal (Duplikat-Deklaration in App()). - setProject: (next: Project | ((p: Project) => Project)) => void, + applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[])) => void, notify: (message: string, kind?: NotifyKind) => void, planViewRef: RefObject, ) { @@ -122,99 +124,85 @@ export function useProjectActions( const deleteDrawingPoint = useStore((s) => s.deleteDrawingPoint); const setPolylineVertexType = useStore((s) => s.setPolylineVertexType); // Wandstile: immutable Patch eines Wandtyps (z. B. Schichtfugen-Stile). Kein - // eigener Store-Slice nötig — läuft direkt über setProject wie die übrigen + // eigener Store-Slice nötig — läuft direkt über applyChange wie die übrigen // Ressourcen-Mutationen. const patchWallType = (id: string, patch: Partial) => - setProject((p) => ({ - ...p, - wallTypes: p.wallTypes.map((wt) => (wt.id === id ? { ...wt, ...patch } : wt)), - })); + applyChange((p) => patchItem(p, "wallTypes", id, patch)); // Grafische Override-Regeln: ersetzt die ganze Regelliste (Reihenfolge = // Priorität, oben gewinnt). Läuft wie die übrigen Ressourcen-Mutationen - // direkt über setProject — persistiert damit automatisch im Projekt-JSON. + // direkt über applyChange — persistiert damit automatisch im Projekt-JSON. const setOverrideRules = (rules: OverrideRule[]) => - setProject((p) => ({ ...p, overrideRules: rules })); + applyChange((p) => fieldOps(p, "overrideRules", rules)); // Deckenstile: immutable Patch eines Deckentyps — analog `patchWallType`. const patchCeilingType = (id: string, patch: Partial) => - setProject((p) => ({ - ...p, - ceilingTypes: (p.ceilingTypes ?? []).map((ct) => - ct.id === id ? { ...ct, ...patch } : ct, - ), - })); + applyChange((p) => patchItem(p, "ceilingTypes", id, patch)); // Neuen Wandtyp anlegen: eine Default-Schicht (erstes Bauteil, 200 mm). const addWallType = () => - setProject((p) => { + applyChange((p) => { const componentId = p.components[0]?.id ?? ""; const wallType: WallType = { id: `wt-${Date.now()}`, name: t("default.wallTypeName"), layers: [{ componentId, thickness: 0.2 }], }; - return { ...p, wallTypes: [...p.wallTypes, wallType] }; + return addItems("wallTypes", [wallType]); }); // Wandtyp löschen — geschützt, solange ihn eine Wand verwendet. const deleteWallType = (id: string) => - setProject((p) => { + applyChange((p) => { const used = p.walls.some((w) => w.wallTypeId === id); if (used) { const name = p.wallTypes.find((wt) => wt.id === id)?.name ?? id; notify(t("alert.wallTypeInUse", { name }), "warning"); - return p; + return []; } - return { ...p, wallTypes: p.wallTypes.filter((wt) => wt.id !== id) }; + return removeItems(p, "wallTypes", [id]); }); // Neuen Deckentyp anlegen — analog `addWallType` (150 mm Default). const addCeilingType = () => - setProject((p) => { + applyChange((p) => { const componentId = p.components[0]?.id ?? ""; const ceilingType: CeilingType = { id: `ct-${Date.now()}`, name: t("default.ceilingTypeName"), layers: [{ componentId, thickness: 0.15 }], }; - return { ...p, ceilingTypes: [...(p.ceilingTypes ?? []), ceilingType] }; + return addItems("ceilingTypes", [ceilingType]); }); // Deckentyp löschen — geschützt, solange ihn eine Decke verwendet. const deleteCeilingType = (id: string) => - setProject((p) => { + applyChange((p) => { const used = (p.ceilings ?? []).some((c) => c.ceilingTypeId === id); if (used) { const name = (p.ceilingTypes ?? []).find((ct) => ct.id === id)?.name ?? id; notify(t("alert.ceilingTypeInUse", { name }), "warning"); - return p; + return []; } - return { - ...p, - ceilingTypes: (p.ceilingTypes ?? []).filter((ct) => ct.id !== id), - }; + return removeItems(p, "ceilingTypes", [id]); }); // ── Dachtypen (Dachaufbauten) — analog Deckentyp ────────────────────────── const patchRoofType = (id: string, patch: Partial) => - setProject((p) => ({ - ...p, - roofTypes: (p.roofTypes ?? []).map((rt) => (rt.id === id ? { ...rt, ...patch } : rt)), - })); + applyChange((p) => patchItem(p, "roofTypes", id, patch)); const addRoofType = () => - setProject((p) => { + applyChange((p) => { const componentId = p.components[0]?.id ?? ""; const roofType: RoofType = { id: `rt-${Date.now()}`, name: t("default.roofTypeName"), layers: [{ componentId, thickness: 0.2 }], }; - return { ...p, roofTypes: [...(p.roofTypes ?? []), roofType] }; + return addItems("roofTypes", [roofType]); }); // Dachtyp löschen — geschützt, solange ihn ein Dach verwendet. const deleteRoofType = (id: string) => - setProject((p) => { + applyChange((p) => { const used = (p.roofs ?? []).some((r) => r.roofTypeId === id); if (used) { const name = (p.roofTypes ?? []).find((rt) => rt.id === id)?.name ?? id; notify(t("alert.roofTypeInUse", { name }), "warning"); - return p; + return []; } - return { ...p, roofTypes: (p.roofTypes ?? []).filter((rt) => rt.id !== id) }; + return removeItems(p, "roofTypes", [id]); }); // ── Bauteil-Typen: Tür / Fenster / Treppe (Bibliothek) ──────────────────── // Anlegen/Patchen/Löschen analog Wand-/Deckentyp — direkt über setProject @@ -222,7 +210,7 @@ export function useProjectActions( // per `typeId` referenziert. Defaults orientieren sich an den Element-Inline- // Werten (Tür 0.9×2.0, Fenster 1.2×1.4 Brüstung 0.9). const addDoorType = () => - setProject((p) => { + applyChange(() => { const dt: DoorType = { id: `dt-${Date.now()}`, name: t("default.doorTypeName"), @@ -233,27 +221,22 @@ export function useProjectActions( defaultWidth: 0.9, defaultHeight: 2.0, }; - return { ...p, doorTypes: [...(p.doorTypes ?? []), dt] }; + return addItems("doorTypes", [dt]); }); const patchDoorType = (id: string, patch: Partial) => - setProject((p) => ({ - ...p, - doorTypes: (p.doorTypes ?? []).map((dt) => - dt.id === id ? { ...dt, ...patch } : dt, - ), - })); + applyChange((p) => patchItem(p, "doorTypes", id, patch)); const deleteDoorType = (id: string) => - setProject((p) => { + applyChange((p) => { const used = (p.openings ?? []).some((o) => o.typeId === id); if (used) { const name = (p.doorTypes ?? []).find((dt) => dt.id === id)?.name ?? id; notify(t("alert.doorTypeInUse", { name }), "warning"); - return p; + return []; } - return { ...p, doorTypes: (p.doorTypes ?? []).filter((dt) => dt.id !== id) }; + return removeItems(p, "doorTypes", [id]); }); const addWindowType = () => - setProject((p) => { + applyChange(() => { const wt: WindowType = { id: `ft-${Date.now()}`, name: t("default.windowTypeName"), @@ -265,35 +248,27 @@ export function useProjectActions( defaultWidth: 1.2, defaultHeight: 1.4, }; - return { ...p, windowTypes: [...(p.windowTypes ?? []), wt] }; + return addItems("windowTypes", [wt]); }); const patchWindowType = (id: string, patch: Partial) => - setProject((p) => ({ - ...p, - windowTypes: (p.windowTypes ?? []).map((wt) => - wt.id === id ? { ...wt, ...patch } : wt, - ), - })); + applyChange((p) => patchItem(p, "windowTypes", id, patch)); const deleteWindowType = (id: string) => - setProject((p) => { + applyChange((p) => { const used = (p.openings ?? []).some((o) => o.typeId === id); if (used) { const name = (p.windowTypes ?? []).find((wt) => wt.id === id)?.name ?? id; notify(t("alert.windowTypeInUse", { name }), "warning"); - return p; + return []; } - return { - ...p, - windowTypes: (p.windowTypes ?? []).filter((wt) => wt.id !== id), - }; + return removeItems(p, "windowTypes", [id]); }); // „Als Stil speichern": aktuellen Fenster-/Tür-Typ der Öffnung als NEUEN // benannten Stil ablegen und der Öffnung zuweisen (VW „Fenster speichern…"). // Ohne Bezugstyp wird aus den Default-Feldern ein frischer Stil erzeugt. const saveOpeningStyle = (openingId: string, name: string) => - setProject((p) => { + applyChange((p) => { const o = (p.openings ?? []).find((x) => x.id === openingId); - if (!o) return p; + if (!o) return []; if (o.kind === "door") { const base = (p.doorTypes ?? []).find((d) => d.id === o.typeId); const nt: DoorType = base @@ -308,13 +283,7 @@ export function useProjectActions( defaultWidth: 0.9, defaultHeight: 2.0, }; - return { - ...p, - doorTypes: [...(p.doorTypes ?? []), nt], - openings: (p.openings ?? []).map((x) => - x.id === openingId ? { ...x, typeId: nt.id } : x, - ), - }; + return [...addItems("doorTypes", [nt]), ...patchItem(p, "openings", openingId, { typeId: nt.id })]; } const base = (p.windowTypes ?? []).find((w) => w.id === o.typeId); const nt: WindowType = base @@ -330,16 +299,10 @@ export function useProjectActions( defaultWidth: 1.2, defaultHeight: 1.4, }; - return { - ...p, - windowTypes: [...(p.windowTypes ?? []), nt], - openings: (p.openings ?? []).map((x) => - x.id === openingId ? { ...x, typeId: nt.id } : x, - ), - }; + return [...addItems("windowTypes", [nt]), ...patchItem(p, "openings", openingId, { typeId: nt.id })]; }); const addStairType = () => - setProject((p) => { + applyChange(() => { const st: StairType = { id: `st-${Date.now()}`, name: t("default.stairTypeName"), @@ -350,24 +313,19 @@ export function useProjectActions( railing: "keine", defaultWidth: 1.0, }; - return { ...p, stairTypes: [...(p.stairTypes ?? []), st] }; + return addItems("stairTypes", [st]); }); const patchStairType = (id: string, patch: Partial) => - setProject((p) => ({ - ...p, - stairTypes: (p.stairTypes ?? []).map((st) => - st.id === id ? { ...st, ...patch } : st, - ), - })); + applyChange((p) => patchItem(p, "stairTypes", id, patch)); const deleteStairType = (id: string) => - setProject((p) => { + applyChange((p) => { const used = (p.stairs ?? []).some((s) => s.typeId === id); if (used) { const name = (p.stairTypes ?? []).find((st) => st.id === id)?.name ?? id; notify(t("alert.stairTypeInUse", { name }), "warning"); - return p; + return []; } - return { ...p, stairTypes: (p.stairTypes ?? []).filter((st) => st.id !== id) }; + return removeItems(p, "stairTypes", [id]); }); const importLineStyles = useStore((s) => s.importLineStyles); const importHatches = useStore((s) => s.importHatches); From 80e3e54a37091fc666195e993c5da16cab1c04ab Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 22:52:21 +0000 Subject: [PATCH 4/4] [K4][6][8] Ressourcen, Stifte/Paletten, Text-Stile, Raumprogramm, Baurecht, Sonne, Kontext-Schicht und 3D-Griffe mit mitgefuehrten Ecken erzeugen Ops direkt; TODO: Rest-Liste von setProject/diffToOps Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- TODO.md | 38 ++-- src/App.tsx | 1 + src/analysis/roomProgramSheet.ts | 16 +- src/core/extra.ts | 4 +- src/io/roomProgramImport.ts | 16 +- src/model/penSets.test.ts | 8 +- src/model/penSets.ts | 46 ++--- src/panels/KennzahlenSection.tsx | 23 +-- src/panels/ProgramCompareSection.tsx | 17 +- src/panels/SiteRulesSection.tsx | 17 +- src/panels/SunStudySection.tsx | 8 +- src/state/appStore.ts | 4 +- src/state/projectSlice.ts | 272 ++++++++++----------------- src/state/resourceOps.test.ts | 135 +++++++++++++ src/state/siteSlice.ts | 35 ++-- src/ui/RoomProgramImportDialog.tsx | 8 +- src/viewport/Wasm3DViewport.tsx | 67 ++++--- src/views/viewportContent.tsx | 4 + 18 files changed, 419 insertions(+), 300 deletions(-) create mode 100644 src/state/resourceOps.test.ts diff --git a/TODO.md b/TODO.md index c1b00fc8..dbd3a397 100644 --- a/TODO.md +++ b/TODO.md @@ -246,16 +246,30 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern **Messung** (vitest/WASM, Linux-Container unter Last, 3000 Wände, `applyChange.perf.test.ts`): Griff ziehen 3,3 → 0,2–0,3 ms je Mausschritt, Auswahl (300 Wände) verschieben 30 → 5,5–7,5 ms, Eigenschaft tippen 2,3–3,8 → 0,03 ms; Undo/Redo 0,45 → 0,07 ms. Kern nativ: 300 `replace` auf 5000 Wände 11,2 → 1,5 ms. Rest beim Verschieben: JSON der 300 Wände (TS→Kern) und Kopien im Kern. - **Noch über `setProject(fn)` + `diffToOps`** (Kosten nur proportional zu den geänderten Listen; keine Mausschritt-Pfade mehr): - Ressourcen/Stifte/Paletten/Text-Stile in `projectSlice.ts` (kleine Listen; `setActivePenSet`/`patchPenSet*` mit - `rebakePenColors` fassen ganze Listen an), `usePanelHostBase.ts` (Stützen, Extrusionen, Layouts/Masterlayouts, Ausschnitte, - Kontext-Objekte), `useProjectActions.ts` (Wand-/Decken-/Dachtypen, Override-Regeln …), `App.tsx` (Stil übertragen, Sperren, - Kategorien ein/aus/isolieren, IFC-/Datei-Import, Kollisions-Marken, Layout-Handler, Georeferenz), Einfügen/Gruppieren/ - Ungruppieren (`useKeyboardShortcuts.ts`), Raumprogramm/Baurecht/Sonnenstand-Panels, `siteSlice.ts`, Ressourcen-Fenster, - Werkzeug-Commits (`tools/`), Editier-Befehle trim/extend/fillet/chamfer/break/join/explode/align/autodim/defblock/georef/ - sectionline/solid/solidbool/voidbox/terrain/ceilingOpening, Befehls-Commits innerhalb einer Gruppe ohne `opsMutation`. - Offen: diese Liste abbauen, danach `diffToOps` nur noch für Laden/Fremdstände; Ebenen-/Gruppen-Logik (`groupActions.ts`) nach - Rust; 3D-Griffe mit mitgeführten Ecken (`onEdit3dVertex`) ebenfalls als Gruppe; Undo-Verlauf als Liste in der UI [84]. + **Dritte Etappe (28.10.): Rest der Aktionen auf Ops.** Umgestellt: Editier-Befehle trim/extend/fillet/chamfer/break/join/explode/ + align/autodim/defblock/georef/sectionline/solid/solidbool/voidbox/terrain/ceilingOpening und die Werkzeug-Commits in `tools/tools.ts` + (alle `CommandResult.commit`/`ToolResult.commit` sind jetzt `opsMutation`); Einfügen (`pasteElementClipboard`), Gruppieren/ + Ungruppieren (`groupSelection`/`ungroup` liefern Ops); `usePanelHostBase.ts` (Stützen, Extrusionen, Kontext-Bild, Ausschnitte + + Ordner, Layouts/Masterlayouts/Ordner), `useProjectActions.ts` (Wand-/Decken-/Dach-/Tür-/Fenster-/Treppentypen, Override-Regeln, + Stil speichern), `App.tsx` (Split, 2D-Boolean, Segment schneiden, Stil übertragen, Sperren, Kategorien aus/isolieren, + Nicht-drucken, Kollisions-Marken, Layout-Blatt, Einstellungen/Georeferenz, Schatten), `projectSlice.ts` (Bauteile, Schraffuren, + Linien-/Text-Stile, Stifte/Stiftsätze mit `rebakePenOps`, Paletten), `siteSlice.ts`, Raumprogramm/Baurecht/Sonne-Panels + (`roomProgramOps`, `addProgramSheetOps`, `setField`); 3D-Griffe mit mitgeführten Ecken: `Wasm3DViewport` fasst Element und + mitgeführte Ecken je Maus-Schritt zur Gruppe mit Schlüssel (`onEditGroup` = `groupChanges`), ein Zug = ein Undo-Schritt. + Neuer Helfer `replaceWithMany` (Elemente durch mehrere an derselben Stelle ersetzen: explode, Split). Die Projekt → Projekt-Fassungen + der Befehle/Editoren sind gelöscht (`explodeDrawings`, `alignDrawings`, `applyDrawingStyle`, `setLocked*`, `rebakePenColors`, + `applyClashMarkers` …); wo CLI/Tests sie brauchen, sind es dünne Hüllen um die Ops (`applyRoomProgram`, `addProgramSheet`). + Gleichheit: beim Umbau je Befehl 300 Zufallsprojekte (trim … ceilingOpening, 8 Ausrichtungen), dazu Typ-CRUD, 46 Panel-Schritte und + 37 Ressourcen-/Stiftsatz-Schritte (inkl. Undo-Tiefe und Meldungen) gegen die alte setProject-Fassung (Stand vor dem Umbau): gleiches + Projekt bis auf erzeugte ids. Bleibende Tests: `commands/cmds/editOps.test.ts`, `state/panelOps.test.ts`, `state/resourceOps.test.ts`, + `replaceWithMany` in `core/opsBuild.test.ts` und die umgestellten Bestandstests (align, explode, matchProps, objectLock, penSets, clash, + groupActions, elementClipboard). Nicht in der Tauri-App getestet (nur vitest/Linux + e2e im Browser). + **`setProject(fn)` + `diffToOps` bleibt nur noch für:** Datei-Öffnen/Neu/Vorlage/Wiederherstellen (`useProjectFileActions`), + Import (DXF-Layer/Linienstile in `runImport`, Bilder einfügen in `useImportHandling`, IFC-Bauteile in `App.tsx` `runIfcImport`), + das Ressourcen-Fenster (Fremd-Synchronisation) und das CLI (`cli/main.ts`: ganze Dateien, Projekt → Projekt-Hilfen); dazu der + Rückfall für Befehle ohne mitgeführte Ops in `App.tsx` (gibt es keine mehr; der Typ `commit: (p) => Project` erlaubt es noch). + Offen: Ebenen-/Gruppen-Logik (`groupActions.ts`) nach Rust; Undo-Verlauf als Liste in der UI [84]; `diffToOps` entfällt erst, wenn auch + Laden/Import/CLI Ops liefern. - ○ **S4 Typen aus Rust**: `types.ts` wird aus den Rust-Strukturen erzeugt (ts-rs); Datei-I/O (`projectFormat`, Migration, IFC/DXF/ STEP-Ex- und -Import) im Kern. Offene Entscheide/Risiken: Kosten der JSON-Übergabe bei grossen Projekten (Teil-Updates statt Neuaufbau), Struktur-Sharing im @@ -347,7 +361,7 @@ Entscheid CLA vs. Verzicht auf Dual Licensing. - ◐ **[6] Jede Aktion ist ein Befehl mit JSON-Parametern.** Registratur vorhanden, aber interaktiv; Panels/Griffe ändern das Projekt direkt. 28.10.: die häufigsten Aktionen (Griffe, Objekt-Info, Auswahl-Transformationen, Löschen, Zeichenbefehle) liefern ihre Änderung als JSON-Ops (`core/opsBuild.ts`, Store `applyChange`) — Grundlage für - Makros/MCP; Rest-Liste unter [K4] S3. · L + Makros/MCP; Rest (nur Laden/Import/CLI) unter [K4] S3. · L - ◐ **[7] Zentrale Validierung nach jedem Befehl.** 28.10.: jede Projektänderung wird im Kern geprüft (`ops.rs`, NaN/neue doppelte ids → Rücknahme mit Meldung); weitere Regeln (Bezüge, Geometrie) offen. · M - ◐ **[8] Undo über Befehle.** 28.10.: Verlauf im Rust-Kern als inverse Ops (coalesceKey, Gruppen, Speichergrenze), keine @@ -357,7 +371,7 @@ Entscheid CLA vs. Verzicht auf Dual Licensing. ArrayBuffer. Tests: `history.roundtrip.test.ts`, e2e „Mehrmals ganz zurück und wieder vor“. Snapshots mehr ([K4] S3). 28.10.: Griffe, Objekt-Info, Auswahl-Transformationen, Löschen und Zeichenbefehle erzeugen Ops direkt (`applyChange`/`opsMutation`); Gruppen mit Schlüssel: ein Griff-Zug mit mitgeführten Ecken = ein Schritt. Offen: - Rest-Liste unter [K4] S3. · M + Rest (nur Laden/Import/CLI) unter [K4] S3. · M - ◐ **[9] MCP-Brücke.** Headless `dossier-cli … mcp`; Brücke zum offenen Fenster fehlt. · M ### Daten diff --git a/src/App.tsx b/src/App.tsx index f0f8657a..40234cbf 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -3711,6 +3711,7 @@ export default function App() { onEdit3dRoofPitch={onEdit3dRoofPitch} onEdit3dWallTop={onEdit3dWallTop} onEdit3dEnd={onEdit3dEnd} + onEdit3dGroup={groupChanges} onGrip3dEditTab={cycleGrip3dEditField} onGrip3dEditCancel={cancelGrip3dEdit} /> diff --git a/src/analysis/roomProgramSheet.ts b/src/analysis/roomProgramSheet.ts index 3ceb68e8..df5e6f22 100644 --- a/src/analysis/roomProgramSheet.ts +++ b/src/analysis/roomProgramSheet.ts @@ -11,6 +11,9 @@ import type { Drawing2D, DrawingLevel, Project } from "../model/types"; import { t } from "../i18n"; +import { applyOps } from "../core/ops"; +import type { CoreOp } from "../core/ops"; +import { addItems } from "../core/opsBuild"; import { layoutRoomProgram } from "./roomProgram"; import type { LayoutGroup, LayoutItem, RoomProgramLayout } from "./roomProgram"; @@ -123,8 +126,13 @@ export function buildProgramSheet(project: Project, labels: SheetLabels, stamp: return { level, drawings, layout }; } -/** Fügt das Blatt dem Projekt hinzu (für `setProject`); ohne Räume unverändert. */ -export function addProgramSheet(project: Project, sheet: ProgramSheet): Project { - if (sheet.drawings.length === 0) return project; - return { ...project, drawingLevels: [...project.drawingLevels, sheet.level], drawings2d: [...project.drawings2d, ...sheet.drawings] }; +/** Ops: fügt das Blatt (Ebene + Zeichnungen) hinzu; ohne Räume keine Ops. */ +export function addProgramSheetOps(sheet: ProgramSheet): CoreOp[] { + if (sheet.drawings.length === 0) return []; + return [...addItems("drawingLevels", [sheet.level]), ...addItems("drawings2d", sheet.drawings)]; +} + +/** Wie {@link addProgramSheetOps}, als Projekt → Projekt (CLI, Tests); ohne Räume unverändert. */ +export function addProgramSheet(project: Project, sheet: ProgramSheet): Project { + return applyOps(project, addProgramSheetOps(sheet)); } diff --git a/src/core/extra.ts b/src/core/extra.ts index 3e9726d2..b1bea08f 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -25,10 +25,10 @@ export type { Project, DrawingLevel } from "../model/types"; export { computeKennzahlen, checkRoomProgram, solidVolume } from "../analysis/kennzahlen"; export type { Kennzahlen, ProgramCheck } from "../analysis/kennzahlen"; export { compareRoomProgram, layoutRoomProgram, DEFAULT_PROGRAM_TOLERANCE } from "../analysis/roomProgram"; -export { buildProgramSheet, addProgramSheet, groupColor, defaultSheetLabels } from "../analysis/roomProgramSheet"; +export { buildProgramSheet, addProgramSheet, addProgramSheetOps, groupColor, defaultSheetLabels } from "../analysis/roomProgramSheet"; export type { ProgramSheet, SheetLabels } from "../analysis/roomProgramSheet"; export type { RoomProgramCompare, RoomProgramLayout, CompareRow, CompareSum, Light, LayoutItem, LayoutGroup } from "../analysis/roomProgram"; -export { readSheetFile, suggestMapping, mapRows, importedRows, applyRoomProgram, cellNumber, cellText, detectHeaderRow, parseKind, PROGRAM_FIELDS } from "../io/roomProgramImport"; +export { readSheetFile, suggestMapping, mapRows, importedRows, applyRoomProgram, roomProgramOps, cellNumber, cellText, detectHeaderRow, parseKind, PROGRAM_FIELDS } from "../io/roomProgramImport"; export type { SheetData, SheetCell, Mapping, ColumnMap, ProgramField, ImportLine, ImportMode, SkipReason } from "../io/roomProgramImport"; export { buildProgramReport } from "../export/programReport"; export { computeAreaTable, computeIvhb } from "../analysis/areaTable"; diff --git a/src/io/roomProgramImport.ts b/src/io/roomProgramImport.ts index f52beeed..d28b8f52 100644 --- a/src/io/roomProgramImport.ts +++ b/src/io/roomProgramImport.ts @@ -9,6 +9,9 @@ import type { Project, RoomProgramRow, SiaCategory } from "../model/types"; import { fileio, loadFileio } from "../engine/fileioWasm"; +import { applyOps } from "../core/ops"; +import type { CoreOp } from "../core/ops"; +import { setField } from "../core/opsBuild"; export type SheetCell = string | number | null; @@ -284,8 +287,13 @@ export function importedRows(lines: ImportLine[]): RoomProgramRow[] { export type ImportMode = "replace" | "append"; -/** Fügt Programmzeilen in das Projekt ein (für `setProject`): ersetzen oder anhängen. Keine Zeilen → unverändert. */ -export function applyRoomProgram(project: Project, rows: RoomProgramRow[], mode: ImportMode): Project { - if (rows.length === 0) return project; - return { ...project, roomProgram: mode === "append" ? [...(project.roomProgram ?? []), ...rows] : rows }; +/** Ops: Programmzeilen ins Projekt einfügen — ersetzen oder anhängen. Keine Zeilen → keine Ops. */ +export function roomProgramOps(project: Project, rows: RoomProgramRow[], mode: ImportMode): CoreOp[] { + if (rows.length === 0) return []; + return [setField("roomProgram", mode === "append" ? [...(project.roomProgram ?? []), ...rows] : rows)]; +} + +/** Wie {@link roomProgramOps}, als Projekt → Projekt (CLI, Tests). Keine Zeilen → unverändert. */ +export function applyRoomProgram(project: Project, rows: RoomProgramRow[], mode: ImportMode): Project { + return applyOps(project, roomProgramOps(project, rows, mode)); } diff --git a/src/model/penSets.test.ts b/src/model/penSets.test.ts index 7eaf7246..2a6f747d 100644 --- a/src/model/penSets.test.ts +++ b/src/model/penSets.test.ts @@ -3,13 +3,17 @@ import { activePenSet, resolvePenColor, resolvePenWeight, - rebakePenColors, + rebakePenOps, generateStandardPenPalette, - seedStandardPenSet, + seedStandardPenSetOps, PEN_FALLBACK_COLOR, PEN_FALLBACK_WEIGHT, } from "./penSets"; import type { Ceiling, Component, Drawing2D, LayerCategory, PenStyle, Project, Room, Wall } from "./types"; +import { applyOps } from "../core/ops"; + +const rebakePenColors = (p: Project): Project => applyOps(p, rebakePenOps(p)); +const seedStandardPenSet = (p: Project): Project => applyOps(p, seedStandardPenSetOps(p)); function baseProject(overrides: Partial = {}): Project { return { diff --git a/src/model/penSets.ts b/src/model/penSets.ts index 144a3a40..9e092986 100644 --- a/src/model/penSets.ts +++ b/src/model/penSets.ts @@ -15,6 +15,9 @@ // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import type { ColorPen, Component, LayerCategory, PenSet, PenStyle, Project } from "./types"; +import { applyOps } from "../core/ops"; +import type { CoreOp } from "../core/ops"; +import { addItems, fieldOps, patchItems, setFieldIfChanged } from "../core/opsBuild"; /** Farbe eines Stifts, der im aktiven Stiftsatz (noch) keinen Eintrag hat. */ export const PEN_FALLBACK_COLOR = "#9aa0a6"; @@ -122,15 +125,15 @@ export function generateStandardPenPalette(): { pens: ColorPen[]; styles: Record * eigene Stifte/Sätze existieren. Der neue Satz wird aktiv, wenn noch KEIN * Stiftsatz aktiv war (dieselbe Konvention wie `addPenSet`). */ -export function seedStandardPenSet(project: Project): Project { +export function seedStandardPenSetOps(project: Project): CoreOp[] { const { pens, styles } = generateStandardPenPalette(); const penSet: PenSet = { id: `penset-${Date.now()}`, name: "Standard (CAD-Palette)", pens: styles }; - return rebakePenColors({ - ...project, - pens, - penSets: [...(project.penSets ?? []), penSet], - activePenSetId: project.activePenSetId ?? penSet.id, - }); + const stateOps = [ + ...fieldOps(project, "pens", pens), + ...addItems("penSets", [penSet]), + ...setFieldIfChanged(project, "activePenSetId", project.activePenSetId ?? penSet.id), + ]; + return [...stateOps, ...rebakePenOps(applyOps(project, stateOps))]; } /** Der aktuell aktive Stiftsatz, oder `undefined` (kein Stiftsatz angelegt/aktiviert). */ @@ -236,18 +239,19 @@ function bakeElementColorAndWeight< * verschachtelt in `Project.layouts`) und `Tür`/`ExtrudedSolid`/Kontext- * Objekte — kein `colorPenId`-Feld dort (Scope-Entscheid, s. PENDENZEN.md). */ -export function rebakePenColors(project: Project): Project { - return { - ...project, - components: project.components.map((c) => bakeComponent(project, c)), - layers: project.layers.map((cat) => bakeCategory(project, cat)), - walls: project.walls.map((w) => bakeElementColorAndWeight(project, w, "strokeWeight")), - drawings2d: project.drawings2d.map((d) => bakeElementColorAndWeight(project, d, "weightMm")), - ceilings: project.ceilings?.map((c) => bakeElementColorAndWeight(project, c, "strokeWeight")), - columns: project.columns?.map((c) => bakeElementColorAndWeight(project, c, "strokeWeight")), - roofs: project.roofs?.map((r) => bakeElementColor(project, r)), - openings: project.openings?.map((o) => bakeElementColor(project, o)), - stairs: project.stairs?.map((s) => bakeElementColor(project, s)), - rooms: project.rooms?.map((r) => bakeElementColor(project, r)), - }; +export function rebakePenOps(project: Project): CoreOp[] { + const all = () => true; + const layers = project.layers.map((cat) => bakeCategory(project, cat)); + return [ + ...patchItems(project, "components", all, (c) => bakeComponent(project, c)), + ...(layers.every((c, i) => c === project.layers[i]) ? [] : fieldOps(project, "layers", layers)), + ...patchItems(project, "walls", all, (w) => bakeElementColorAndWeight(project, w, "strokeWeight")), + ...patchItems(project, "drawings2d", all, (d) => bakeElementColorAndWeight(project, d, "weightMm")), + ...patchItems(project, "ceilings", all, (c) => bakeElementColorAndWeight(project, c, "strokeWeight")), + ...patchItems(project, "columns", all, (c) => bakeElementColorAndWeight(project, c, "strokeWeight")), + ...patchItems(project, "roofs", all, (r) => bakeElementColor(project, r)), + ...patchItems(project, "openings", all, (o) => bakeElementColor(project, o)), + ...patchItems(project, "stairs", all, (s) => bakeElementColor(project, s)), + ...patchItems(project, "rooms", all, (r) => bakeElementColor(project, r)), + ]; } diff --git a/src/panels/KennzahlenSection.tsx b/src/panels/KennzahlenSection.tsx index b67b47bf..092b9d4d 100644 --- a/src/panels/KennzahlenSection.tsx +++ b/src/panels/KennzahlenSection.tsx @@ -4,7 +4,7 @@ // • Parzellenfläche: Eingabefeld → `Project.parcelArea` (leer/0 = aus der Parzellengrenze, sonst nicht gesetzt). // • Raumprogramm: Soll-Zeilen (Name, Fläche je Raum, Anzahl) bearbeiten; der Status je Zeile // kommt aus `checkRoomProgram`. -// Änderungen laufen über `setProject` mit coalesceKey, damit Tippen einen Undo-Schritt ergibt. +// Änderungen laufen über `applyChange` (Ops) mit coalesceKey, damit Tippen einen Undo-Schritt ergibt. import { t } from "../i18n"; import type { TranslationKey } from "../i18n"; @@ -12,6 +12,7 @@ import { usePanelHost } from "./host"; import { useStore } from "../state/appStore"; import { checkRoomProgram, computeKennzahlen, polygonArea } from "../core"; import type { Project, RoomProgramRow } from "../model/types"; +import { setField, setFieldIfChanged } from "../core"; import { RoomProgramImportButton } from "../ui/RoomProgramImportDialog"; import { ProgramCompareSection } from "./ProgramCompareSection"; @@ -41,7 +42,7 @@ const fmt = (n: number, d = 1) => n.toLocaleString("de-CH", { minimumFractionDig export function KennzahlenSection() { const host = usePanelHost(); - const setProject = useStore((s) => s.setProject); + const applyChange = useStore((s) => s.applyChange); const notify = useStore((s) => s.notify); const project = host.project; const k = computeKennzahlen(project); @@ -50,22 +51,18 @@ export function KennzahlenSection() { const setParcel = (text: string) => { const v = parseNum(text); - setProject((p: Project) => { - const { parcelArea: _old, ...rest } = p; - return v !== null && v > 0 ? { ...rest, parcelArea: v } : rest; - }, "parcelArea"); + applyChange((p: Project) => setFieldIfChanged(p, "parcelArea", v !== null && v > 0 ? v : undefined), "parcelArea"); }; const patchRow = (i: number, patch: Partial, field: string) => - setProject( - (p: Project) => ({ ...p, roomProgram: (p.roomProgram ?? []).map((r, j) => (j === i ? { ...r, ...patch } : r)) }), + applyChange( + (p: Project) => [setField("roomProgram", (p.roomProgram ?? []).map((r, j) => (j === i ? { ...r, ...patch } : r)))], `roomProgram:${i}:${field}`, ); - const addRow = () => setProject((p: Project) => ({ ...p, roomProgram: [...(p.roomProgram ?? []), { name: "", area: 20, count: 1 }] })); + const addRow = () => applyChange((p: Project) => [setField("roomProgram", [...(p.roomProgram ?? []), { name: "", area: 20, count: 1 }])]); const removeRow = (i: number) => - setProject((p: Project) => { + applyChange((p: Project) => { const next = (p.roomProgram ?? []).filter((_, j) => j !== i); - const { roomProgram: _old, ...rest } = p; - return next.length > 0 ? { ...rest, roomProgram: next } : rest; + return setFieldIfChanged(p, "roomProgram", next.length > 0 ? next : undefined); }); const tiles: { label: string; value: string; title: TranslationKey }[] = [ @@ -182,7 +179,7 @@ export function KennzahlenSection() { - setProject(fn)} notify={notify} /> + applyChange(build)} notify={notify} /> {rows.length > 0 && } diff --git a/src/panels/ProgramCompareSection.tsx b/src/panels/ProgramCompareSection.tsx index 511ee455..5ceeefdb 100644 --- a/src/panels/ProgramCompareSection.tsx +++ b/src/panels/ProgramCompareSection.tsx @@ -11,7 +11,7 @@ import { t } from "../i18n"; import type { TranslationKey } from "../i18n"; import { usePanelHost } from "./host"; import { useStore } from "../state/appStore"; -import { addProgramSheet, areaReportToCsv, buildAreaReportPdf, buildProgramReport, buildProgramSheet, compareRoomProgram, defaultSheetLabels, DEFAULT_PROGRAM_TOLERANCE } from "../core"; +import { addProgramSheetOps, areaReportToCsv, buildAreaReportPdf, buildProgramReport, buildProgramSheet, compareRoomProgram, defaultSheetLabels, DEFAULT_PROGRAM_TOLERANCE, setFieldIfChanged } from "../core"; import type { CompareRow, CompareSum, Light } from "../core"; import type { Project } from "../model/types"; import { downloadCsv } from "./downloadFile"; @@ -41,7 +41,7 @@ function SumRow({ s, label, total }: { s: CompareSum; label: string; total?: boo export function ProgramCompareSection({ statusLabel }: { statusLabel: (status: CompareRow["status"]) => string }) { const host = usePanelHost(); const project = host.project; - const setProject = useStore((s) => s.setProject); + const applyChange = useStore((s) => s.applyChange); const notify = useStore((s) => s.notify); const c = compareRoomProgram(project); if (c.rows.length === 0) return null; @@ -51,10 +51,11 @@ export function ProgramCompareSection({ statusLabel }: { statusLabel: (status: C const setTolerance = (text: string) => { const v = Number(text.trim().replace(",", ".")); - setProject((p: Project) => { - const { roomProgramTolerance: _old, ...rest } = p; - return text.trim() !== "" && Number.isFinite(v) && v >= 0 && v <= 100 ? { ...rest, roomProgramTolerance: v / 100 } : rest; - }, "roomProgramTolerance"); + applyChange( + (p: Project) => + setFieldIfChanged(p, "roomProgramTolerance", text.trim() !== "" && Number.isFinite(v) && v >= 0 && v <= 100 ? v / 100 : undefined), + "roomProgramTolerance", + ); }; const exportPdf = () => { @@ -71,8 +72,8 @@ export function ProgramCompareSection({ statusLabel }: { statusLabel: (status: C notify(t("program.generate.none"), "warning"); return; } - // Ein setProject = ein Undo-Schritt: Ebene und alle Zeichnungen zusammen. - setProject((p: Project) => addProgramSheet(p, sheet)); + // Ein applyChange = ein Undo-Schritt: Ebene und alle Zeichnungen zusammen. + applyChange(addProgramSheetOps(sheet)); host.onSelectLevel(sheet.level.id); notify(t("program.generate.done", { n: sheet.layout.items.length, name: sheet.level.name })); }; diff --git a/src/panels/SiteRulesSection.tsx b/src/panels/SiteRulesSection.tsx index 6dae8103..d656f9ac 100644 --- a/src/panels/SiteRulesSection.tsx +++ b/src/panels/SiteRulesSection.tsx @@ -5,7 +5,7 @@ import { t } from "../i18n"; import { usePanelHost } from "./host"; import { useStore } from "../state/appStore"; -import { checkSiteRules } from "../core"; +import { checkSiteRules, setField } from "../core"; import type { Project, SiteRules } from "../model/types"; import { lineFromDrawing, parcelFromDrawing } from "./siteRulesInput"; @@ -20,7 +20,7 @@ function parseLen(text: string): number | undefined | null { export function SiteRulesSection() { const host = usePanelHost(); - const setProject = useStore((s) => s.setProject); + const applyChange = useStore((s) => s.applyChange); const rules = host.project.siteRules; const sel = host.selection; const selDrawing = sel?.kind === "drawing2d" ? host.project.drawings2d.find((d) => d.id === sel.id) : undefined; @@ -28,19 +28,18 @@ export function SiteRulesSection() { const selLine = lineFromDrawing(selDrawing); const write = (fn: (r: SiteRules) => SiteRules | undefined, key?: string) => - setProject((p: Project) => { - const { siteRules: old, ...rest } = p; - if (!old) return p; - const next = fn(old); - return next ? { ...rest, siteRules: next } : rest; + applyChange((p: Project) => { + const old = p.siteRules; + if (!old) return []; + return [setField("siteRules", fn(old))]; }, key); const takeParcel = () => { if (!selParcel) return; - setProject((p: Project) => { + applyChange((p: Project) => { // Neue Grenze: Grenzabstände je Kante passen nicht mehr → zurücksetzen. const { setbacks: _old, ...prev } = p.siteRules ?? { parcel: [], defaultSetback: 4 }; - return { ...p, siteRules: { ...prev, parcel: selParcel } }; + return [setField("siteRules", { ...prev, parcel: selParcel })]; }); }; diff --git a/src/panels/SunStudySection.tsx b/src/panels/SunStudySection.tsx index aae1d430..73020f57 100644 --- a/src/panels/SunStudySection.tsx +++ b/src/panels/SunStudySection.tsx @@ -5,8 +5,8 @@ import { t } from "../i18n"; import { usePanelHost } from "./host"; import { useStore } from "../state/appStore"; -import { projectLatLon, sunPosition } from "../core"; -import type { Project, SunStudy } from "../model/types"; +import { projectLatLon, setField, sunPosition } from "../core"; +import type { SunStudy } from "../model/types"; import { defaultStudyIso, formatMinutes, isoToLocal, localToIso } from "./sunStudyTime"; /** Merkdaten: Tagundnachtgleiche, Sommer- und Wintersonnenwende (Tag/Monat). */ @@ -18,11 +18,11 @@ const PRESETS: { key: "sun.equinox" | "sun.summer" | "sun.winter"; md: string }[ export function SunStudySection() { const host = usePanelHost(); - const setProject = useStore((s) => s.setProject); + const applyChange = useStore((s) => s.applyChange); const study: SunStudy = host.project.sunStudy ?? { when: defaultStudyIso(), show: false }; const local = isoToLocal(study.when) ?? isoToLocal(defaultStudyIso())!; - const write = (next: SunStudy, key?: string) => setProject((p: Project) => ({ ...p, sunStudy: next }), key); + const write = (next: SunStudy, key?: string) => applyChange([setField("sunStudy", next)], key); const setLocal = (date: string, minutes: number, key?: string) => { const iso = localToIso({ date, minutes }); if (iso) write({ ...study, when: iso }, key); diff --git a/src/state/appStore.ts b/src/state/appStore.ts index cc253945..38f71f8b 100644 --- a/src/state/appStore.ts +++ b/src/state/appStore.ts @@ -48,13 +48,13 @@ const store = createStore((api) => ({ ...createSelectionSlice(api as unknown as StoreApi), ...createViewSlice(api as unknown as StoreApi), ...createLayoutSlice(api as unknown as StoreApi), - // Site-/Kontext-Slice liest `project` und schreibt über `setProject` + // Site-/Kontext-Slice liest `project` und schreibt über `applyChange` // (beide aus der Projekt-Slice) — daher die kombinierte Sicht im Cast. ...createSiteSlice( api as unknown as StoreApi< SiteSlice & { project: ProjectSlice["project"]; - setProject: ProjectSlice["setProject"]; + applyChange: ProjectSlice["applyChange"]; } >, ), diff --git a/src/state/projectSlice.ts b/src/state/projectSlice.ts index f48066b2..5b819a06 100644 --- a/src/state/projectSlice.ts +++ b/src/state/projectSlice.ts @@ -8,7 +8,7 @@ // laufen. Die Slice tippt daher nur ihre eigenen Felder; `get()` liefert // RootState (siehe appStore.ts), wir greifen punktuell auf View-Felder zu. -import { diffToOps } from "../core/ops"; +import { applyOps, diffToOps } from "../core/ops"; import type { CoreOp } from "../core/ops"; import { addItems, @@ -17,7 +17,9 @@ import { patchItem, patchItems, removeItems, + replaceItem, setField, + setFieldIfChanged, } from "../core"; import { withVertexType, type PolylineVertexType } from "../core"; import { sampleProject } from "../model/sampleProject"; @@ -40,8 +42,8 @@ import type { } from "../model/types"; import { activePenSet, - rebakePenColors, - seedStandardPenSet as buildStandardPenSet, + rebakePenOps, + seedStandardPenSetOps, PEN_FALLBACK_COLOR, PEN_FALLBACK_WEIGHT, } from "../model/penSets"; @@ -764,18 +766,12 @@ export function createProjectSlice( ), // ── Ressourcen ───────────────────────────────────────────────────────── - patchComponent: (id, patch) => - setProject((p) => ({ - ...p, - components: p.components.map((c) => - c.id === id ? { ...c, ...patch } : c, - ), - })), + patchComponent: (id, patch) => applyChange((p) => patchItem(p, "components", id, patch)), addComponent: () => - setProject((p) => { - let hatches = p.hatches; - let hatchId = hatches[0]?.id; + applyChange((p) => { + const ops: CoreOp[] = []; + let hatchId = p.hatches[0]?.id; if (!hatchId) { const fallback: HatchStyle = { id: `hatch-${Date.now()}`, @@ -785,7 +781,7 @@ export function createProjectSlice( angle: 0, color: "#2b3039", }; - hatches = [fallback]; + ops.push(...fieldOps(p, "hatches", [fallback])); hatchId = fallback.id; } const component: Component = { @@ -795,30 +791,26 @@ export function createProjectSlice( hatchId, joinPriority: 50, }; - return { ...p, hatches, components: [...p.components, component] }; + return [...ops, ...addItems("components", [component])]; }), deleteComponent: (id) => - setProject((p) => { + applyChange((p) => { const used = p.wallTypes.some((wt) => wt.layers.some((l) => l.componentId === id), ); if (used) { const name = p.components.find((c) => c.id === id)?.name ?? id; get().notify(t("alert.componentInUse", { name }), "warning"); - return p; + return []; } - return { ...p, components: p.components.filter((c) => c.id !== id) }; + return removeItems(p, "components", [id]); }), - patchHatch: (id, patch) => - setProject((p) => ({ - ...p, - hatches: p.hatches.map((h) => (h.id === id ? { ...h, ...patch } : h)), - })), + patchHatch: (id, patch) => applyChange((p) => patchItem(p, "hatches", id, patch)), addHatch: () => - setProject((p) => { + applyChange((p) => { const hatch: HatchStyle = { id: `hatch-${Date.now()}`, name: t("default.hatchName"), @@ -828,30 +820,24 @@ export function createProjectSlice( color: "#2b3039", lineStyleId: p.lineStyles[0]?.id, }; - return { ...p, hatches: [...p.hatches, hatch] }; + return addItems("hatches", [hatch]); }), deleteHatch: (id) => - setProject((p) => { + applyChange((p) => { const used = p.components.some((c) => c.hatchId === id); if (used) { const name = p.hatches.find((h) => h.id === id)?.name ?? id; get().notify(t("alert.hatchInUse", { name }), "warning"); - return p; + return []; } - return { ...p, hatches: p.hatches.filter((h) => h.id !== id) }; + return removeItems(p, "hatches", [id]); }), - patchLineStyle: (id, patch) => - setProject((p) => ({ - ...p, - lineStyles: p.lineStyles.map((l) => - l.id === id ? { ...l, ...patch } : l, - ), - })), + patchLineStyle: (id, patch) => applyChange((p) => patchItem(p, "lineStyles", id, patch)), addLineStyle: () => - setProject((p) => { + applyChange(() => { const lineStyle: LineStyle = { id: `line-${Date.now()}`, name: t("default.lineStyleName"), @@ -859,87 +845,70 @@ export function createProjectSlice( color: "#2b3039", dash: null, }; - return { ...p, lineStyles: [...p.lineStyles, lineStyle] }; + return addItems("lineStyles", [lineStyle]); }), deleteLineStyle: (id) => - setProject((p) => { + applyChange((p) => { const used = p.hatches.some((h) => h.lineStyleId === id); if (used) { const name = p.lineStyles.find((l) => l.id === id)?.name ?? id; get().notify(t("alert.lineStyleInUse", { name }), "warning"); - return p; + return []; } - return { ...p, lineStyles: p.lineStyles.filter((l) => l.id !== id) }; + return removeItems(p, "lineStyles", [id]); }), importLineStyles: (styles) => - setProject((p) => ({ - ...p, - lineStyles: [ - ...p.lineStyles, - ...styles.map((s, i) => ({ ...s, id: `ls-${Date.now()}-${i}` })), - ], - })), + applyChange(addItems("lineStyles", styles.map((s, i) => ({ ...s, id: `ls-${Date.now()}-${i}` })))), patchTextStyle: (id, patch) => - setProject((p) => ({ - ...p, - textStyles: (p.textStyles ?? DEFAULT_PRESETS).map((s) => - s.id === id ? { ...s, ...patch, marks: { ...s.marks, ...patch.marks } } : s, + applyChange((p) => + fieldOps( + p, + "textStyles", + (p.textStyles ?? DEFAULT_PRESETS).map((s) => + s.id === id ? { ...s, ...patch, marks: { ...s.marks, ...patch.marks } } : s, + ), ), - })), + ), addTextStyle: () => - setProject((p) => { + applyChange((p) => { const style: TextStylePreset = { id: `ts-${Date.now()}`, label: t("default.textStyleName"), marks: { sizePt: 10 }, }; - return { ...p, textStyles: [...(p.textStyles ?? DEFAULT_PRESETS), style] }; + return fieldOps(p, "textStyles", [...(p.textStyles ?? DEFAULT_PRESETS), style]); }), deleteTextStyle: (id) => - setProject((p) => ({ - ...p, - textStyles: (p.textStyles ?? DEFAULT_PRESETS).filter((s) => s.id !== id), - })), + applyChange((p) => fieldOps(p, "textStyles", (p.textStyles ?? DEFAULT_PRESETS).filter((s) => s.id !== id))), importHatches: (hatches) => - setProject((p) => ({ - ...p, - hatches: [ - ...p.hatches, - ...hatches.map((h, i) => ({ ...h, id: `ht-${Date.now()}-${i}` })), - ], - })), + applyChange(addItems("hatches", hatches.map((h, i) => ({ ...h, id: `ht-${Date.now()}-${i}` })))), // ── Stiftsätze ───────────────────────────────────────────────────────── addPen: () => - setProject((p) => { + applyChange((p) => { const pen: ColorPen = { id: `pen-${Date.now()}`, name: t("default.penName") }; - return { - ...p, - pens: [...(p.pens ?? []), pen], + return [ + ...addItems("pens", [pen]), // Neuer Stift bekommt in JEDEM bestehenden Stiftsatz sofort einen // Eintrag (Fallback-Grauton+Stärke) — Stiftsätze bleiben dadurch // immer deckungsgleich zur `pens`-Liste, keine "fehlt in Satz X"-Lücken. - penSets: p.penSets?.map((s) => ({ + ...patchItems(p, "penSets", () => true, (s) => ({ ...s, pens: { ...s.pens, [pen.id]: { color: PEN_FALLBACK_COLOR, weight: PEN_FALLBACK_WEIGHT } }, })), - }; + ]; }), - renamePen: (id, name) => - setProject((p) => ({ - ...p, - pens: p.pens?.map((pen) => (pen.id === id ? { ...pen, name } : pen)), - })), + renamePen: (id, name) => applyChange((p) => patchItem(p, "pens", id, { name })), deletePen: (id) => - setProject((p) => { + applyChange((p) => { const clearPenRefs = (x: T): T => x.colorPenId === id || x.foregroundPenId === id || x.backgroundPenId === id ? { @@ -953,20 +922,19 @@ export function createProjectSlice( ...(cat.colorPenId === id ? { ...cat, colorPenId: undefined } : cat), ...(cat.children ? { children: cat.children.map(clearCategoryPenRefs) } : {}), }); - return { - ...p, - pens: p.pens?.filter((pen) => pen.id !== id), - penSets: p.penSets?.map((s) => { + return [ + ...removeItems(p, "pens", [id]), + ...patchItems(p, "penSets", () => true, (s) => { const { [id]: _removed, ...rest } = s.pens; return { ...s, pens: rest }; }), - components: p.components.map(clearPenRefs), - layers: p.layers.map(clearCategoryPenRefs), - }; + ...patchItems(p, "components", () => true, clearPenRefs), + ...fieldOps(p, "layers", p.layers.map(clearCategoryPenRefs)), + ]; }), addPenSet: () => - setProject((p) => { + applyChange((p) => { const current = activePenSet(p); const penSet: PenSet = { id: `penset-${Date.now()}`, @@ -977,128 +945,90 @@ export function createProjectSlice( (p.pens ?? []).map((pen) => [pen.id, { color: PEN_FALLBACK_COLOR, weight: PEN_FALLBACK_WEIGHT }]), ), }; - const penSets = [...(p.penSets ?? []), penSet]; // Erster Stiftsatz überhaupt: automatisch aktivieren (sonst löst jeder // Stift-Verweis bis zur ersten manuellen Aktivierung auf den Fallback auf). - return { - ...p, - penSets, - activePenSetId: p.activePenSetId ?? penSet.id, - }; + return [ + ...addItems("penSets", [penSet]), + ...setFieldIfChanged(p, "activePenSetId", p.activePenSetId ?? penSet.id), + ]; }), - renamePenSet: (id, name) => - setProject((p) => ({ - ...p, - penSets: p.penSets?.map((s) => (s.id === id ? { ...s, name } : s)), - })), + renamePenSet: (id, name) => applyChange((p) => patchItem(p, "penSets", id, { name })), deletePenSet: (id) => - setProject((p) => { + applyChange((p) => { if (p.activePenSetId === id) { const name = p.penSets?.find((s) => s.id === id)?.name ?? id; get().notify(t("alert.penSetIsActive", { name }), "warning"); - return p; + return []; } - return { ...p, penSets: p.penSets?.filter((s) => s.id !== id) }; + return removeItems(p, "penSets", [id]); }), setActivePenSet: (id) => - setProject((p) => rebakePenColors({ ...p, activePenSetId: id })), + applyChange((p) => { + const stateOps = [setField("activePenSetId", id)]; + return [...stateOps, ...rebakePenOps(applyOps(p, stateOps))]; + }), patchPenSetColor: (setId, penId, color) => - setProject((p) => { - const next = { - ...p, - penSets: p.penSets?.map((s) => - s.id === setId - ? { - ...s, - pens: { - ...s.pens, - [penId]: { ...(s.pens[penId] ?? { color: PEN_FALLBACK_COLOR, weight: PEN_FALLBACK_WEIGHT }), color }, - }, - } - : s, - ), - }; - return setId === p.activePenSetId ? rebakePenColors(next) : next; + applyChange((p) => { + const stateOps = patchItem(p, "penSets", setId, (s) => ({ + ...s, + pens: { + ...s.pens, + [penId]: { ...(s.pens[penId] ?? { color: PEN_FALLBACK_COLOR, weight: PEN_FALLBACK_WEIGHT }), color }, + }, + })); + return setId === p.activePenSetId ? [...stateOps, ...rebakePenOps(applyOps(p, stateOps))] : stateOps; }), patchPenSetWeight: (setId, penId, weight) => - setProject((p) => { - const next = { - ...p, - penSets: p.penSets?.map((s) => - s.id === setId - ? { - ...s, - pens: { - ...s.pens, - [penId]: { ...(s.pens[penId] ?? { color: PEN_FALLBACK_COLOR, weight: PEN_FALLBACK_WEIGHT }), weight }, - }, - } - : s, - ), - }; - return setId === p.activePenSetId ? rebakePenColors(next) : next; + applyChange((p) => { + const stateOps = patchItem(p, "penSets", setId, (s) => ({ + ...s, + pens: { + ...s.pens, + [penId]: { ...(s.pens[penId] ?? { color: PEN_FALLBACK_COLOR, weight: PEN_FALLBACK_WEIGHT }), weight }, + }, + })); + return setId === p.activePenSetId ? [...stateOps, ...rebakePenOps(applyOps(p, stateOps))] : stateOps; }), - seedStandardPenSet: () => setProject((p) => buildStandardPenSet(p)), + seedStandardPenSet: () => applyChange((p) => seedStandardPenSetOps(p)), addCustomPalette: () => - setProject((p) => ({ - ...p, - customPalettes: [ - ...(p.customPalettes ?? []), - { id: `palette-${Date.now()}`, name: t("default.customPaletteName"), colors: [] }, - ], - })), + applyChange( + addItems("customPalettes", [{ id: `palette-${Date.now()}`, name: t("default.customPaletteName"), colors: [] }]), + ), - renameCustomPalette: (id, name) => - setProject((p) => ({ - ...p, - customPalettes: p.customPalettes?.map((c) => (c.id === id ? { ...c, name } : c)), - })), + renameCustomPalette: (id, name) => applyChange((p) => patchItem(p, "customPalettes", id, { name })), - deleteCustomPalette: (id) => - setProject((p) => ({ - ...p, - customPalettes: p.customPalettes?.filter((c) => c.id !== id), - })), + deleteCustomPalette: (id) => applyChange((p) => removeItems(p, "customPalettes", [id])), addColorToCustomPalette: (paletteId, hex) => - setProject((p) => { - const palettes = p.customPalettes ?? []; - const target = palettes.find((c) => c.id === paletteId); + applyChange((p) => { + const target = (p.customPalettes ?? []).find((c) => c.id === paletteId); if (!target) { const created = { id: `palette-${Date.now()}`, name: t("default.customPaletteName"), colors: [hex] }; - return { ...p, customPalettes: [...palettes, created] }; + return addItems("customPalettes", [created]); } const withoutDupe = target.colors.filter((c) => c.toLowerCase() !== hex.toLowerCase()); - const updated = { ...target, colors: [hex, ...withoutDupe] }; - return { ...p, customPalettes: palettes.map((c) => (c.id === target.id ? updated : c)) }; + return [replaceItem("customPalettes", { ...target, colors: [hex, ...withoutDupe] })]; }), removeColorFromCustomPalette: (paletteId, hex) => - setProject((p) => ({ - ...p, - customPalettes: p.customPalettes?.map((c) => - c.id === paletteId ? { ...c, colors: c.colors.filter((h) => h.toLowerCase() !== hex.toLowerCase()) } : c, - ), - })), + applyChange((p) => + patchItem(p, "customPalettes", paletteId, (c) => ({ + ...c, + colors: c.colors.filter((h) => h.toLowerCase() !== hex.toLowerCase()), + })), + ), - setCustomPaletteVisible: (id, visible) => - setProject((p) => ({ - ...p, - customPalettes: p.customPalettes?.map((c) => (c.id === id ? { ...c, visible } : c)), - })), + setCustomPaletteVisible: (id, visible) => applyChange((p) => patchItem(p, "customPalettes", id, { visible })), setBuiltinPaletteVisible: (bank, visible) => - setProject((p) => ({ - ...p, - builtinPaletteBanks: { ...p.builtinPaletteBanks, [bank]: visible }, - })), + applyChange((p) => [setField("builtinPaletteBanks", { ...p.builtinPaletteBanks, [bank]: visible })]), insertDrawingPoint: (drawingId, segIndex, pt) => applyChange((p) => diff --git a/src/state/resourceOps.test.ts b/src/state/resourceOps.test.ts new file mode 100644 index 00000000..62112681 --- /dev/null +++ b/src/state/resourceOps.test.ts @@ -0,0 +1,135 @@ +// Ressourcen, Stifte/Paletten, Text-Stile, Kontext-Schicht und 3D-Griffe laufen über Ops ([K4] S3): +// jede Aktion = genau ein Undo-Schritt, Ergebnis wie erwartet. Beim Umbau wurden 37 Schritte dieser Aktionen +// gegen die alte setProject-Fassung (git HEAD) verglichen: Projekt, Undo-Tiefe und Meldungen gleich. +import { beforeEach, describe, expect, it } from "vitest"; +import { getState } from "./appStore"; +import { sampleProject } from "../model/sampleProject"; +import type { ContextObject, Project } from "../model/types"; + +const st = () => getState(); + +beforeEach(() => { + const p: Project = { + ...structuredClone(sampleProject), + components: sampleProject.components.map((c, i) => (i === 0 ? { ...c, colorPenId: "p1" } : c)), + walls: sampleProject.walls.map((w, i) => (i === 0 ? { ...w, colorPenId: "p1" } : w)), + }; + st().setProject(p); + st().clearHistory(); +}); + +/** Eine Aktion → ein Undo-Schritt; Undo stellt das Projekt exakt wieder her. */ +function oneStep(label: string, act: () => void): void { + const before = st().project; + const depth = st().undoDepth; + act(); + expect(st().undoDepth, label).toBe(depth + 1); + st().undo(); + expect(JSON.parse(JSON.stringify(st().project)), label).toEqual(JSON.parse(JSON.stringify(before))); + st().redo(); +} + +describe("Ressourcen und Stiftsätze über Ops", () => { + it("Bauteile, Schraffuren, Linienstile: anlegen, ändern, geschütztes Löschen", () => { + const c0 = st().project.components[0].id; + const h0 = st().project.hatches[0].id; + oneStep("patchComponent", () => st().patchComponent(c0, { name: "X" })); + expect(st().project.components[0].name).toBe("X"); + oneStep("addComponent", () => st().addComponent()); + expect(st().project.components).toHaveLength(sampleProject.components.length + 1); + // Von einer Wandart verwendetes Bauteil: Meldung, keine Änderung, kein Undo-Schritt. + const depth = st().undoDepth; + st().deleteComponent(c0); + expect(st().undoDepth).toBe(depth); + oneStep("addHatch", () => st().addHatch()); + oneStep("patchHatch", () => st().patchHatch(h0, { scale: 3 })); + oneStep("addLineStyle", () => st().addLineStyle()); + oneStep("importHatches", () => st().importHatches([{ name: "H", pattern: "diagonal", scale: 1, angle: 0, color: "#000" }])); + }); + + it("Text-Stile: die Vorgaben werden beim ersten Ändern ins Projekt übernommen", () => { + expect(st().project.textStyles).toBeUndefined(); + oneStep("addTextStyle", () => st().addTextStyle()); + expect(st().project.textStyles!.length).toBeGreaterThan(1); + const id = st().project.textStyles![0].id; + oneStep("patchTextStyle", () => st().patchTextStyle(id, { label: "Neu" })); + expect(st().project.textStyles![0].label).toBe("Neu"); + }); + + it("Stifte: Stift anlegen, Stiftsatz aktivieren und Farbe ändern bäckt die Farben ein", () => { + oneStep("addPen", () => st().addPen()); + oneStep("addPenSet", () => st().addPenSet()); + const setId = st().project.penSets![0].id; + expect(st().project.activePenSetId).toBe(setId); // erster Satz wird aktiv + oneStep("patchPenSetColor", () => st().patchPenSetColor(setId, "p1", "#123456")); + // Bauteil und Wand mit `colorPenId: "p1"` tragen jetzt die gebackene Farbe — in einem Schritt. + expect(st().project.components[0].color).toBe("#123456"); + expect(st().project.walls[0].color).toBe("#123456"); + oneStep("patchPenSetWeight", () => st().patchPenSetWeight(setId, "p1", 0.7)); + expect(st().project.walls[0].strokeWeight).toBe(0.7); + oneStep("addPenSet 2", () => st().addPenSet()); + const set2 = st().project.penSets![1].id; + oneStep("patchPenSetColor inaktiv", () => st().patchPenSetColor(set2, "p1", "#abcdef")); + expect(st().project.walls[0].color).toBe("#123456"); // aktiver Satz unverändert + oneStep("setActivePenSet", () => st().setActivePenSet(set2)); + expect(st().project.walls[0].color).toBe("#abcdef"); + // Aktiver Satz ist geschützt. + const depth = st().undoDepth; + st().deletePenSet(set2); + expect(st().undoDepth).toBe(depth); + oneStep("deletePen", () => st().deletePen("p1")); + expect(st().project.components[0].colorPenId).toBeUndefined(); // Verweis gelöst, Farbe bleibt + oneStep("seedStandardPenSet", () => st().seedStandardPenSet()); + expect(st().project.pens).toHaveLength(255); + }); + + it("Farbpaletten", () => { + oneStep("addCustomPalette", () => st().addCustomPalette()); + const id = st().project.customPalettes![0].id; + oneStep("addColor", () => st().addColorToCustomPalette(id, "#ff0000")); + oneStep("addColor 2", () => st().addColorToCustomPalette(id, "#00ff00")); + oneStep("addColor Duplikat", () => st().addColorToCustomPalette(id, "#FF0000")); + expect(st().project.customPalettes![0].colors).toEqual(["#FF0000", "#00ff00"]); + oneStep("addColor neue Palette", () => st().addColorToCustomPalette(undefined, "#0000ff")); + expect(st().project.customPalettes).toHaveLength(2); + oneStep("removeColor", () => st().removeColorFromCustomPalette(id, "#00ff00")); + oneStep("builtin", () => st().setBuiltinPaletteVisible("ral", false)); + expect(st().project.builtinPaletteBanks).toMatchObject({ ral: false }); + }); +}); + +describe("Kontext-Schicht über Ops", () => { + const mesh = (id: string, categoryCode: string): ContextObject => + ({ id, type: "importedMesh", name: id, positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], indices: [0, 1, 2], categoryCode }) as unknown as ContextObject; + + it("Hinzufügen ergänzt fehlende Kategorien, Entfernen und Leeren je ein Schritt", () => { + const codes = (p: Project) => JSON.stringify(p.layers); + const before = codes(st().project); + oneStep("addContextObjects", () => st().addContextObjects([mesh("m1", "15"), mesh("m2", "15")])); + expect(st().project.context!.map((o) => o.id)).toEqual(["m1", "m2"]); + expect(codes(st().project)).not.toBe(before); + oneStep("removeContextObject", () => st().removeContextObject("m1")); + expect(st().project.context!.map((o) => o.id)).toEqual(["m2"]); + oneStep("removeContextObjects", () => st().removeContextObjects(["m2"])); + expect(st().project.context).toEqual([]); + }); +}); + +describe("3D-Griffe: Element und mitgeführte Ecken", () => { + it("ein Zug mit mehreren Maus-Schritten = ein Undo-Schritt (Gruppe mit Schlüssel)", () => { + const [a, b] = st().project.walls; + const depth = st().undoDepth; + for (let k = 1; k <= 6; k++) { + st().groupChanges(() => { + st().moveGripOf(null, a.id, 1, { x: a.end.x + k * 0.1, y: a.end.y }); + st().moveGripOf(null, b.id, 0, { x: a.end.x + k * 0.1, y: a.end.y }); + }, `grip3d:${a.id}:1`); + } + expect(st().undoDepth).toBe(depth + 1); + expect(st().project.walls[0].end.x).toBeCloseTo(a.end.x + 0.6, 12); + expect(st().project.walls[1].start.x).toBeCloseTo(a.end.x + 0.6, 12); + st().undo(); + expect(st().project.walls[0].end).toEqual(a.end); + expect(st().project.walls[1].start).toEqual(b.start); + }); +}); diff --git a/src/state/siteSlice.ts b/src/state/siteSlice.ts index 539fcbe0..0cd2cf64 100644 --- a/src/state/siteSlice.ts +++ b/src/state/siteSlice.ts @@ -4,14 +4,15 @@ // // Entwurfsentscheidung: `context` ist Teil von `project` (ein einziger // Wahrheits-Baum, konsistent mit projectSlice). Diese Slice MUTIERT daher -// `project.context` IMMUTABEL über die vorhandene `setProject`-Aktion -// (Cross-Slice), genau wie projectSlice ein neues Project-Objekt liefert. So -// bleiben Persistenz/Undo später einheitlich am Project hängen. +// `project.context` über die vorhandene `applyChange`-Aktion (Ops, Cross-Slice), +// genau wie projectSlice. So bleiben Persistenz/Undo einheitlich am Project hängen. // // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import { generateTerrainFromContours } from "../model/terrain"; import type { ContextObject, Project } from "../model/types"; +import { addItems, fieldOps, removeItems } from "../core/opsBuild"; +import type { CoreOp } from "../core/ops"; import { ensureContextCategories } from "../model/contextCategories"; import type { StoreApi } from "./store"; @@ -38,12 +39,12 @@ export interface SiteSlice { /** * Cross-Slice-Abhängigkeit: diese Slice liest `project` und schreibt es über - * `setProject` (beide aus projectSlice). Der Store komponiert SiteSlice mit + * `applyChange` (beide aus projectSlice). Der Store komponiert SiteSlice mit * dieser Sicht, sodass `get()`/Actions typsicher auf das Projekt zugreifen. */ type SiteSliceDeps = { project: Project; - setProject: (next: Project | ((p: Project) => Project)) => void; + applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[])) => void; }; export function createSiteSlice( @@ -51,13 +52,6 @@ export function createSiteSlice( ): SiteSlice { const { get } = api; - // Immutabler Kontext-Updater: ersetzt `project.context` über die vorhandene - // setProject-Aktion (konsistent mit projectSlice-Stil). - const setContext = ( - update: (ctx: ContextObject[]) => ContextObject[], - ): void => { - get().setProject((p) => ({ ...p, context: update(p.context ?? []) })); - }; // Wie `setContext`, aber fürs HINZUFÜGEN: ergänzt zusätzlich jede fehlende // Grafik-Kategorie der neu ankommenden Objekte in `project.layers` (s. @@ -69,11 +63,10 @@ export function createSiteSlice( const codes = added .map((o) => o.categoryCode) .filter((c): c is string => !!c); - get().setProject((p) => ({ - ...p, - context: [...(p.context ?? []), ...added], - layers: ensureContextCategories(p.layers, codes), - })); + get().applyChange((p) => [ + ...addItems("context", added), + ...fieldOps(p, "layers", ensureContextCategories(p.layers, codes)), + ]); }; return { @@ -81,13 +74,11 @@ export function createSiteSlice( addContextObjects: (objs) => addToContext(objs), - removeContextObject: (id) => - setContext((ctx) => ctx.filter((o) => o.id !== id)), + removeContextObject: (id) => get().applyChange((p) => removeItems(p, "context", [id])), removeContextObjects: (ids) => { if (ids.length === 0) return; - const drop = new Set(ids); - setContext((ctx) => ctx.filter((o) => !drop.has(o.id))); + get().applyChange((p) => removeItems(p, "context", ids)); }, generateTerrain: (contourSetId) => { @@ -102,6 +93,6 @@ export function createSiteSlice( return terrain.id; }, - clearContext: () => setContext(() => []), + clearContext: () => get().applyChange((p) => fieldOps(p, "context", [])), }; } diff --git a/src/ui/RoomProgramImportDialog.tsx b/src/ui/RoomProgramImportDialog.tsx index cd95fcbd..dae49c0f 100644 --- a/src/ui/RoomProgramImportDialog.tsx +++ b/src/ui/RoomProgramImportDialog.tsx @@ -9,8 +9,8 @@ import { useEffect, useMemo, useRef, useState } from "react"; import { createPortal } from "react-dom"; import { t } from "../i18n"; import type { TranslationKey } from "../i18n"; -import { applyRoomProgram, cellText, importedRows, mapRows, PROGRAM_FIELDS, readSheetFile, suggestMapping } from "../core"; -import type { ImportMode, Mapping, ProgramField, SheetData, SkipReason } from "../core"; +import { roomProgramOps, cellText, importedRows, mapRows, PROGRAM_FIELDS, readSheetFile, suggestMapping } from "../core"; +import type { CoreOp, ImportMode, Mapping, ProgramField, SheetData, SkipReason } from "../core"; import type { Project, RoomProgramRow } from "../model/types"; const FIELD_KEY: Record = { @@ -235,7 +235,7 @@ export function RoomProgramImportDialog({ fileName, sheets, existing, onImport, export interface RoomProgramImportButtonProps { project: Project; /** Übernimmt die Zeilen ins Projekt (ein Undo-Schritt). */ - onApply: (project: (p: Project) => Project) => void; + onApply: (build: (p: Project) => readonly CoreOp[]) => void; notify: (message: string, kind?: "info" | "warning" | "error") => void; } @@ -278,7 +278,7 @@ export function RoomProgramImportButton({ project, onApply, notify }: RoomProgra existing={project.roomProgram?.length ?? 0} onClose={() => setData(null)} onImport={(rows, mode) => { - onApply((p) => applyRoomProgram(p, rows, mode)); + onApply((p) => roomProgramOps(p, rows, mode)); notify(t("program.import.done", { n: rows.length })); setData(null); }} diff --git a/src/viewport/Wasm3DViewport.tsx b/src/viewport/Wasm3DViewport.tsx index 3e616454..00b7094e 100644 --- a/src/viewport/Wasm3DViewport.tsx +++ b/src/viewport/Wasm3DViewport.tsx @@ -327,6 +327,7 @@ export function Wasm3DViewport({ onEditRoofPitch, onEditWallTop, onEditEnd, + onEditGroup, section3d = null, onClearSection3d, commandActive = false, @@ -406,6 +407,12 @@ export function Wasm3DViewport({ onEditWallTop?: (wallId: string, topZ: number) => void; /** Ende eines Griff-Drags. */ onEditEnd?: () => void; + /** + * Fasst die Änderungen EINES Maus-Schritts (Element + mitgeführte Ecken anderer Elemente) zu einem + * Undo-Schritt zusammen; gleicher `key` über die Schritte eines Zugs = ein Schritt für den ganzen + * Zug ([K4] S3, Store `groupChanges`). Fehlt es, läuft `fn` direkt. + */ + onEditGroup?: (fn: () => void, key: string) => void; /** Aktive 3D-Schnittebene (world point+normal) aus der gebundenen Schnittlinie * (App-State, `sectionPlaneFromLevel`), oder `null` = kein Live-Schnitt. * Ersetzt den früheren lokalen Hardcode-Toggle. */ @@ -469,6 +476,14 @@ export function Wasm3DViewport({ onEditWallTopRef.current = onEditWallTop; const onEditEndRef = useRef(onEditEnd); onEditEndRef.current = onEditEnd; + const onEditGroupRef = useRef(onEditGroup); + onEditGroupRef.current = onEditGroup; + /** Ein Maus-Schritt als Gruppe (ein Undo-Schritt je Zug), s. `onEditGroup`. */ + const editGroup = (key: string, fn: () => void) => { + const g = onEditGroupRef.current; + if (g) g(fn, key); + else fn(); + }; const onGrip3dEditTabRef = useRef(onGrip3dEditTab); onGrip3dEditTabRef.current = onGrip3dEditTab; const onGrip3dEditCancelRef = useRef(onGrip3dEditCancel); @@ -1075,20 +1090,25 @@ export function Wasm3DViewport({ : axisLock === "y" ? { x: anchor.x, y: model.y } : applyAngleConstraint(anchor, model, 45); - const applied = constrained - ? (onEditVertexRef.current?.(drag.target, drag.index, constrained) ?? constrained) - : (onEditVertexRef.current?.( - drag.target, - drag.index, - model, - drag.excludeWallIds, - drag.excludeDrawingIds, - ) ?? model); - // Koinzidente Endpunkte ANDERER gewählter Elemente mitführen — exakt - // auf denselben (ggf. gesnappten) Punkt, ohne erneut zu snappen. - for (const c of drag.coincident) { - onEditVertexRef.current?.(c.target, c.index, applied); - } + // Element und mitgeführte Ecken = EIN Undo-Schritt für den ganzen Zug (Gruppe mit Schlüssel). + let applied: Vec2 = model; + const t0 = drag.target; + editGroup(`grip3d:${t0.wallId ?? t0.drawingId ?? t0.ceilingId ?? t0.roofId ?? ""}:${drag.index}`, () => { + applied = constrained + ? (onEditVertexRef.current?.(drag.target, drag.index, constrained) ?? constrained) + : (onEditVertexRef.current?.( + drag.target, + drag.index, + model, + drag.excludeWallIds, + drag.excludeDrawingIds, + ) ?? model); + // Koinzidente Endpunkte ANDERER gewählter Elemente mitführen — exakt + // auf denselben (ggf. gesnappten) Punkt, ohne erneut zu snappen. + for (const c of drag.coincident) { + onEditVertexRef.current?.(c.target, c.index, applied); + } + }); return; } if (drag.kind === "edge") { @@ -1124,14 +1144,17 @@ export function Wasm3DViewport({ y: constrainedModel.y - drag.lastModel.y, }; if (delta.x !== 0 || delta.y !== 0) { - onEditBodyRef.current?.(drag.target, delta, !!moveAxisLock || shiftKey); - // Koinzidente Sibling-Ecken (ANDERER gewählter Elemente) um dasselbe - // Delta mitführen — ihre LIVE-Position wird inkrementell - // fortgeschrieben und absolut neu gesetzt (kein Snap). - for (const c of drag.moveCoincident) { - c.pos = { x: c.pos.x + delta.x, y: c.pos.y + delta.y }; - onEditVertexRef.current?.(c.target, c.index, c.pos); - } + const t1 = drag.target; + editGroup(`grip3dMove:${t1.wallId ?? t1.drawingId ?? t1.ceilingId ?? t1.roofId ?? ""}`, () => { + onEditBodyRef.current?.(drag.target, delta, !!moveAxisLock || shiftKey); + // Koinzidente Sibling-Ecken (ANDERER gewählter Elemente) um dasselbe + // Delta mitführen — ihre LIVE-Position wird inkrementell + // fortgeschrieben und absolut neu gesetzt (kein Snap). + for (const c of drag.moveCoincident) { + c.pos = { x: c.pos.x + delta.x, y: c.pos.y + delta.y }; + onEditVertexRef.current?.(c.target, c.index, c.pos); + } + }); } } drag.lastModel = constrainedModel; diff --git a/src/views/viewportContent.tsx b/src/views/viewportContent.tsx index 6bb2f1ee..568016ca 100644 --- a/src/views/viewportContent.tsx +++ b/src/views/viewportContent.tsx @@ -138,6 +138,7 @@ export function Content({ onEdit3dRoofPitch, onEdit3dWallTop, onEdit3dEnd, + onEdit3dGroup, onGrip3dEditTab, onGrip3dEditCancel, }: { @@ -258,6 +259,8 @@ export function Content({ onEdit3dRoofPitch: (roofId: string, apexHeight: number) => void; onEdit3dWallTop: (wallId: string, topZ: number) => void; onEdit3dEnd: () => void; + /** Maus-Schritt eines 3D-Griff-Zugs als Gruppe mit Schlüssel (ein Undo-Schritt je Zug). */ + onEdit3dGroup?: (fn: () => void, key: string) => void; /** Tab während eines laufenden 3D-Griff-Drags (Endpunkt/Verschieben): Feld- * Controller fürs Cursor-HUD öffnen/zykeln, s. App.tsx `cycleGrip3dEditField`. */ onGrip3dEditTab?: () => void; @@ -471,6 +474,7 @@ export function Content({ onEditRoofPitch={onEdit3dRoofPitch} onEditWallTop={onEdit3dWallTop} onEditEnd={onEdit3dEnd} + onEditGroup={onEdit3dGroup} onGrip3dEditTab={onGrip3dEditTab} onGrip3dEditCancel={onGrip3dEditCancel} />