diff --git a/src/core/boundary.test.ts b/src/core/boundary.test.ts index cdc6febe..f4bc0653 100644 --- a/src/core/boundary.test.ts +++ b/src/core/boundary.test.ts @@ -14,7 +14,7 @@ import { readdirSync, readFileSync, statSync } from "node:fs"; import { dirname, join, normalize, relative, sep } from "node:path"; const SRC = join(process.cwd(), "src"); -const CORE_DIRS = new Set(["model", "geometry", "plan", "io", "export", "analysis", "materials", "text", "engine"]); +const CORE_DIRS = new Set(["core", "model", "geometry", "plan", "io", "export", "analysis", "materials", "text", "engine"]); const SHELL_DIRS = new Set(["ui", "panels", "views", "menus", "editors", "viewport", "native", "tools", "state", "commands"]); const FACADE_DIRS = new Set(["plan", "geometry"]); const FORBIDDEN_PACKAGES = /^(react|react-dom|zustand|@tauri-apps\/.*)$/; diff --git a/src/core/ops.test.ts b/src/core/ops.test.ts new file mode 100644 index 00000000..b0562640 --- /dev/null +++ b/src/core/ops.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from "vitest"; +import { applyOps, diffToOps, validateProject } from "./ops"; +import type { CoreOp } from "./ops"; +import { sampleProject } from "../model/sampleProject"; +import type { Project } from "../model/types"; + +const roundtrip = (ops: CoreOp[]): CoreOp[] => JSON.parse(JSON.stringify(ops)); + +/** Zufällige, aber deterministische Änderung eines Projekts. */ +function mutate(p: Project, seed: number): Project { + let x = seed; + const rnd = () => ((x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296); + let out = { ...p }; + const walls = [...out.walls]; + if (rnd() < 0.5 && walls.length) walls.splice(Math.floor(rnd() * walls.length), 1); + if (rnd() < 0.7 && walls.length) { + const i = Math.floor(rnd() * walls.length); + walls[i] = { ...walls[i], height: (walls[i].height ?? 2.6) + rnd() }; + } + if (rnd() < 0.6) walls.splice(Math.floor(rnd() * (walls.length + 1)), 0, { ...p.walls[0], id: `new-${seed}-a` }, { ...p.walls[0], id: `new-${seed}-b` }); + if (rnd() < 0.4) walls.reverse(); + out = { ...out, walls }; + if (rnd() < 0.5) out = { ...out, name: `n${seed}` }; + if (rnd() < 0.3) out = { ...out, referenceElevationMasl: rnd() * 500 }; + if (rnd() < 0.3) out = { ...out, geoAnchor: undefined }; + if (rnd() < 0.5) out = { ...out, drawings2d: [] }; + return out; +} + +describe("CoreOps", () => { + it("keine Änderung: keine Ops", () => { + expect(diffToOps(sampleProject, sampleProject)).toEqual([]); + }); + + it("Roundtrip: apply(JSON(diff)) ergibt das Zielprojekt, für viele zufällige Änderungen", () => { + for (let seed = 1; seed <= 200; seed++) { + const next = mutate(sampleProject, seed); + const ops = roundtrip(diffToOps(sampleProject, next)); + expect(applyOps(sampleProject, ops)).toEqual(next); + } + }); + + it("unveränderte Elemente behalten ihre Objekt-Identität", () => { + const next = { ...sampleProject, walls: [...sampleProject.walls, { ...sampleProject.walls[0], id: "x-neu" }] }; + const out = applyOps(sampleProject, diffToOps(sampleProject, next)); + expect(out.walls[0]).toBe(sampleProject.walls[0]); + expect(out.walls).toHaveLength(sampleProject.walls.length + 1); + }); + + it("jede Op-Art übersteht JSON ohne Unterschied", () => { + const w = sampleProject.walls[0]; + const ops: CoreOp[] = [ + { kind: "add", collection: "walls", items: [{ ...w, id: "z1" }], at: 0 }, + { kind: "replace", collection: "walls", entity: { ...w, height: 9 } }, + { kind: "reorder", collection: "walls", ids: [w.id] }, + { kind: "remove", collection: "walls", ids: ["z1"] }, + { kind: "setField", key: "name", value: "J" }, + { kind: "setField", key: "geoAnchor" }, + ]; + expect(applyOps(sampleProject, roundtrip(ops))).toEqual(applyOps(sampleProject, ops)); + }); + + it("Feld entfernen und Listen ohne ids als ganzes Feld", () => { + const withAnchor = { ...sampleProject, referenceElevationMasl: 400 } as Project; + const next = { ...withAnchor, referenceElevationMasl: undefined } as Project; + const ops = diffToOps(withAnchor, next); + expect(ops).toEqual([{ kind: "setField", key: "referenceElevationMasl" }]); + expect("referenceElevationMasl" in applyOps(withAnchor, ops)).toBe(false); + }); + + it("Fuzz: beliebige Op-Folgen (auch Unsinn) werfen nicht und lassen das Original unberührt", () => { + const snapshot = JSON.stringify(sampleProject); + const junk: CoreOp[] = [ + { kind: "replace", collection: "doesNotExist", entity: { id: "q" } }, + { kind: "remove", collection: "walls", ids: ["gibt-es-nicht"] }, + { kind: "reorder", collection: "walls", ids: ["nope", "nada"] }, + { kind: "add", collection: "walls", items: [], at: -5 }, + { kind: "add", collection: "walls", items: [{ id: "q" }], at: 99999 }, + { kind: "setField", key: "walls", value: "kaputt" }, + ]; + for (let i = 0; i < junk.length; i++) expect(() => applyOps(sampleProject, junk.slice(0, i + 1))).not.toThrow(); + expect(JSON.stringify(sampleProject)).toBe(snapshot); + }); + + it("Validierung: gültiges Beispielprojekt ok; NaN und doppelte ids werden gemeldet", () => { + expect(validateProject(sampleProject)).toEqual([]); + const w = sampleProject.walls[0]; + const bad = { ...sampleProject, walls: [...sampleProject.walls, { ...w }] }; + expect(validateProject(bad).join()).toMatch(/Doppelte ids/); + const nan = { ...sampleProject, walls: [{ ...w, height: NaN }, ...sampleProject.walls.slice(1)] }; + expect(validateProject(nan).join()).toMatch(/nicht endlich/); + }); +}); diff --git a/src/core/ops.ts b/src/core/ops.ts new file mode 100644 index 00000000..03e761da --- /dev/null +++ b/src/core/ops.ts @@ -0,0 +1,228 @@ +// Änderungen am Projekt als DATEN (Phase B der Kern/UI-Trennung, docs/core-ui-split.md; +// lessons-bimcraft [6]/[8], Grundlage für [7] und [16]). +// +// Die interaktive Befehlslogik (Schritte, Prompts, Vorschau, Panels, Griffe) bleibt in der Hülle +// und liefert weiterhin Projekt → Projekt-Funktionen. `setProject` übersetzt jede Änderung +// über {@link diffToOps} in eine Folge von {@link CoreOp}s und wendet SIE mit {@link applyOps} +// an — das Projekt ändert sich ausschliesslich durch Ops. Ops sind JSON-serialisierbar +// (Undo-Verlauf [84], Makros [85], MCP [9], später ein Rust-Kern). +// +// Granularität (bewusst grob, aber stabil): +// • Listen aus Elementen mit `id` (walls, ceilings, drawings2d, …): `add` / `replace` / `remove` +// / `reorder` je Element — unveränderte Elemente behalten ihre Objekt-Identität +// (structural sharing, billiger Änderungstest für Plan/Schnitt/3D). +// • Alles andere (Skalare, Objekte, Listen ohne ids): `setField` mit dem ganzen Wert. + +import type { Project } from "../model/types"; + +type Entity = { id: string } & Record; + +export type CoreOp = + /** Fügt Elemente an `at` (Default: Ende) in die Liste `collection` ein. */ + | { kind: "add"; collection: string; items: Entity[]; at?: number } + /** Ersetzt das Element mit `entity.id` in `collection` (Position bleibt). */ + | { kind: "replace"; collection: string; entity: Entity } + /** Entfernt Elemente per id. */ + | { kind: "remove"; collection: string; ids: string[] } + /** Setzt die Reihenfolge der Liste (`ids` ist eine Permutation der vorhandenen ids). */ + | { kind: "reorder"; collection: string; ids: string[] } + /** Setzt ein Projekt-Feld auf `value` (`undefined`/fehlend ⇒ Feld entfernen). */ + | { kind: "setField"; key: string; value?: unknown }; + +const isEntityList = (v: unknown): v is Entity[] => + Array.isArray(v) && v.length > 0 && v.every((x) => x !== null && typeof x === "object" && typeof (x as Entity).id === "string"); + +/** Ob `v` eine (auch leere) Liste ist, deren Elemente — falls vorhanden — alle `id`s tragen. */ +const isIdList = (v: unknown): v is Entity[] => Array.isArray(v) && (v.length === 0 || isEntityList(v)); + +/** Eindeutige ids? (Voraussetzung für die Element-Ops.) */ +function uniqueIds(list: Entity[]): boolean { + const seen = new Set(); + for (const e of list) { + if (seen.has(e.id)) return false; + seen.add(e.id); + } + return true; +} + +/** + * Berechnet die Ops, die `prev` in `next` überführen. `applyOps(prev, diffToOps(prev, next))` + * ist inhaltlich gleich `next` (Test), Elemente aus `next` behalten ihre Identität. + */ +export function diffToOps(prev: Project, next: Project): CoreOp[] { + if (prev === next) return []; + const ops: CoreOp[] = []; + const a = prev as unknown as Record; + const b = next as unknown as Record; + const keys = new Set([...Object.keys(a), ...Object.keys(b)]); + for (const key of keys) { + const va = a[key]; + const vb = b[key]; + if (va === vb) continue; + if (isIdList(va) && isIdList(vb) && uniqueIds(va) && uniqueIds(vb)) { + diffList(key, va, vb, ops); + } else { + ops.push(vb === undefined ? { kind: "setField", key } : { kind: "setField", key, value: vb }); + } + } + return ops; +} + +function diffList(collection: string, va: Entity[], vb: Entity[], ops: CoreOp[]): void { + const inB = new Set(vb.map((e) => e.id)); + const mapA = new Map(va.map((e) => [e.id, e])); + const removed = va.filter((e) => !inB.has(e.id)).map((e) => e.id); + if (removed.length) ops.push({ kind: "remove", collection, ids: removed }); + // Geänderte Elemente (gleiche id, andere Referenz). + for (const e of vb) { + const old = mapA.get(e.id); + if (old !== undefined && old !== e) ops.push({ kind: "replace", collection, entity: e }); + } + // Reihenfolge der behaltenen Elemente in vb. + const kept = va.filter((e) => inB.has(e.id)).map((e) => e.id); + const keptSet = new Set(kept); + const keptInB = vb.map((e) => e.id).filter((id) => keptSet.has(id)); + if (keptInB.some((id, idx) => id !== kept[idx])) ops.push({ kind: "reorder", collection, ids: keptInB }); + // Neue Elemente: zusammenhängende Läufe, von links nach rechts direkt an ihrer Zielposition + // in `vb` eingefügt (frühere Läufe stehen dann schon, die Position stimmt). + let i = 0; + while (i < vb.length) { + if (keptSet.has(vb[i].id)) { + i++; + continue; + } + const at = i; + const run: Entity[] = []; + while (i < vb.length && !keptSet.has(vb[i].id)) run.push(vb[i++]); + ops.push({ kind: "add", collection, items: run, at }); + } +} + +/** Wendet eine Op-Folge rein an (kein Zugriff auf Store/UI). */ +export function applyOps(project: Project, ops: readonly CoreOp[]): Project { + let cur = project as unknown as Record; + for (const op of ops) cur = applyOne(cur, op); + return cur as unknown as Project; +} + +function listOf(cur: Record, collection: string): Entity[] { + const v = cur[collection]; + return Array.isArray(v) ? (v as Entity[]) : []; +} + +function applyOne(cur: Record, op: CoreOp): Record { + switch (op.kind) { + case "setField": { + const next = { ...cur }; + if (op.value === undefined) delete next[op.key]; + else next[op.key] = op.value; + return next; + } + case "add": { + const list = listOf(cur, op.collection); + const at = op.at === undefined ? list.length : Math.max(0, Math.min(list.length, op.at)); + return { ...cur, [op.collection]: [...list.slice(0, at), ...op.items, ...list.slice(at)] }; + } + case "replace": { + const list = listOf(cur, op.collection); + const idx = list.findIndex((e) => e.id === op.entity.id); + if (idx < 0) return { ...cur, [op.collection]: [...list, op.entity] }; + const out = list.slice(); + out[idx] = op.entity; + return { ...cur, [op.collection]: out }; + } + case "remove": { + const drop = new Set(op.ids); + return { ...cur, [op.collection]: listOf(cur, op.collection).filter((e) => !drop.has(e.id)) }; + } + case "reorder": { + const list = listOf(cur, op.collection); + const byId = new Map(list.map((e) => [e.id, e])); + const ordered = op.ids.map((id) => byId.get(id)).filter((e): e is Entity => e !== undefined); + const inOps = new Set(op.ids); + return { ...cur, [op.collection]: [...ordered, ...list.filter((e) => !inOps.has(e.id))] }; + } + } +} + +// ── Validierung ([7]) ──────────────────────────────────────────────────────── + +/** + * Prüft ein Projekt auf Verstösse, die nie gewollt sind: nicht endliche Zahlen in Geometrie + * und doppelte ids innerhalb einer Liste. Liefert Meldungen (leer = gültig). Bewusst + * konservativ — gesperrt wird nur, was sicher kaputt ist. + */ +export function validateProject(p: Project): string[] { + const problems: string[] = []; + const rec = p as unknown as Record; + for (const key of Object.keys(rec)) { + const v = rec[key]; + if (!isIdList(v) || v.length === 0) continue; + if (!uniqueIds(v)) problems.push(`Doppelte ids in „${key}".`); + // Nicht endliche Zahlen in den Elementen (flache Suche bis Tiefe 3, ohne grosse Zahlenfelder). + for (const e of v) { + const bad = findNonFinite(e, 0); + if (bad) { + problems.push(`„${key}" ${e.id}: ${bad} ist nicht endlich.`); + break; + } + } + } + return problems; +} + +/** + * Wie {@link validateProject}, aber nur für das, was `ops` anfassen (billig genug für jeden + * Maus-Schritt eines Drags): nicht endliche Zahlen in neuen/ersetzten Elementen, doppelte ids + * in den betroffenen Listen, nicht endliche `setField`-Zahlen. + */ +export function validateOps(after: Project, ops: readonly CoreOp[], before?: Project): string[] { + const beforeRec = before as unknown as Record | undefined; + /** Alt-Dateien mit doppelten ids sollen weiter änderbar bleiben: nur NEUE Doppelungen melden. */ + const hadDup = (key: string) => { + const l = beforeRec?.[key]; + return isIdList(l) && !uniqueIds(l); + }; + const problems: string[] = []; + const rec = after as unknown as Record; + const dupChecked = new Set(); + for (const op of ops) { + if (op.kind === "add" || op.kind === "replace") { + const ents = op.kind === "add" ? op.items : [op.entity]; + for (const e of ents) { + const bad = findNonFinite(e, 0); + if (bad) problems.push(`„${op.collection}" ${e.id}: ${bad} ist nicht endlich.`); + } + if (op.kind === "add" && !dupChecked.has(op.collection)) { + dupChecked.add(op.collection); + const list = rec[op.collection]; + if (isIdList(list) && !uniqueIds(list) && !hadDup(op.collection)) problems.push(`Doppelte ids in „${op.collection}".`); + } + } else if (op.kind === "setField") { + if (typeof op.value === "number" && !Number.isFinite(op.value)) { + problems.push(`Feld „${op.key}": ${String(op.value)} ist nicht endlich.`); + } else if (isEntityList(op.value) && !uniqueIds(op.value) && !hadDup(op.key)) { + problems.push(`Doppelte ids in „${op.key}".`); + } + } + } + return problems; +} + +function findNonFinite(v: unknown, depth: number): string | null { + if (typeof v === "number") return Number.isFinite(v) ? null : String(v); + if (depth > 3 || v === null || typeof v !== "object") return null; + if (Array.isArray(v)) { + if (v.length > 5000) return null; // Mesh-Arrays: nicht durchlaufen + for (const x of v) { + const r = findNonFinite(x, depth + 1); + if (r) return r; + } + return null; + } + for (const x of Object.values(v as Record)) { + const r = findNonFinite(x, depth + 1); + if (r) return r; + } + return null; +} diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 18134e66..3cec15ef 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -1756,6 +1756,7 @@ export const de = { "recover.restore": "Wiederherstellen", "recover.discard": "Verwerfen", "recover.later": "Später", + "project.change.rejected": "Änderung abgelehnt:", "project.open.failed": "Projekt konnte nicht geöffnet werden.", "menu.native.clashCheck": "Kollisionsprüfung …", "clash.none": "Keine Kollisionen gefunden.", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 4a0e7172..4044c3ed 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1717,6 +1717,7 @@ export const en: Record = { "recover.restore": "Restore", "recover.discard": "Discard", "recover.later": "Later", + "project.change.rejected": "Change rejected:", "project.open.failed": "Project could not be opened.", "menu.native.clashCheck": "Clash detection …", "clash.none": "No clashes found.", diff --git a/src/state/projectSlice.ts b/src/state/projectSlice.ts index 34b9ff7d..5282caa5 100644 --- a/src/state/projectSlice.ts +++ b/src/state/projectSlice.ts @@ -8,6 +8,8 @@ // laufen. Die Slice tippt daher nur ihre eigenen Felder; `get()` liefert // RootState (siehe appStore.ts), wir greifen punktuell auf View-Felder zu. +import { applyOps, diffToOps, validateOps } from "../core/ops"; +import type { CoreOp } from "../core/ops"; import { withVertexType, type PolylineVertexType } from "../core"; import { sampleProject } from "../model/sampleProject"; import { @@ -69,6 +71,8 @@ export interface ProjectSlice { * Implementierung unten. */ setProject: (next: Project | ((p: Project) => Project), coalesceKey?: string) => void; + /** Die zuletzt angewendeten Ops (JSON-serialisierbar), jüngste zuletzt. */ + recentOps: () => CoreOp[][]; // ── Zeichnungsebenen (Levels/Geschosse) ────────────────────────────────── toggleLevelVisible: (id: string) => void; @@ -444,6 +448,9 @@ export function createProjectSlice( let lastCoalesceKey: string | undefined; let lastCoalesceAt = 0; const COALESCE_WINDOW_MS = 400; + // Protokoll der angewendeten Ops (jüngste zuletzt) — Rohstoff für Undo-Verlauf [84], Makros [85]. + const opLog: CoreOp[][] = []; + const OP_LOG_LIMIT = 200; const history = createHistorySlice( api as unknown as StoreApi, @@ -467,13 +474,27 @@ export function createProjectSlice( coalesceKey?: string, ) => set((s) => { - const nextProject = + const wanted = typeof next === "function" ? (next as (p: Project) => Project)(s.project) : next; // No-Op-Schutz: echte Immutable-Updates liefern bei tatsächlicher // Änderung immer eine NEUE Referenz — bleibt sie gleich, gab es keine // Änderung, also kein History-Eintrag (und `set` selbst benachrichtigt // dann ebenfalls nicht, da der Patch leer ist). - if (nextProject === s.project) return {}; + if (wanted === s.project) return {}; + // Das Projekt ändert sich NUR über Ops (core/ops.ts): die gewünschte Änderung wird in + // eine Op-Folge übersetzt, validiert und angewendet. Verstösse (NaN, doppelte ids) + // werden zurückgerollt und gemeldet. + const ops = diffToOps(s.project, wanted); + if (ops.length === 0) return {}; + const nextProject = applyOps(s.project, ops); + const problems = validateOps(nextProject, ops, s.project); + if (problems.length > 0) { + console.warn("Projektänderung verworfen:", problems); + queueMicrotask(() => get().notify(`${t("project.change.rejected")} ${problems[0]}`, "error")); + return {}; + } + opLog.push(ops); + if (opLog.length > OP_LOG_LIMIT) opLog.shift(); const now = Date.now(); const coalesced = coalesceKey !== undefined && @@ -495,6 +516,7 @@ export function createProjectSlice( project: sampleProject, setProject, + recentOps: () => opLog.slice(), // ── Zeichnungsebenen ─────────────────────────────────────────────────── toggleLevelVisible: (id) => diff --git a/src/state/setProjectOps.test.ts b/src/state/setProjectOps.test.ts new file mode 100644 index 00000000..c99424ed --- /dev/null +++ b/src/state/setProjectOps.test.ts @@ -0,0 +1,38 @@ +// setProject läuft über Ops (core/ops.ts): das Ergebnis muss dem gewünschten Projekt gleichen, +// ungültige Änderungen werden zurückgerollt, Ops werden protokolliert und sind JSON-fähig. +import { describe, expect, it } from "vitest"; +import { getState } from "./appStore"; +import { sampleProject } from "../model/sampleProject"; + +const st = () => getState(); + +describe("setProject über CoreOps", () => { + it("Änderung kommt unverändert an, Op wird protokolliert (JSON-fähig), Undo stellt zurück", () => { + st().setProject(structuredClone(sampleProject)); + const before = st().project; + const w = before.walls[0]; + const wanted = { ...before, walls: [{ ...w, height: (w.height ?? 2.6) + 1 }, ...before.walls.slice(1)] }; + st().setProject(wanted); + expect(st().project).toEqual(wanted); + const ops = st().recentOps(); + expect(ops.length).toBeGreaterThan(0); + expect(JSON.parse(JSON.stringify(ops.at(-1)))).toEqual(ops.at(-1)); + st().undo(); + expect(st().project).toBe(before); + }); + + it("NaN-Änderung wird verworfen, Projekt bleibt, Undo-Stapel unverändert", () => { + const before = st().project; + const depth = st().undoStack.length; + const w = before.walls[0]; + st().setProject({ ...before, walls: [{ ...w, height: NaN }, ...before.walls.slice(1)] }); + expect(st().project).toBe(before); + expect(st().undoStack.length).toBe(depth); + }); + + it("doppelte ids beim Einfügen werden verworfen", () => { + const before = st().project; + st().setProject({ ...before, walls: [...before.walls, { ...before.walls[0] }] }); + expect(st().project).toBe(before); + }); +});