diff --git a/TODO.md b/TODO.md index 997613cb..1ad1ec6e 100644 --- a/TODO.md +++ b/TODO.md @@ -149,8 +149,31 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern Nächste: Export (Schedule/CSV, STL/OBJ, STEP), Plan/Schnitt/Ansicht-Sammler (generatePlan, toSection, toElevation) — hängt an Plan-Puffer v2. Ziel: Plan/Schnitt/Ansicht, 3D, Export rechnen mit `doc`-Handle statt flach gesammelter Arrays; TS-Sammler/-Adapter werden gelöscht ([K3d] hängt hier dran: Plan-Puffer v2 mit Pick-IDs und vollem Primitive-Umfang). - - ○ **S3 Änderungen kommen aus Rust**: Befehle (Zustandsautomaten, Werkzeuge) erzeugen Ops im Kern; Undo/Redo, Validierung + - ◐ **S3 Änderungen kommen aus Rust**: Befehle (Zustandsautomaten, Werkzeuge) erzeugen Ops im Kern; Undo/Redo, Validierung (`validateOps`) und Gruppen/Ebenen-Logik wandern nach Rust; `diffToOps` entfällt, TS hält nur noch eine Leseansicht. + **Erste Etappe (28.10.): Ops, Prüfung, Undo/Redo im Kern.** `core/src/ops.rs` (Op, Prüfung bitgleich zur TS-Fassung — gleiche + Ablehnungen und Meldungen; NaN/±Infinity reisen als Marken `"\u0001NaN"`, weil JSON sie nicht kennt), `document.rs` + `commit`/`undo`/`redo`: atomar anwenden, prüfen, bei Verstoss über die inversen Ops zurückrollen; Verlauf als **inverse Ops** + statt Schnappschüssen (feine Inverse je Op, Feld-Sicherung nur bei Alt-Doppelungen/fehlendem Feld; Feld-Position wird mit + zurückgegeben, Undo ist JSON-exakt). coalesceKey + Zeitfenster (400 ms) und Gruppen (`doc_group_begin/end`, Store + `groupChanges`) = ein Schritt; Drag-Serien werden verdichtet (wachsen nicht je Mausbewegung); Grenzen 100 Schritte / + 256 MiB (älteste fallen weg). Store: `setProject` → `diffToOps` → `ProjectDocument.commit` (Kern) → TS führt die + Leseansicht mit denselben Ops nach (`applyOps`); `undo`/`redo` holen die Ops aus dem Kern (`doc_undo`/`doc_redo`). + TS-Snapshot-Undo und TS-`validateOps`/`validateProject`-Rechnung gelöscht (Fassaden über `ops_validate`/`project_validate`). + Das Store-Dokument ist zugleich das Abfrage-Dokument (`documentFor` → kein zweiter Spiegel). Store-Felder + `undoStack/redoStack` → `undoDepth/redoDepth`, `clearHistory()`. + **Entscheid Richtung (28.10.):** halb umgedreht. Der Kern ist Autorität für Prüfung und Verlauf; das TS-Projekt ist eine + Leseansicht, die nur mit Ops nachgeführt wird, die der Kern angenommen (`commit`) oder geliefert (Undo/Redo) hat — so kann + sie nicht auseinanderlaufen (Test: 1000 Zufallsänderungen, Undo bis Anfang/Redo bis Ende, Kern-JSON == TS-Projekt). + `diffToOps` bleibt vorerst als Adapter, weil ~50 Store-Aktionen, Griffe, Panels und `src/commands` noch Projekt → Projekt + liefern; die volle Umkehr (ganzes Projekt als JSON zurück) ist verworfen: sie kostet je Schritt Parse-Zeit und zerstört die + Objekt-Identität unveränderter Elemente, auf der die Plan-/3D-Caches beruhen. Patches (Ops) erhalten sie. Änderungen vorbei an + den Ops (direktes `setState` in Tests) zieht der Spiegel per Differenz nach und leert den Verlauf. + **Messung** (Linux-Container): Kern nativ (release), 5000 Wände: commit 51 µs, Undo 37 µs, Redo 36 µs je Schritt. Über WASM im + Store-Weg (vitest, 3000 Wände, 500 Schritte): 2,6 ms/Schritt, davon `diffToOps`+`applyOps` in TS ≈ 2,0 ms, Kern-Commit ≈ 0,4 ms; + Undo 0,08 ms, Redo 0,07 ms; Verlauf ≈ 780 KiB für 500 Schritte. + Offen: Befehle/Store-Aktionen erzeugen Ops direkt (dann entfällt `diffToOps`, der grösste Kostenanteil); `applyOps` bleibt als + Patch-Anwendung der Leseansicht; Ebenen-/Gruppen-Logik (`groupActions.ts`) nach Rust; Undo-Verlauf als Liste in der UI [84]. - ○ **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 @@ -240,8 +263,10 @@ 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. · L -- ○ **[7] Zentrale Validierung nach jedem Befehl.** · M -- ◐ **[8] Undo über Befehle.** Undo existiert (Snapshots, coalesceKey), nicht befehlsbasiert. · M +- ◐ **[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 + Snapshots mehr ([K4] S3). Offen: Befehle erzeugen Ops direkt statt `diffToOps`. · M - ◐ **[9] MCP-Brücke.** Headless `dossier-cli … mcp`; Brücke zum offenen Fenster fehlt. · M ### Daten diff --git a/src/core/document.history.test.ts b/src/core/document.history.test.ts new file mode 100644 index 00000000..874ac3ec --- /dev/null +++ b/src/core/document.history.test.ts @@ -0,0 +1,179 @@ +// Undo/Redo im Kern ([K4] S3, [8]): Änderungen laufen über `ProjectDocument.commit` (Prüfung + +// Verlauf in Rust), Undo/Redo liefern Ops, mit denen die TS-Leseansicht nachgeführt wird. +import { describe, expect, it } from "vitest"; +import { ProjectDocument } from "./document"; +import { diffToOps, validateOps, validateProject } from "./ops"; +import type { CoreOp } from "./ops"; +import { sampleProject } from "../model/sampleProject"; +import type { Project, Wall } from "../model/types"; + +const plain = (p: Project): unknown => JSON.parse(JSON.stringify(p)); + +/** Zufällige, deterministische Änderung (Wände, Felder, Reihenfolgen, Listen ersetzen). */ +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]; + const r = rnd(); + if (r < 0.2 && walls.length) walls.splice(Math.floor(rnd() * walls.length), 1); + else if (r < 0.55 && walls.length) { + const i = Math.floor(rnd() * walls.length); + walls[i] = { ...walls[i], height: Math.round(((walls[i].height ?? 2.6) + rnd()) * 1000) / 1000 }; + } else if (r < 0.75) { + walls.splice(Math.floor(rnd() * (walls.length + 1)), 0, { ...sampleProject.walls[0], id: `n${seed}` }); + } else if (r < 0.82) walls.reverse(); + out = { ...out, walls }; + const f = rnd(); + if (f < 0.15) out = { ...out, name: `n${seed}` }; + else if (f < 0.25) out = { ...out, referenceElevationMasl: Math.round(rnd() * 500) }; + else if (f < 0.32) out = { ...out, referenceElevationMasl: undefined }; + else if (f < 0.38) out = { ...out, geoAnchor: out.geoAnchor ? undefined : sampleProject.geoAnchor }; + else if (f < 0.42) out = { ...out, drawings2d: out.drawings2d.length ? [] : sampleProject.drawings2d }; + return out; +} + +describe("Undo/Redo im Kern-Dokument", () => { + it("1000 Zufallsänderungen: Undo bis zum Anfang = Ausgangsprojekt, Redo bis zum Ende = Endprojekt", () => { + const d = new ProjectDocument(sampleProject); + d.setHistoryLimits(5000, 1 << 30); + let cur: Project = sampleProject; + let steps = 0; + for (let seed = 1; seed <= 1000; seed++) { + const next = mutate(cur, seed); + const ops = diffToOps(cur, next); + if (!ops.length) continue; + const r = d.commit(cur, ops, undefined, seed * 1000); + expect("project" in r, `seed ${seed}`).toBe(true); + if ("project" in r) cur = r.project; + steps++; + } + const end = cur; + expect(d.historyState().undo).toBe(steps); + expect(JSON.parse(d.json())).toEqual(plain(end)); + for (;;) { + const prev = d.undo(cur); + if (!prev) break; + cur = prev; + } + expect(cur).toEqual(sampleProject); + // Exakt, auch die Feld-Reihenfolge, und Kern == Leseansicht. + expect(JSON.stringify(cur)).toBe(JSON.stringify(sampleProject)); + expect(JSON.parse(d.json())).toEqual(plain(sampleProject)); + for (;;) { + const next = d.redo(cur); + if (!next) break; + cur = next; + } + expect(JSON.stringify(cur)).toBe(JSON.stringify(end)); + expect(JSON.parse(d.json())).toEqual(plain(end)); + d.close(); + }); + + it("coalesceKey: Serie im Zeitfenster = ein Schritt, unveränderte Elemente bleiben identisch", () => { + const d = new ProjectDocument(sampleProject); + let cur: Project = sampleProject; + for (let i = 0; i < 50; i++) { + const w = cur.walls[0]; + const next = { ...cur, walls: [{ ...w, height: 3 + i / 100 }, ...cur.walls.slice(1)] }; + const r = d.commit(cur, diffToOps(cur, next), "drag:W", 1000 + i * 10); + if ("project" in r) cur = r.project; + } + expect(d.historyState().undo).toBe(1); + const back = d.undo(cur)!; + expect(back).toEqual(sampleProject); + expect(back.walls[1]).toBe(cur.walls[1]); + // Nach Undo beginnt dieselbe Serie einen neuen Schritt. + const again = d.redo(back)!; + const r = d.commit(again, diffToOps(again, { ...again, name: "x" }), "drag:W", 1500); + expect("project" in r).toBe(true); + expect(d.historyState().undo).toBe(2); + d.close(); + }); + + it("Gruppe: mehrere Änderungen = ein Schritt", () => { + const d = new ProjectDocument(sampleProject); + let cur: Project = sampleProject; + d.beginGroup(); + for (const name of ["a", "b", "c"]) { + const r = d.commit(cur, diffToOps(cur, { ...cur, name }), undefined, 0); + if ("project" in r) cur = r.project; + } + d.endGroup(); + expect(d.historyState().undo).toBe(1); + expect(d.undo(cur)!.name).toBe(sampleProject.name); + d.close(); + }); + + it("NaN und doppelte ids: abgelehnt mit den Meldungen der TS-Fassung, kein Schritt", () => { + const d = new ProjectDocument(sampleProject); + const w = sampleProject.walls[0]; + const nan = { ...sampleProject, walls: [{ ...w, height: NaN }, ...sampleProject.walls.slice(1)] }; + const r1 = d.commit(sampleProject, diffToOps(sampleProject, nan), undefined, 0); + expect(r1).toEqual({ problems: [`„walls" ${w.id}: NaN ist nicht endlich.`] }); + const dup = { ...sampleProject, walls: [...sampleProject.walls, { ...w }] }; + const r2 = d.commit(sampleProject, diffToOps(sampleProject, dup), undefined, 0); + expect(r2).toEqual({ problems: [`Doppelte ids in „walls".`] }); + const inf = { ...sampleProject, referenceElevationMasl: -Infinity } as Project; + const r3 = d.commit(sampleProject, diffToOps(sampleProject, inf), undefined, 0); + expect(r3).toEqual({ problems: [`Feld „referenceElevationMasl": -Infinity ist nicht endlich.`] }); + expect(d.historyState().undo).toBe(0); + expect(JSON.parse(d.json())).toEqual(plain(sampleProject)); + d.close(); + }); + + it("Fassaden validateOps/validateProject (Kern) melden wie bisher", () => { + const w = sampleProject.walls[0]; + const ops: CoreOp[] = [ + { kind: "add", collection: "walls", items: [{ ...w, start: { x: Infinity, y: 0 } }] as never }, + { kind: "setField", key: "scale", value: NaN }, + ]; + const after = { ...sampleProject, walls: [...sampleProject.walls, ops[0].kind === "add" ? (ops[0].items[0] as unknown as Wall) : w] }; + expect(validateOps(after, ops, sampleProject)).toEqual([ + `„walls" ${w.id}: Infinity ist nicht endlich.`, + `Doppelte ids in „walls".`, + `Feld „scale": NaN ist nicht endlich.`, + ]); + // Alt-Doppelungen bleiben änderbar. + expect(validateOps(after, [{ kind: "add", collection: "walls", items: [{ id: "neu" }] }], after)).toEqual([]); + expect(validateProject(sampleProject)).toEqual([]); + }); + + it("Messung: grosses Projekt, viele Undo-Schritte", () => { + const base = sampleProject.walls; + const walls: Wall[] = Array.from({ length: 3000 }, (_, i) => ({ + ...base[i % base.length], + id: `w${i}`, + start: { x: i, y: 0 }, + end: { x: i + 1, y: 0 }, + })); + const big: Project = { ...sampleProject, walls }; + const d = new ProjectDocument(big); + d.setHistoryLimits(1000, 1 << 30); + let cur = big; + const n = 500; + let t = performance.now(); + for (let i = 0; i < n; i++) { + const k = (i * 7) % walls.length; + const next = { ...cur, walls: cur.walls.map((w, j) => (j === k ? { ...w, height: 2 + i / 1000 } : w)) }; + const r = d.commit(cur, diffToOps(cur, next), undefined, i * 1000); + if ("project" in r) cur = r.project; + } + const commitMs = (performance.now() - t) / n; + const end = cur; + t = performance.now(); + for (let p = d.undo(cur); p; p = d.undo(cur)) cur = p; + const undoMs = (performance.now() - t) / n; + t = performance.now(); + for (let p = d.redo(cur); p; p = d.redo(cur)) cur = p; + const redoMs = (performance.now() - t) / n; + const kib = Math.round(d.historyState().bytes / 1024); + process.stderr.write( + `3000 Wände, ${n} Schritte: setProject-Weg ${commitMs.toFixed(2)} ms/Schritt (diff+commit+apply), Undo ${undoMs.toFixed(2)} ms, Redo ${redoMs.toFixed(2)} ms, Verlauf ≈ ${kib} KiB\n`, + ); + expect(cur.walls.map((w) => w.height)).toEqual(end.walls.map((w) => w.height)); + // Grosszügige Grenze (Container unter Last); typische Werte s. TODO [K4]. + expect(commitMs + undoMs + redoMs).toBeLessThan(50); + d.close(); + }); +}); diff --git a/src/core/document.ts b/src/core/document.ts index 351a501b..45c066e7 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -1,12 +1,14 @@ -// Projekt-Dokument im Rust-Kern ([K4], Stufe S1): spiegelt das TS-Projekt über Ops nach Rust -// (`document.rs`). TS bleibt vorerst Quelle der Änderungen (`setProject` → `diffToOps`); Rust hält +// Projekt-Dokument im Rust-Kern ([K4], Stufe S1; S3: Prüfung und Undo/Redo im Kern, s. `commit`). +// Spiegelt das TS-Projekt über Ops nach Rust (`document.rs`). Befehle liefern vorerst noch +// Projekt → Projekt (`setProject` → `diffToOps`); Rust hält // den Stand, auf dem die Ableitungen später direkt rechnen, ohne dass TS das Projekt je Aufruf // flach neu sammeln muss. Bei jedem Widerspruch (abgelehnte Ops, Fehler) wird das Dokument aus dem // vollen Projekt neu geöffnet — der Spiegel heilt sich selbst. import type { Project } from "../model/types"; import { core } from "../engine/coreWasm"; -import { diffToOps } from "./ops"; +import { applyOps, diffToOps, opsToJson } from "./ops"; +import type { CoreOp } from "./ops"; /** Abfragen des Kerns (`queries.rs`). */ export type QueryName = @@ -33,6 +35,8 @@ export type QueryName = export class ProjectDocument { private handle = 0; private mirror: Project; + /** Verlaufsgrenzen (Schritte, Bytes), beim Neuöffnen wieder gesetzt. */ + private limits: [number, number] | null = null; constructor(project: Project) { this.mirror = project; @@ -48,6 +52,7 @@ export class ProjectDocument { if (this.handle) core().doc_close(this.handle); this.handle = core().doc_open(JSON.stringify(project)); if (!this.handle) console.warn("Projekt-Dokument im Kern konnte nicht geöffnet werden."); + else if (this.limits) core().doc_history_limits(this.handle, this.limits[0], this.limits[1]); } /** Bringt das Dokument auf den Stand `next` (über die Differenz als Ops). */ @@ -103,9 +108,107 @@ export class ProjectDocument { if (this.handle) core().doc_close(this.handle); this.handle = 0; } + + // ── Änderungen mit Verlauf ([K4] S3, [7], [8]) ────────────────────────────── + // Der Kern prüft, wendet an und zeichnet Undo-Schritte als inverse Ops auf; das TS-Projekt ist + // die Leseansicht und wird mit genau den Ops nachgeführt, die der Kern angenommen bzw. für + // Undo/Redo geliefert hat (`applyOps`, unveränderte Elemente behalten ihre Identität). + + /** Stand des Spiegels (die zuletzt übernommene Leseansicht). */ + get current(): Project { + return this.mirror; + } + + /** + * Stellt sicher, dass das Dokument `base` spiegelt. Wurde das Projekt vorbei an den Ops + * geändert (Laden in Tests, fremder Stand), passt der Verlauf nicht mehr: er wird geleert. + */ + private ensure(base: Project): void { + if (base === this.mirror && this.handle) return; + this.sync(base); + if (!this.handle) this.reopen(base); + if (this.handle) core().doc_history_clear(this.handle); + } + + /** + * Benutzer-Änderung: `ops` (auf `base`) im Kern prüfen, anwenden und als Undo-Schritt + * aufzeichnen (`coalesceKey` + `now` in ms: Serien im Zeitfenster = ein Schritt). + * Ergebnis: neues Projekt oder die Meldungen des Kerns (dann bleibt alles unverändert). + */ + commit(base: Project, ops: readonly CoreOp[], coalesceKey: string | undefined, now: number): { project: Project } | { problems: string[] } { + this.ensure(base); + if (!this.handle) return { problems: ["Projekt-Dokument im Kern nicht offen."] }; + const res = core().doc_commit(this.handle, opsToJson(ops), coalesceKey ?? "", now); + if (res) { + let problems: string[]; + try { + problems = JSON.parse(res) as string[]; + } catch { + problems = [res]; + } + return { problems }; + } + const project = applyOps(base, ops); + this.mirror = project; + return { project }; + } + + /** Einen Schritt zurück auf `base` (= aktuelles Projekt); `null` = nichts rückgängig zu machen. */ + undo(base: Project): Project | null { + return this.jump(base, "doc_undo"); + } + + /** Einen Schritt vor; `null` = nichts wiederherzustellen. */ + redo(base: Project): Project | null { + return this.jump(base, "doc_redo"); + } + + private jump(base: Project, fn: "doc_undo" | "doc_redo"): Project | null { + if (base !== this.mirror || !this.handle) { + this.ensure(base); + return null; + } + const json = core()[fn](this.handle); + if (!json) return null; + const project = applyOps(base, JSON.parse(json) as CoreOp[]); + this.mirror = project; + return project; + } + + /** Verlaufsstand: Undo-/Redo-Tiefe und geschätzter Speicher (Bytes). */ + historyState(): { undo: number; redo: number; bytes: number } { + const s = this.handle ? core().doc_history_state(this.handle) : new Float64Array(0); + return { undo: s[0] ?? 0, redo: s[1] ?? 0, bytes: s[2] ?? 0 }; + } + + clearHistory(): void { + if (this.handle) core().doc_history_clear(this.handle); + } + + /** Grenzen des Verlaufs (Schritte, ungefähre Bytes). */ + setHistoryLimits(steps: number, bytes: number): void { + this.limits = [steps, bytes]; + if (this.handle) core().doc_history_limits(this.handle, steps, bytes); + } + + /** Gruppe: alle Änderungen bis {@link endGroup} werden ein Undo-Schritt (verschachtelbar). */ + beginGroup(): void { + if (this.handle) core().doc_group_begin(this.handle); + } + + endGroup(): void { + if (this.handle) core().doc_group_end(this.handle); + } } let shared: ProjectDocument | null = null; +/** Dokument des Stores (mit Verlauf); Abfragen auf dessen aktuellem Projekt laufen direkt darüber. */ +let primary: ProjectDocument | null = null; + +/** Meldet das Dokument des Stores an (s. {@link documentFor}). */ +export function setPrimaryDocument(doc: ProjectDocument | null): void { + primary = doc; +} /** * Das gemeinsame Kern-Dokument, auf den Stand von `project` gebracht. Der Abgleich läuft über die @@ -113,6 +216,7 @@ let shared: ProjectDocument | null = null; * wechselt ein Aufrufer zwischen sehr verschiedenen Projekten, ist es nur langsamer, nie falsch. */ export function documentFor(project: Project): ProjectDocument { + if (primary && primary.current === project && primary.id) return primary; if (!shared) shared = new ProjectDocument(project); else shared.sync(project); return shared; diff --git a/src/core/ops.ts b/src/core/ops.ts index 03e761da..ac00b046 100644 --- a/src/core/ops.ts +++ b/src/core/ops.ts @@ -7,6 +7,12 @@ // an — das Projekt ändert sich ausschliesslich durch Ops. Ops sind JSON-serialisierbar // (Undo-Verlauf [84], Makros [85], MCP [9], später ein Rust-Kern). // +// [K4] S3: Prüfung (`validateOps`/`validateProject`), Anwendung mit Verlauf und Undo/Redo liegen im +// Rust-Kern (`src-tauri/core/src/ops.rs`, `document.rs`). Hier bleiben `diffToOps` (Adapter für die +// Befehle, die noch Projekt → Projekt liefern) und `applyOps` als Nachführung der TS-Leseansicht: +// TS wendet genau die Ops an, die der Kern angenommen oder für Undo/Redo geliefert hat — +// unveränderte Elemente behalten so ihre Objekt-Identität (Caches in Plan/3D). +// // 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 @@ -14,6 +20,7 @@ // • Alles andere (Skalare, Objekte, Listen ohne ids): `setField` mit dem ganzen Wert. import type { Project } from "../model/types"; +import { core } from "../engine/coreWasm"; type Entity = { id: string } & Record; @@ -26,8 +33,9 @@ export type CoreOp = | { 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 }; + /** Setzt ein Projekt-Feld auf `value` (`undefined`/fehlend ⇒ Feld entfernen). `at`: Position, falls + * das Feld neu eingefügt wird (vom Kern-Undo gesetzt, damit die Feld-Reihenfolge exakt zurückkommt). */ + | { kind: "setField"; key: string; value?: unknown; at?: number }; 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"); @@ -113,6 +121,12 @@ function listOf(cur: Record, collection: string): Entity[] { function applyOne(cur: Record, op: CoreOp): Record { switch (op.kind) { case "setField": { + if (op.value !== undefined && op.at !== undefined && !(op.key in cur)) { + // Neues Feld an Position `at` (wie `shift_insert` im Kern). + const entries = Object.entries(cur); + entries.splice(Math.max(0, Math.min(entries.length, op.at)), 0, [op.key, op.value]); + return Object.fromEntries(entries); + } const next = { ...cur }; if (op.value === undefined) delete next[op.key]; else next[op.key] = op.value; @@ -145,7 +159,28 @@ function applyOne(cur: Record, op: CoreOp): Record, op: CoreOp): 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; + return problemsOf(core().project_validate(JSON.stringify(p, markNonFinite))); } /** - * 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. + * Prüft angewendete Ops (nur was sie anfassen, billig genug für jeden Drag-Schritt): nicht + * endliche Zahlen in neuen/ersetzten Elementen und `setField`-Zahlen, NEUE doppelte ids in den + * betroffenen Listen. Im Store läuft die Prüfung direkt im Kern-Dokument (`ProjectDocument.commit`). */ 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 keys = new Set(ops.map((op) => (op.kind === "setField" ? op.key : op.collection))); + const pick = (p: Project | undefined): string => { + if (!p) return ""; + const rec = p as unknown as Record; + const out: Record = {}; + for (const k of keys) if (k in rec) out[k] = rec[k]; + return JSON.stringify(out); }; - 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; + return problemsOf(core().ops_validate(opsToJson(ops), pick(after), pick(before))); } diff --git a/src/state/history.test.ts b/src/state/history.test.ts index e05c59cd..683d82f3 100644 --- a/src/state/history.test.ts +++ b/src/state/history.test.ts @@ -23,11 +23,12 @@ import { HISTORY_LIMIT } from "./historySlice"; beforeEach(() => { setState({ project: sampleProject, - undoStack: [], - redoStack: [], + undoDepth: 0, + redoDepth: 0, canUndo: false, canRedo: false, }); + getState().clearHistory(); }); describe("Undo/Redo", () => { @@ -59,7 +60,7 @@ describe("Undo/Redo", () => { }); it("undo bei leerem Stack ist ein No-Op (kein Crash)", () => { - expect(getState().undoStack.length).toBe(0); + expect(getState().undoDepth).toBe(0); const before = getState().project; expect(() => getState().undo()).not.toThrow(); @@ -69,7 +70,7 @@ describe("Undo/Redo", () => { }); it("redo bei leerem Stack ist ein No-Op (kein Crash)", () => { - expect(getState().redoStack.length).toBe(0); + expect(getState().redoDepth).toBe(0); const before = getState().project; expect(() => getState().redo()).not.toThrow(); @@ -81,27 +82,27 @@ describe("Undo/Redo", () => { it("eine neue Aktion nach undo() verwirft den Redo-Stack", () => { getState().toggleLevelVisible("eg"); getState().undo(); - expect(getState().redoStack.length).toBe(1); + expect(getState().redoDepth).toBe(1); getState().toggleLevelVisible("og"); - expect(getState().redoStack.length).toBe(0); + expect(getState().redoDepth).toBe(0); expect(getState().canRedo).toBe(false); // Die neue Aktion selbst bleibt natürlich undo-fähig. expect(getState().canUndo).toBe(true); }); it("die allererste Änderung bleibt exakt EIN Undo-Schritt (kein Start-Eintrag)", () => { - expect(getState().undoStack.length).toBe(0); + expect(getState().undoDepth).toBe(0); getState().toggleLevelVisible("eg"); - expect(getState().undoStack.length).toBe(1); + expect(getState().undoDepth).toBe(1); }); it("history-Stack verwirft die ältesten Einträge über HISTORY_LIMIT hinaus", () => { for (let i = 0; i < HISTORY_LIMIT + 10; i++) { getState().toggleLevelVisible("eg"); } - expect(getState().undoStack.length).toBe(HISTORY_LIMIT); + expect(getState().undoDepth).toBe(HISTORY_LIMIT); }); it("ein Grip-Drag (viele setProject-Aufrufe in Serie) koalesziert zu EINEM Undo-Schritt", () => { @@ -118,19 +119,19 @@ describe("Undo/Redo", () => { const w1After = getState().project.walls.find((w) => w.id === "W1"); expect(w1After?.start).toEqual({ x: 2, y: 0 }); // Trotz 20 Aufrufen: genau EIN Undo-Schritt. - expect(getState().undoStack.length).toBe(1); + expect(getState().undoDepth).toBe(1); getState().undo(); const w1Restored = getState().project.walls.find((w) => w.id === "W1"); expect(w1Restored?.start).toEqual({ x: 0, y: 0 }); - expect(getState().undoStack.length).toBe(0); + expect(getState().undoDepth).toBe(0); }); it("zwei Drags auf UNTERSCHIEDLICHE Griffe erzeugen ZWEI Undo-Schritte", () => { getState().moveGripOf(null, "W1", 0, { x: 1, y: 0 }); getState().moveGripOf(null, "W1", 1, { x: 6, y: 0 }); - expect(getState().undoStack.length).toBe(2); + expect(getState().undoDepth).toBe(2); }); }); diff --git a/src/state/historySlice.ts b/src/state/historySlice.ts index 7cc44b76..00117599 100644 --- a/src/state/historySlice.ts +++ b/src/state/historySlice.ts @@ -1,107 +1,95 @@ -// History-Slice: Undo/Redo für das Projekt-Modell. Reine Snapshot-Historie — -// dank immutabler Updates in `projectSlice.ts` (jede echte Änderung liefert -// eine NEUE `Project`-Referenz mit structural sharing) ist ein Stack aus -// `Project`-Werten billig (kein Deep-Clone nötig, unveränderte Teilbäume -// werden zwischen den Snapshots geteilt). +// History-Slice: Undo/Redo für das Projekt-Modell ([8], [K4] S3). Der Verlauf liegt im Rust-Kern +// (`src-tauri/core/src/ops.rs`, `document.rs`): je Schritt die Vorwärts- und die inversen Ops — +// keine Projekt-Schnappschüsse mehr. Gleicher `coalesceKey` im Zeitfenster = ein Schritt (Drag, +// Regler), Gruppen (`groupChanges`) fassen mehrere Änderungen zusammen; begrenzt auf +// {@link HISTORY_LIMIT} Schritte und {@link HISTORY_MAX_BYTES}. // -// Die eigentliche Buchführung (WANN wird gepusht, Koaleszenz von Drag-Serien) -// lebt bewusst in `projectSlice.ts` bei `setProject` selbst — das ist die -// EINZIGE Stelle, durch die jede Projekt-Mutation läuft. Dieses Modul liefert -// nur den reaktiven Zustand (Stacks + Flags) und die `undo`/`redo`-Aktionen, -// die DIREKT über `set()` schreiben (NICHT über `setProject`), damit sie -// keinen neuen History-Eintrag erzeugen (sonst Endlosschleife/kaputte -// Historie). Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). +// `setProject` (projectSlice.ts) ist die EINZIGE Stelle, durch die jede Projekt-Mutation läuft: es +// übergibt die Ops dem Kern-Dokument des Stores ({@link storeDocument}). `undo`/`redo` holen die +// Ops vom Kern und führen die TS-Leseansicht damit nach (direkt über `set()`, kein neuer Schritt). +// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import type { Project } from "../model/types"; +import { ProjectDocument, setPrimaryDocument } from "../core/document"; import type { StoreApi } from "./store"; -/** Obergrenze der Undo-Tiefe — ältere Einträge fallen hinten raus (Speicher/Performance). */ +/** Obergrenze der Undo-Tiefe — ältere Schritte fallen hinten raus. */ export const HISTORY_LIMIT = 100; +/** Ungefähre Speichergrenze des Verlaufs (Bytes) — ältere Schritte fallen hinten raus. */ +export const HISTORY_MAX_BYTES = 256 * 1024 * 1024; /** Felder, die diese Slice in den RootState beisteuert. */ export interface HistorySlice { - /** Ältere Projekt-Stände (oben = zuletzt verlassener Stand, für `undo`). */ - undoStack: Project[]; - /** Durch `undo` verlassene Stände (oben = zuletzt verlassener, für `redo`). */ - redoStack: Project[]; - /** Abgeleitet aus `undoStack.length > 0` — bequem für UI-Bindings (Buttons/Menüs). */ + /** Anzahl Undo-Schritte im Kern. */ + undoDepth: number; + /** Anzahl Redo-Schritte im Kern. */ + redoDepth: number; + /** Abgeleitet aus `undoDepth > 0` — bequem für UI-Bindings (Buttons/Menüs). */ canUndo: boolean; - /** Abgeleitet aus `redoStack.length > 0`. */ + /** Abgeleitet aus `redoDepth > 0`. */ canRedo: boolean; - /** Einen Schritt zurück. No-Op (kein Crash), wenn der Undo-Stack leer ist. */ + /** Einen Schritt zurück. No-Op (kein Crash), wenn nichts rückgängig zu machen ist. */ undo: () => void; - /** Einen Schritt vor. No-Op (kein Crash), wenn der Redo-Stack leer ist. */ + /** Einen Schritt vor. No-Op (kein Crash), wenn nichts wiederherzustellen ist. */ redo: () => void; + /** Verlauf leeren. */ + clearHistory: () => void; + /** Alle Projekt-Änderungen in `fn` werden EIN Undo-Schritt. */ + groupChanges: (fn: () => void) => void; } -/** - * Reines Patch-Berechnen für einen History-Push — von `setProject` (in - * `projectSlice.ts`) bei jeder ECHTEN Projekt-Änderung aufgerufen (kein - * Store-Zugriff nötig, daher hier als freie Funktion statt Store-Aktion: so - * lässt sich der Push in EINEM gemeinsamen `set()`-Aufruf mit der eigentlichen - * `project`-Änderung zusammenfassen, statt einen zweiten, verschachtelten - * `set()`-Aufruf auszulösen). - * - * Eine neue Aktion verwirft immer die Redo-Historie (Standardverhalten jedes - * Undo/Redo-Systems: sobald der Nutzer nach einem `undo()` etwas Neues tut, - * ist der alte "vordere" Zweig weg). - */ -export function pushHistoryPatch( - undoStack: Project[], - prevProject: Project, -): Pick { - const next = [...undoStack, prevProject]; - if (next.length > HISTORY_LIMIT) next.shift(); - return { undoStack: next, redoStack: [], canUndo: true, canRedo: false }; -} +let doc: ProjectDocument | null = null; /** - * Baut `undo`/`redo` + initialen Zustand. `onAfterJump` wird nach jedem - * Sprung aufgerufen (projectSlice.ts nutzt das, um die Koaleszenz-Buchführung - * für Drag-Serien zurückzusetzen — sonst könnte eine neue Aktion direkt nach - * einem `undo()` fälschlich mit der VORHERIGEN Serie verschmolzen und dadurch - * NIE auf dem Undo-Stack landen). + * Das Kern-Dokument des Stores (mit Verlauf), beim ersten Gebrauch aus `project` geöffnet. Es ist + * zugleich das Dokument, über das die Abfragen auf dem aktuellen Projekt laufen (`documentFor`). */ -export function createHistorySlice( - api: StoreApi, - onAfterJump?: () => void, -): HistorySlice { +export function storeDocument(project: Project): ProjectDocument { + if (!doc) { + doc = new ProjectDocument(project); + doc.setHistoryLimits(HISTORY_LIMIT, HISTORY_MAX_BYTES); + setPrimaryDocument(doc); + } + return doc; +} + +/** Verlaufs-Felder für den Store aus dem Stand im Kern. */ +export function historyPatch(d: ProjectDocument): Pick { + const h = d.historyState(); + return { undoDepth: h.undo, redoDepth: h.redo, canUndo: h.undo > 0, canRedo: h.redo > 0 }; +} + +/** Baut `undo`/`redo` + initialen Zustand. */ +export function createHistorySlice(api: StoreApi): HistorySlice { const { set, get } = api; + const jump = (dir: "undo" | "redo") => { + const { project } = get(); + const d = storeDocument(project); + const next = dir === "undo" ? d.undo(project) : d.redo(project); + set(next ? { project: next, ...historyPatch(d) } : historyPatch(d)); + }; + return { - undoStack: [], - redoStack: [], + undoDepth: 0, + redoDepth: 0, canUndo: false, canRedo: false, - - undo: () => { - const { undoStack, redoStack, project } = get(); - if (undoStack.length === 0) return; - const prev = undoStack[undoStack.length - 1]; - const rest = undoStack.slice(0, -1); - set({ - project: prev, - undoStack: rest, - redoStack: [...redoStack, project], - canUndo: rest.length > 0, - canRedo: true, - }); - onAfterJump?.(); + undo: () => jump("undo"), + redo: () => jump("redo"), + clearHistory: () => { + const d = storeDocument(get().project); + d.clearHistory(); + set(historyPatch(d)); }, - - redo: () => { - const { undoStack, redoStack, project } = get(); - if (redoStack.length === 0) return; - const next = redoStack[redoStack.length - 1]; - const rest = redoStack.slice(0, -1); - set({ - project: next, - undoStack: [...undoStack, project], - redoStack: rest, - canUndo: true, - canRedo: rest.length > 0, - }); - onAfterJump?.(); + groupChanges: (fn) => { + const d = storeDocument(get().project); + d.beginGroup(); + try { + fn(); + } finally { + d.endGroup(); + } }, }; } diff --git a/src/state/projectSlice.customPalettes.test.ts b/src/state/projectSlice.customPalettes.test.ts index 5c639836..e63d3b97 100644 --- a/src/state/projectSlice.customPalettes.test.ts +++ b/src/state/projectSlice.customPalettes.test.ts @@ -16,8 +16,8 @@ beforeEach(() => { vi.spyOn(Date, "now").mockImplementation(() => clock++); setState({ project: { ...sampleProject, components: sampleProject.components.slice(0, 1), customPalettes: [] }, - undoStack: [], - redoStack: [], + undoDepth: 0, + redoDepth: 0, canUndo: false, canRedo: false, }); diff --git a/src/state/projectSlice.drawingGrips.test.ts b/src/state/projectSlice.drawingGrips.test.ts index d3ad0e19..e0a2c192 100644 --- a/src/state/projectSlice.drawingGrips.test.ts +++ b/src/state/projectSlice.drawingGrips.test.ts @@ -32,8 +32,8 @@ beforeEach(() => { ...sampleProject, drawings2d: [circleDrawing, arcDrawing], }, - undoStack: [], - redoStack: [], + undoDepth: 0, + redoDepth: 0, canUndo: false, canRedo: false, }); diff --git a/src/state/projectSlice.leaderBendGrips.test.ts b/src/state/projectSlice.leaderBendGrips.test.ts index 25ef4f69..a29f3319 100644 --- a/src/state/projectSlice.leaderBendGrips.test.ts +++ b/src/state/projectSlice.leaderBendGrips.test.ts @@ -38,8 +38,8 @@ const leaderTwoBends: Drawing2D = { beforeEach(() => { setState({ project: { ...sampleProject, drawings2d: [leaderNoBends, leaderTwoBends] }, - undoStack: [], - redoStack: [], + undoDepth: 0, + redoDepth: 0, canUndo: false, canRedo: false, }); diff --git a/src/state/projectSlice.moveEdge.test.ts b/src/state/projectSlice.moveEdge.test.ts index 96da9750..48462e16 100644 --- a/src/state/projectSlice.moveEdge.test.ts +++ b/src/state/projectSlice.moveEdge.test.ts @@ -57,8 +57,8 @@ function makeRoom(over: Partial = {}): Room { beforeEach(() => { setState({ project: { ...sampleProject, drawings2d: [pentagon], rooms: [makeRoom()] }, - undoStack: [], - redoStack: [], + undoDepth: 0, + redoDepth: 0, canUndo: false, canRedo: false, }); diff --git a/src/state/projectSlice.objectLock.test.ts b/src/state/projectSlice.objectLock.test.ts index ad79ed58..06426687 100644 --- a/src/state/projectSlice.objectLock.test.ts +++ b/src/state/projectSlice.objectLock.test.ts @@ -36,8 +36,8 @@ const lockedDrawing: Drawing2D = { beforeEach(() => { setState({ project: { ...sampleProject, walls: [lockedWall], drawings2d: [lockedDrawing] }, - undoStack: [], - redoStack: [], + undoDepth: 0, + redoDepth: 0, canUndo: false, canRedo: false, }); diff --git a/src/state/projectSlice.penSets.test.ts b/src/state/projectSlice.penSets.test.ts index 44d16d81..da0b9af0 100644 --- a/src/state/projectSlice.penSets.test.ts +++ b/src/state/projectSlice.penSets.test.ts @@ -21,8 +21,8 @@ beforeEach(() => { vi.spyOn(Date, "now").mockImplementation(() => clock++); setState({ project: { ...sampleProject, components: sampleProject.components.slice(0, 1), pens: [], penSets: [], activePenSetId: undefined }, - undoStack: [], - redoStack: [], + undoDepth: 0, + redoDepth: 0, canUndo: false, canRedo: false, }); diff --git a/src/state/projectSlice.polylineBulge.test.ts b/src/state/projectSlice.polylineBulge.test.ts index 6c66f658..3c9472e7 100644 --- a/src/state/projectSlice.polylineBulge.test.ts +++ b/src/state/projectSlice.polylineBulge.test.ts @@ -21,8 +21,8 @@ const openPoly: Drawing2D = { beforeEach(() => { setState({ project: { ...sampleProject, drawings2d: [openPoly] }, - undoStack: [], - redoStack: [], + undoDepth: 0, + redoDepth: 0, canUndo: false, canRedo: false, }); diff --git a/src/state/projectSlice.polylinePoints.test.ts b/src/state/projectSlice.polylinePoints.test.ts index da3918a1..ba3d16f5 100644 --- a/src/state/projectSlice.polylinePoints.test.ts +++ b/src/state/projectSlice.polylinePoints.test.ts @@ -24,8 +24,8 @@ function setPolyline(geom: Extract) { }; setState({ project: { ...sampleProject, drawings2d: [d] }, - undoStack: [], - redoStack: [], + undoDepth: 0, + redoDepth: 0, canUndo: false, canRedo: false, }); diff --git a/src/state/projectSlice.textFrameGrips.test.ts b/src/state/projectSlice.textFrameGrips.test.ts index d17f736b..4fb77231 100644 --- a/src/state/projectSlice.textFrameGrips.test.ts +++ b/src/state/projectSlice.textFrameGrips.test.ts @@ -60,8 +60,8 @@ beforeEach(() => { ...sampleProject, drawings2d: [plainText, textBox, rotatedTextBox], }, - undoStack: [], - redoStack: [], + undoDepth: 0, + redoDepth: 0, canUndo: false, canRedo: false, }); diff --git a/src/state/projectSlice.textStyles.test.ts b/src/state/projectSlice.textStyles.test.ts index 9770a478..b126522f 100644 --- a/src/state/projectSlice.textStyles.test.ts +++ b/src/state/projectSlice.textStyles.test.ts @@ -16,8 +16,8 @@ import { DEFAULT_PRESETS } from "../text/richText"; beforeEach(() => { setState({ project: { ...sampleProject, textStyles: undefined }, - undoStack: [], - redoStack: [], + undoDepth: 0, + redoDepth: 0, canUndo: false, canRedo: false, }); diff --git a/src/state/projectSlice.ts b/src/state/projectSlice.ts index d71d4717..6e5e940d 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 { applyOps, diffToOps, validateOps } from "../core/ops"; +import { diffToOps } from "../core/ops"; import type { CoreOp } from "../core/ops"; import { withVertexType, type PolylineVertexType } from "../core"; import { sampleProject } from "../model/sampleProject"; @@ -54,7 +54,7 @@ import { textFrameCorners } from "../text/textFrame"; import { DEFAULT_PRESETS, type TextStylePreset } from "../text/richText"; import { t } from "../i18n"; import type { StoreApi } from "./store"; -import { createHistorySlice, pushHistoryPatch } from "./historySlice"; +import { createHistorySlice, historyPatch, storeDocument } from "./historySlice"; import type { HistorySlice } from "./historySlice"; import type { NotifyKind } from "./notifySlice"; @@ -422,7 +422,7 @@ export interface ProjectSlice { * `get()`/`set` typsicher auf `activeLevelId` zugreifen können. Die * History-Felder gehören ebenfalls dazu: `setProject` (unten) ist der EINZIGE * Durchlaufpunkt jeder Projekt-Mutation und pusht dort bei jeder ECHTEN - * Änderung auf `undoStack`. + * Änderung einen Undo-Schritt im Kern-Dokument auf. */ type ProjectSliceDeps = { activeLevelId: string; @@ -436,32 +436,16 @@ export function createProjectSlice( ): ProjectSlice & HistorySlice { const { set, get } = api; - // Koaleszenz-Buchführung für Drag-Serien (Griff ziehen, Element verschieben, - // Kante ziehen, …): diese Aktionen rufen `setProject` bei JEDEM - // Maus-Move-Schritt auf (kein separates Draft/Preview + Commit-Muster wie - // bei den Zeichenwerkzeugen — dort läuft die Vorschau über lokalen - // `draft`-State in App.tsx, und `setProject` wird erst einmal beim Commit - // aufgerufen, siehe `applyToolResult`/`onToolCommit` in App.tsx). Ohne - // Koaleszenz würde EIN Drag zig Undo-Schritte erzeugen. Ephemer (wie ein - // Ref) — kein reaktiver State nötig, wird bei jedem `setProject`-Aufruf neu - // bewertet und bei `undo`/`redo` zurückgesetzt (siehe `onAfterJump` unten). - let lastCoalesceKey: string | undefined; - let lastCoalesceAt = 0; - const COALESCE_WINDOW_MS = 400; + // Koaleszenz von Drag-Serien (Griff ziehen, Element verschieben, Kante ziehen, …): diese + // Aktionen rufen `setProject` bei JEDEM Maus-Move-Schritt mit einem `coalesceKey` auf (kein + // Draft/Commit-Muster wie bei den Zeichenwerkzeugen, deren Vorschau über lokalen `draft`-State + // in App.tsx läuft). Gleicher Schlüssel innerhalb des Zeitfensters = EIN Undo-Schritt; die + // Buchführung (Schlüssel, Zeitfenster, Rücksetzen nach Undo/Redo) liegt im Kern (`ops.rs`). // 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, - () => { - // Nach einem Sprung (undo/redo) muss die NÄCHSTE Aktion garantiert - // pushen, auch wenn sie zufällig denselben coalesceKey trägt wie die - // Serie vor dem Sprung — sonst würde sie mit der alten Serie - // verschmolzen und verschwände spurlos (kein Undo-Eintrag). - lastCoalesceKey = undefined; - }, - ); + const history = createHistorySlice(api as unknown as StoreApi); // Bequemer immutabler Projekt-Updater (wie setProject in App). Zweiter, // optionaler Parameter `coalesceKey`: NUR von den paar bekannten @@ -482,28 +466,21 @@ export function createProjectSlice( // dann ebenfalls nicht, da der Patch leer ist). 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. + // eine Op-Folge übersetzt; der Kern prüft (NaN, doppelte ids), wendet an und zeichnet den + // Undo-Schritt auf. Verstösse werden zurückgerollt und gemeldet. const ops = diffToOps(s.project, wanted); if (ops.length === 0) return {}; - const nextProject = applyOps(s.project, ops); - const problems = validateOps(nextProject, ops, s.project); - if (problems.length > 0) { + const doc = storeDocument(s.project); + const res = doc.commit(s.project, ops, coalesceKey, Date.now()); + if ("problems" in res) { + const problems = res.problems; console.warn("Projektänderung verworfen:", problems); queueMicrotask(() => get().notify(`${t("project.change.rejected")} ${problems[0]}`, "error")); return {}; } opLog.push(ops); if (opLog.length > OP_LOG_LIMIT) opLog.shift(); - const now = Date.now(); - const coalesced = - coalesceKey !== undefined && - coalesceKey === lastCoalesceKey && - now - lastCoalesceAt < COALESCE_WINDOW_MS; - lastCoalesceKey = coalesceKey; - lastCoalesceAt = now; - if (coalesced) return { project: nextProject }; - return { project: nextProject, ...pushHistoryPatch(s.undoStack, s.project) }; + return { project: res.project, ...historyPatch(doc) }; }); return { diff --git a/src/state/reorderDrawingLevels.test.ts b/src/state/reorderDrawingLevels.test.ts index 548c32b4..ed0e0c54 100644 --- a/src/state/reorderDrawingLevels.test.ts +++ b/src/state/reorderDrawingLevels.test.ts @@ -31,8 +31,8 @@ beforeEach(() => { ...sampleProject, drawingLevels: [floor("A"), floor("B"), floor("C"), floor("D")], }, - undoStack: [], - redoStack: [], + undoDepth: 0, + redoDepth: 0, canUndo: false, canRedo: false, }); diff --git a/src/state/reorderDrawings.test.ts b/src/state/reorderDrawings.test.ts index 3fc9ffcf..7cacc299 100644 --- a/src/state/reorderDrawings.test.ts +++ b/src/state/reorderDrawings.test.ts @@ -27,8 +27,8 @@ beforeEach(() => { ...sampleProject, drawings2d: [rect("A"), rect("B"), rect("C"), rect("D")], }, - undoStack: [], - redoStack: [], + undoDepth: 0, + redoDepth: 0, canUndo: false, canRedo: false, }); diff --git a/src/state/roofGrips.test.ts b/src/state/roofGrips.test.ts index 6a1f196f..92f6e2b0 100644 --- a/src/state/roofGrips.test.ts +++ b/src/state/roofGrips.test.ts @@ -40,8 +40,8 @@ const baseProject = { beforeEach(() => { setState({ project: JSON.parse(JSON.stringify(baseProject)), - undoStack: [], - redoStack: [], + undoDepth: 0, + redoDepth: 0, canUndo: false, canRedo: false, }); @@ -62,15 +62,14 @@ describe("moveRoofGrip — Eckpunkt-Resize", () => { }); it("hochfrequente Drags koaleszieren zu EINEM Undo-Schritt", () => { - // Saubere Koaleszenz-Grenze: eine diskrete (keyless) Aktion setzt - // lastCoalesceKey zurück, damit der erste Drag garantiert pusht (der - // Coalesce-Zustand ist ein Modul-Closure und überlebt sonst zwischen Tests). + // Saubere Koaleszenz-Grenze: eine diskrete (keyless) Aktion setzt den + // Koaleszenz-Schlüssel im Kern zurück, danach Verlauf leeren. getState().updateRoof("RF1", { overhang: 0.1 }); - setState({ undoStack: [], canUndo: false }); + getState().clearHistory(); getState().moveRoofGrip("RF1", 2, { x: 5, y: 3 }); getState().moveRoofGrip("RF1", 2, { x: 5.5, y: 3.5 }); getState().moveRoofGrip("RF1", 2, { x: 7, y: 5 }); - expect(getState().undoStack.length).toBe(1); + expect(getState().undoDepth).toBe(1); getState().undo(); // Nach einem Undo wieder der Ausgangsumriss. expect(getState().project.roofs![0].outline).toEqual(baseProject.roofs![0].outline); diff --git a/src/state/setProjectOps.test.ts b/src/state/setProjectOps.test.ts index c99424ed..6d622840 100644 --- a/src/state/setProjectOps.test.ts +++ b/src/state/setProjectOps.test.ts @@ -18,16 +18,18 @@ describe("setProject über CoreOps", () => { expect(ops.length).toBeGreaterThan(0); expect(JSON.parse(JSON.stringify(ops.at(-1)))).toEqual(ops.at(-1)); st().undo(); - expect(st().project).toBe(before); + // Undo kommt als inverse Ops aus dem Kern: inhaltlich gleich, unveränderte Elemente identisch. + expect(st().project).toEqual(before); + expect(st().project.walls[1]).toBe(before.walls[1]); }); it("NaN-Änderung wird verworfen, Projekt bleibt, Undo-Stapel unverändert", () => { const before = st().project; - const depth = st().undoStack.length; + const depth = st().undoDepth; 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); + expect(st().undoDepth).toBe(depth); }); it("doppelte ids beim Einfügen werden verworfen", () => {