[K4][7][8] Store: Undo/Redo und Prüfung über das Kern-Dokument, TS-Snapshots gelöscht

setProject übergibt die Ops (diffToOps) dem Kern-Dokument des Stores
(ProjectDocument.commit); die TS-Leseansicht wird mit genau den angenommenen
bzw. für Undo/Redo gelieferten Ops nachgeführt (applyOps, Objekt-Identität
bleibt). historySlice ohne Snapshots: undoDepth/redoDepth, clearHistory,
groupChanges. validateOps/validateProject sind Fassaden über den Kern.
Das Store-Dokument dient zugleich als Abfrage-Dokument (documentFor).
TODO [K4] S3 mit Entscheid zur Richtung und Messung, [7], [8] nachgeführt.

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-28 19:48:57 +00:00
1 parent 72483026dc
commit d3bd7eb928
21 files changed
+496 -240

No files matched your search

+179
View File
@@ -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();
});
});
+107 -3
View File
@@ -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;
+50 -69
View File
@@ -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<string, unknown>;
@@ -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<string, unknown>, collection: string): Entity[] {
function applyOne(cur: Record<string, unknown>, op: CoreOp): Record<string, unknown> {
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<string, unknown>, op: CoreOp): Record<string, unkn
}
}
// ── Validierung ([7]) ────────────────────────────────────────────────────────
// ── Übergabe an den Kern ─────────────────────────────────────────────────────
/** Nicht endliche Zahlen als Marken-Text (JSON kennt sie nicht; der Kern prüft sie, s. `ops.rs`). */
function markNonFinite(_key: string, v: unknown): unknown {
return typeof v === "number" && !Number.isFinite(v) ? `\u0001${String(v)}` : v;
}
/** Ops als JSON für den Kern (NaN/±Infinity als Marken). */
export function opsToJson(ops: readonly CoreOp[]): string {
return JSON.stringify(ops, markNonFinite);
}
// ── Validierung ([7]) — im Kern (`ops.rs`) ───────────────────────────────────
function problemsOf(json: string): string[] {
try {
const v = JSON.parse(json) as unknown;
return Array.isArray(v) ? (v as string[]) : [];
} catch {
return ["Prüfung im Kern fehlgeschlagen."];
}
}
/**
* Prüft ein Projekt auf Verstösse, die nie gewollt sind: nicht endliche Zahlen in Geometrie
@@ -153,76 +188,22 @@ function applyOne(cur: Record<string, unknown>, op: CoreOp): Record<string, unkn
* konservativ — gesperrt wird nur, was sicher kaputt ist.
*/
export function validateProject(p: Project): string[] {
const problems: string[] = [];
const rec = p as unknown as Record<string, unknown>;
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<string, unknown> | 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<string, unknown>;
const out: Record<string, unknown> = {};
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<string, unknown>;
const dupChecked = new Set<string>();
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<string, unknown>)) {
const r = findNonFinite(x, depth + 1);
if (r) return r;
}
return null;
return problemsOf(core().ops_validate(opsToJson(ops), pick(after), pick(before)));
}