From fc41dcd9a62b3d945fa2ed6e3c18783592e51894 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 22:37:41 +0000 Subject: [PATCH] [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);