[K4][6][8] S3/S4: Öffnen/Neu laden im Kern, Importe als Ops, diffToOps gelöscht
Öffnen/Vorlage/Wiederherstellen: Store openProjectFile (Kern liest, migriert, lädt direkt ins Dokument, Verlauf leer); Neu/Musterhaus: loadProject (doc_load_json). Autosave sichert den Datei-Text des Kerns, Wiederherstellen lädt ihn wie eine Datei. CLI/MCP laden ins gemeinsame Abfrage-Dokument. DXF/PDF-Import als Ops in einer Gruppe (ein Undo-Schritt), Bilder und IFC-Bauteile als Ops, CLI-Importe über fieldOps/addItems. setProject/CommandResult.commit/ToolResult.commit nehmen nur noch ProjectMutation; diffToOps, isOpsMutation, addNewElementsToActiveGroup, project_parse gelöscht. documentFor folgt fremden Projekten feldweise (fieldOps). Tests: Laden/Speichern zeichengleich zu JSON.stringify, Store-Laden, e2e Öffnen leert Verlauf und DXF-Import = ein Schritt; Zufallsänderungen in Tests über projectDiff.testutil.
This commit is contained in:
37 files changed
+582
-485
No files matched your search
@@ -2,7 +2,8 @@
|
||||
// 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 { validateOps, validateProject } from "./ops";
|
||||
import { projectDiffOps } from "./projectDiff.testutil";
|
||||
import type { CoreOp } from "./ops";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Project, Wall } from "../model/types";
|
||||
@@ -41,7 +42,7 @@ describe("Undo/Redo im Kern-Dokument", () => {
|
||||
let steps = 0;
|
||||
for (let seed = 1; seed <= 1000; seed++) {
|
||||
const next = mutate(cur, seed);
|
||||
const ops = diffToOps(cur, next);
|
||||
const ops = projectDiffOps(cur, next);
|
||||
if (!ops.length) continue;
|
||||
const r = d.commit(cur, ops, undefined, seed * 1000);
|
||||
expect("project" in r, `seed ${seed}`).toBe(true);
|
||||
@@ -76,7 +77,7 @@ describe("Undo/Redo im Kern-Dokument", () => {
|
||||
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);
|
||||
const r = d.commit(cur, projectDiffOps(cur, next), "drag:W", 1000 + i * 10);
|
||||
if ("project" in r) cur = r.project;
|
||||
}
|
||||
expect(d.historyState().undo).toBe(1);
|
||||
@@ -85,7 +86,7 @@ describe("Undo/Redo im Kern-Dokument", () => {
|
||||
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);
|
||||
const r = d.commit(again, projectDiffOps(again, { ...again, name: "x" }), "drag:W", 1500);
|
||||
expect("project" in r).toBe(true);
|
||||
expect(d.historyState().undo).toBe(2);
|
||||
d.close();
|
||||
@@ -96,7 +97,7 @@ describe("Undo/Redo im Kern-Dokument", () => {
|
||||
let cur: Project = sampleProject;
|
||||
d.beginGroup();
|
||||
for (const name of ["a", "b", "c"]) {
|
||||
const r = d.commit(cur, diffToOps(cur, { ...cur, name }), undefined, 0);
|
||||
const r = d.commit(cur, projectDiffOps(cur, { ...cur, name }), undefined, 0);
|
||||
if ("project" in r) cur = r.project;
|
||||
}
|
||||
d.endGroup();
|
||||
@@ -109,13 +110,13 @@ describe("Undo/Redo im Kern-Dokument", () => {
|
||||
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);
|
||||
const r1 = d.commit(sampleProject, projectDiffOps(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);
|
||||
const r2 = d.commit(sampleProject, projectDiffOps(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);
|
||||
const r3 = d.commit(sampleProject, projectDiffOps(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));
|
||||
@@ -156,7 +157,7 @@ describe("Undo/Redo im Kern-Dokument", () => {
|
||||
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);
|
||||
const r = d.commit(cur, projectDiffOps(cur, next), undefined, i * 1000);
|
||||
if ("project" in r) cur = r.project;
|
||||
}
|
||||
const commitMs = (performance.now() - t) / n;
|
||||
|
||||
+61
-14
@@ -1,14 +1,19 @@
|
||||
// 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.
|
||||
// Projekt-Dokument im Rust-Kern ([K4], Stufe S1; S3: Prüfung und Undo/Redo im Kern, s. `commit`;
|
||||
// S4: Laden/Speichern der Projektdatei, s. `loadFile`/`serialize`). Änderungen kommen als Ops
|
||||
// (`commit`), ein anderes Projekt als Ganzes (`load`, `loadFile` — leert den Verlauf). TS hält die
|
||||
// Leseansicht (`current`). Das gemeinsame Abfrage-Dokument (`documentFor`) folgt fremden Projekten
|
||||
// feldweise (`sync`); bei jedem Widerspruch wird es aus dem vollen Projekt neu geöffnet.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import { applyOps, diffToOps, opsToJson } from "./ops";
|
||||
import { applyOps, opsToJson } from "./ops";
|
||||
import type { CoreOp } from "./ops";
|
||||
import { fieldOps } from "./opsBuild";
|
||||
|
||||
/** Ergebnis des Ladens einer Projektdatei ({@link ProjectDocument.loadFile}). */
|
||||
export type LoadFileResult =
|
||||
| { ok: true; project: Project; warnings: string[]; migratedFrom: number | null }
|
||||
| { ok: false; error: string };
|
||||
|
||||
/** Abfragen des Kerns (`queries.rs`). */
|
||||
export type QueryName =
|
||||
@@ -63,10 +68,19 @@ export class ProjectDocument {
|
||||
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). */
|
||||
/**
|
||||
* Bringt das Abfrage-Dokument auf den Stand `next` (ohne Verlauf): nur die Felder, deren Referenz
|
||||
* sich geändert hat, je über {@link fieldOps} (Listen elementweise) — unveränderte Teile kosten
|
||||
* nichts. Kein Weg für Benutzer-Änderungen (die gehen als Ops über {@link commit}).
|
||||
*/
|
||||
sync(next: Project): void {
|
||||
if (next === this.mirror) return;
|
||||
const ops = diffToOps(this.mirror, next);
|
||||
const a = this.mirror as unknown as Record<string, unknown>;
|
||||
const b = next as unknown as Record<string, unknown>;
|
||||
const ops: CoreOp[] = [];
|
||||
for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
|
||||
if (a[key] !== b[key]) ops.push(...fieldOps(this.mirror, key as keyof Project, b[key] as never));
|
||||
}
|
||||
this.mirror = next;
|
||||
if (ops.length === 0) return;
|
||||
if (!this.handle) {
|
||||
@@ -106,7 +120,33 @@ export class ProjectDocument {
|
||||
return core().doc_query_bin(this.handle, name, Float64Array.from(args), text);
|
||||
}
|
||||
|
||||
/** Datei-Text des Projekts (Formatversion vorn, Einrückung 2). */
|
||||
/**
|
||||
* Projekt laden (Neu, Musterhaus, Abgleich nach einer Änderung vorbei an den Ops): ersetzt den
|
||||
* ganzen Inhalt im Kern und leert den Verlauf. `project` wird die Leseansicht (Identität bleibt).
|
||||
*/
|
||||
load(project: Project): void {
|
||||
this.mirror = project;
|
||||
if (!this.handle || !core().doc_load_json(this.handle, JSON.stringify(project))) this.reopen(project);
|
||||
}
|
||||
|
||||
/**
|
||||
* Projektdatei laden (Öffnen, Vorlage, Wiederherstellen; [K4] S4): der Kern liest den Text, migriert
|
||||
* ältere Formate, prüft und ergänzt (`project_format.rs`) und lädt das Ergebnis direkt ins Dokument
|
||||
* (Verlauf leer). Die Leseansicht kommt als JSON des Dokuments zurück. Bei Fehler bleibt alles, wie es war.
|
||||
*/
|
||||
loadFile(text: string, now = Date.now()): LoadFileResult {
|
||||
if (!this.handle) this.reopen({} as Project);
|
||||
if (!this.handle) return { ok: false, error: "Projekt-Dokument im Kern nicht offen." };
|
||||
const r = JSON.parse(core().doc_load_file(this.handle, text, now)) as
|
||||
| { ok: true; warnings: string[]; migratedFrom: number | null }
|
||||
| { ok: false; error: string };
|
||||
if (!r.ok) return r;
|
||||
const project = JSON.parse(core().doc_json(this.handle)) as Project;
|
||||
this.mirror = project;
|
||||
return { ok: true, project, warnings: r.warnings, migratedFrom: r.migratedFrom };
|
||||
}
|
||||
|
||||
/** Datei-Text des Projekts (Formatversion vorn, Einrückung 2, Zeichen für Zeichen wie `JSON.stringify`). */
|
||||
serialize(): string {
|
||||
return this.handle ? core().doc_serialize(this.handle) : "";
|
||||
}
|
||||
@@ -138,13 +178,11 @@ export class ProjectDocument {
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* geändert (fremder Stand), passt der Verlauf nicht mehr: `base` wird als Ganzes geladen.
|
||||
*/
|
||||
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);
|
||||
this.load(base);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -228,6 +266,15 @@ export class ProjectDocument {
|
||||
}
|
||||
|
||||
let shared: ProjectDocument | null = null;
|
||||
|
||||
/**
|
||||
* Das gemeinsame Abfrage-Dokument (ohne Verlauf), z. B. für das CLI: eine dort geladene Datei
|
||||
* ({@link ProjectDocument.loadFile}) ist sofort das Dokument der Abfragen auf ihrem Projekt.
|
||||
*/
|
||||
export function sharedDocument(): ProjectDocument {
|
||||
if (!shared) shared = new ProjectDocument({} as Project);
|
||||
return shared;
|
||||
}
|
||||
/** Dokument des Stores (mit Verlauf); Abfragen auf dessen aktuellem Projekt laufen direkt darüber. */
|
||||
let primary: ProjectDocument | null = null;
|
||||
|
||||
|
||||
+2
-2
@@ -19,7 +19,7 @@ export { exportProjectStep } from "../export/exportStep";
|
||||
export { planToSvgString } from "../export/planToSvgString";
|
||||
export { setWasmBytesProvider } from "../engine/wasmSource";
|
||||
export { initCore, coreReady } from "../engine/coreWasm";
|
||||
export { applyOps, diffToOps, validateProject, validateOps } from "./ops";
|
||||
export { applyOps, validateProject, validateOps } from "./ops";
|
||||
export type { CoreOp } from "./ops";
|
||||
export type { Project, DrawingLevel } from "../model/types";
|
||||
export { computeKennzahlen, checkRoomProgram, solidVolume } from "../analysis/kennzahlen";
|
||||
@@ -49,5 +49,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, replaceWithMany, setField, setFieldIfChanged } from "./opsBuild";
|
||||
export { addItems, fieldOps, findItem, itemsOf, opsMutation, patchItem, patchItems, removeItems, replaceItem, replaceWithMany, setField, setFieldIfChanged } from "./opsBuild";
|
||||
export type { EntityCollection, EntityOf, ProjectMutation } from "./opsBuild";
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { applyOps, diffToOps, validateProject } from "./ops";
|
||||
import { applyOps, validateProject } from "./ops";
|
||||
import { projectDiffOps } from "./projectDiff.testutil";
|
||||
import type { CoreOp } from "./ops";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Project } from "../model/types";
|
||||
@@ -29,20 +30,20 @@ function mutate(p: Project, seed: number): Project {
|
||||
|
||||
describe("CoreOps", () => {
|
||||
it("keine Änderung: keine Ops", () => {
|
||||
expect(diffToOps(sampleProject, sampleProject)).toEqual([]);
|
||||
expect(projectDiffOps(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));
|
||||
const ops = roundtrip(projectDiffOps(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));
|
||||
const out = applyOps(sampleProject, projectDiffOps(sampleProject, next));
|
||||
expect(out.walls[0]).toBe(sampleProject.walls[0]);
|
||||
expect(out.walls).toHaveLength(sampleProject.walls.length + 1);
|
||||
});
|
||||
@@ -63,7 +64,7 @@ describe("CoreOps", () => {
|
||||
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);
|
||||
const ops = projectDiffOps(withAnchor, next);
|
||||
expect(ops).toEqual([{ kind: "setField", key: "referenceElevationMasl" }]);
|
||||
expect("referenceElevationMasl" in applyOps(withAnchor, ops)).toBe(false);
|
||||
});
|
||||
|
||||
+6
-77
@@ -2,16 +2,14 @@
|
||||
// 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).
|
||||
// und beschreibt jede Änderung als Folge von {@link CoreOp}s (Bauhelfer `opsBuild.ts`) — das
|
||||
// Projekt ändert sich ausschliesslich durch Ops. Ops sind JSON-serialisierbar (Undo-Verlauf [84],
|
||||
// Makros [85], MCP [9]). Ein anderes Projekt als Ganzes lädt der Kern (`ProjectDocument.load`/`loadFile`).
|
||||
//
|
||||
// [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).
|
||||
// Rust-Kern (`src-tauri/core/src/ops.rs`, `document.rs`). Hier bleibt `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`
|
||||
@@ -37,75 +35,6 @@ export type CoreOp =
|
||||
* 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");
|
||||
|
||||
/** 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<string>();
|
||||
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<string, unknown>;
|
||||
const b = next as unknown as Record<string, unknown>;
|
||||
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). Unberührte Listen und Elemente behalten
|
||||
* ihre Identität. Innerhalb eines Aufrufs wird jede Liste höchstens einmal kopiert und für
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
// Op-Bauhelfer ([K4] S3): Ergebnis = das bisherige Projekt → Projekt-Muster (`map`/`filter`/Anhängen)
|
||||
// über `diffToOps`, auf Zufallsprojekten; unveränderte Elemente bleiben identisch.
|
||||
// über `projectDiffOps`, auf Zufallsprojekten; unveränderte Elemente bleiben identisch.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { applyOps, diffToOps } from "./ops";
|
||||
import { applyOps } from "./ops";
|
||||
import { projectDiffOps } from "./projectDiff.testutil";
|
||||
import {
|
||||
addItems,
|
||||
fieldOps,
|
||||
findItem,
|
||||
isOpsMutation,
|
||||
opsMutation,
|
||||
patchItem,
|
||||
patchItems,
|
||||
@@ -32,7 +32,7 @@ function project(seed: number): Project {
|
||||
}
|
||||
|
||||
/** Alter Weg: Projekt → Projekt, dann über die Differenz. */
|
||||
const viaDiff = (p: Project, next: Project): Project => applyOps(p, diffToOps(p, next));
|
||||
const viaDiff = (p: Project, next: Project): Project => applyOps(p, projectDiffOps(p, next));
|
||||
|
||||
describe("Op-Bauhelfer", () => {
|
||||
it("patchItem = map über die Liste (Teilobjekt und Funktion), Zufall", () => {
|
||||
@@ -119,18 +119,16 @@ describe("Op-Bauhelfer", () => {
|
||||
const levels = p.drawingLevels.filter(() => r() < 0.8).map((z) => (r() < 0.3 ? { ...z, visible: !z.visible } : z));
|
||||
if (r() < 0.3) levels.reverse();
|
||||
const next = { ...p, drawingLevels: levels };
|
||||
expect(fieldOps(p, "drawingLevels", levels)).toEqual(diffToOps(p, next));
|
||||
expect(fieldOps(p, "drawingLevels", levels)).toEqual(projectDiffOps(p, next));
|
||||
expect(applyOps(p, fieldOps(p, "drawingLevels", levels))).toEqual(next);
|
||||
}
|
||||
expect(fieldOps(sampleProject, "layers", sampleProject.layers)).toEqual([]);
|
||||
expect(fieldOps(sampleProject, "geoAnchor", undefined)).toEqual(diffToOps(sampleProject, { ...sampleProject, geoAnchor: undefined }));
|
||||
expect(fieldOps(sampleProject, "geoAnchor", undefined)).toEqual(projectDiffOps(sampleProject, { ...sampleProject, geoAnchor: undefined }));
|
||||
});
|
||||
|
||||
it("opsMutation: wirkt wie eine Projekt → Projekt-Funktion und trägt die Ops mit", () => {
|
||||
const id = sampleProject.walls[0].id;
|
||||
const m = opsMutation((p) => patchItem(p, "walls", id, { height: 4.2 }));
|
||||
expect(isOpsMutation(m)).toBe(true);
|
||||
expect(isOpsMutation((p: Project) => p)).toBe(false);
|
||||
expect(m(sampleProject).walls[0].height).toBe(4.2);
|
||||
expect(m.toOps(sampleProject)).toHaveLength(1);
|
||||
});
|
||||
|
||||
+61
-16
@@ -1,6 +1,6 @@
|
||||
// Op-Bauhelfer ([K4] S3, zweite Etappe): Aktionen beschreiben ihre Änderung direkt als
|
||||
// {@link CoreOp}s statt als Projekt → Projekt-Funktion, die `setProject` erst per `diffToOps` über
|
||||
// alle Listen zurückübersetzen muss (bei 3000 Wänden ≈ 2,4 ms je Mausschritt). Die Helfer lesen
|
||||
// {@link CoreOp}s statt als Projekt → Projekt-Funktion (früher übersetzte `setProject` sie per
|
||||
// Projekt-Differenz zurück: bei 3000 Wänden ≈ 2,4 ms je Mausschritt; die Differenz ist gelöscht). Die Helfer lesen
|
||||
// nur das betroffene Element; unveränderte Elemente bleiben unberührt (Identität in der
|
||||
// TS-Leseansicht, `applyOps`).
|
||||
//
|
||||
@@ -9,7 +9,7 @@
|
||||
// {@link opsMutation} die Ops mit — `setProject` nimmt dann die Ops ohne Differenz.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { applyOps, diffToOps } from "./ops";
|
||||
import { applyOps } from "./ops";
|
||||
import type { CoreOp } from "./ops";
|
||||
|
||||
/** Projekt-Felder, die Listen von Elementen mit `id` sind (walls, drawings2d, rooms, …). */
|
||||
@@ -173,28 +173,73 @@ export type ProjectMutation = ((p: Project) => Project) & { readonly toOps: (p:
|
||||
|
||||
/**
|
||||
* Verpackt einen Op-Bauer als Projekt → Projekt-Funktion (für Schnittstellen wie
|
||||
* `CommandResult.commit`). Aufgerufen liefert sie `applyOps(p, build(p))`; `setProject` erkennt
|
||||
* sie an `toOps` und übergibt die Ops ohne `diffToOps` an den Kern.
|
||||
* `CommandResult.commit`). Aufgerufen liefert sie `applyOps(p, build(p))`; `setProject` übergibt
|
||||
* ihre `toOps` an den Kern.
|
||||
*/
|
||||
export function opsMutation(build: (p: Project) => CoreOp[]): ProjectMutation {
|
||||
const fn = (p: Project): Project => applyOps(p, build(p));
|
||||
return Object.assign(fn, { toOps: build });
|
||||
}
|
||||
|
||||
/** Ob `fn` ihre Ops mitträgt. */
|
||||
export function isOpsMutation(fn: unknown): fn is ProjectMutation {
|
||||
return typeof fn === "function" && typeof (fn as Partial<ProjectMutation>).toOps === "function";
|
||||
}
|
||||
|
||||
/**
|
||||
* Ops, die das Feld `key` auf `value` bringen — für KLEINE Listen, die eine Hilfsfunktion als Ganzes
|
||||
* neu liefert (Ebenen nach `recomputeFloorElevations`, Kategorien-Baum …): Differenz nur über
|
||||
* dieses eine Feld (Elemente mit id einzeln, sonst `setField`). Grosse Listen (Wände, 2D) gehören
|
||||
* über {@link patchItem}/{@link patchItems}/{@link addItems}/{@link removeItems}.
|
||||
* dieses eine Feld (Elemente mit id einzeln: `remove`/`replace`/`reorder`/`add`, sonst `setField`).
|
||||
* `applyOps(p, fieldOps(p, key, v))[key]` ist inhaltlich `v`, Elemente aus `v` behalten ihre Identität.
|
||||
* Grosse Listen (Wände, 2D) gehören über {@link patchItem}/{@link patchItems}/{@link addItems}/{@link removeItems}.
|
||||
*/
|
||||
export function fieldOps<K extends keyof Project>(p: Project, key: K, value: Project[K] | undefined): CoreOp[] {
|
||||
if (p[key] === value) return [];
|
||||
const before = { [key]: p[key] } as unknown as Project;
|
||||
const after = (value === undefined ? {} : { [key]: value }) as unknown as Project;
|
||||
return diffToOps(before, after);
|
||||
const va = p[key] as unknown;
|
||||
const vb = value as unknown;
|
||||
if (va === vb) return [];
|
||||
if (isIdList(va) && isIdList(vb) && uniqueIds(va) && uniqueIds(vb)) return diffList(key, va, vb);
|
||||
return [vb === undefined ? { kind: "setField", key } : { kind: "setField", key, value: vb }];
|
||||
}
|
||||
|
||||
const isEntityList = (v: unknown): v is AnyEntity[] =>
|
||||
Array.isArray(v) && v.length > 0 && v.every((x) => x !== null && typeof x === "object" && typeof (x as AnyEntity).id === "string");
|
||||
|
||||
/** Ob `v` eine (auch leere) Liste ist, deren Elemente — falls vorhanden — alle `id`s tragen. */
|
||||
const isIdList = (v: unknown): v is AnyEntity[] => Array.isArray(v) && (v.length === 0 || isEntityList(v));
|
||||
|
||||
/** Eindeutige ids? (Voraussetzung für die Element-Ops.) */
|
||||
function uniqueIds(list: AnyEntity[]): boolean {
|
||||
const seen = new Set<string>();
|
||||
for (const e of list) {
|
||||
if (seen.has(e.id)) return false;
|
||||
seen.add(e.id);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function diffList(collection: string, va: AnyEntity[], vb: AnyEntity[]): CoreOp[] {
|
||||
const ops: CoreOp[] = [];
|
||||
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: AnyEntity[] = [];
|
||||
while (i < vb.length && !keptSet.has(vb[i].id)) run.push(vb[i++]);
|
||||
ops.push({ kind: "add", collection, items: run, at });
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// NUR für Tests: Ops, die `prev` in `next` überführen (je Feld `fieldOps`, Listen elementweise).
|
||||
// Die App erzeugt Änderungen direkt als Ops ([K4] S3, `opsBuild.ts`) und lädt ganze Projekte über
|
||||
// den Kern (`loadProject`/`openProjectFile`, S4); eine Projekt-Differenz gibt es dort nicht mehr. Die
|
||||
// Tests brauchen sie, um beliebige Zufallsänderungen als Ops an den Kern zu geben.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import type { CoreOp } from "./ops";
|
||||
import { fieldOps } from "./opsBuild";
|
||||
|
||||
export function projectDiffOps(prev: Project, next: Project): CoreOp[] {
|
||||
if (prev === next) return [];
|
||||
const a = prev as unknown as Record<string, unknown>;
|
||||
const b = next as unknown as Record<string, unknown>;
|
||||
const ops: CoreOp[] = [];
|
||||
for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
|
||||
if (a[key] !== b[key]) ops.push(...fieldOps(prev, key as keyof Project, b[key] as never));
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
Reference in new issue
Block a user