From b33f336bf0118b35e9655dd3d8afb091b148fdd1 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 22:02:25 +0000 Subject: [PATCH] =?UTF-8?q?[K4][8]=20Op-Bauhelfer=20(core/opsBuild.ts),=20?= =?UTF-8?q?Gruppen=20mit=20Schl=C3=BCssel=20im=20Store?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `patchItem`/`patchItems`/`addItems`/`removeItems`/`replaceItem`/`setField`/`fieldOps` (Differenz nur über ein kleines Feld) und `opsMutation`: Projekt → Projekt-Funktion, die ihre Ops mitträgt (für `CommandResult.commit`, Hüllen-Aufrufer von `setProject`). - `ProjectDocument.beginKeyedGroup`, Store `groupChanges(fn, coalesceKey?)`. - Tests: Helfer = bisheriges map/filter/Anhängen über `diffToOps` (Zufall), fieldOps = volle Differenz. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src/core/document.ts | 9 +++ src/core/extra.ts | 2 + src/core/opsBuild.test.ts | 115 ++++++++++++++++++++++++++++ src/core/opsBuild.ts | 155 ++++++++++++++++++++++++++++++++++++++ src/state/historySlice.ts | 12 ++- 5 files changed, 289 insertions(+), 4 deletions(-) create mode 100644 src/core/opsBuild.test.ts create mode 100644 src/core/opsBuild.ts diff --git a/src/core/document.ts b/src/core/document.ts index 5348a77e..375174c8 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -199,6 +199,15 @@ export class ProjectDocument { if (this.handle) core().doc_group_begin(this.handle); } + /** + * Wie {@link beginGroup}, mit `coalesceKey` (+ `now` in ms): aufeinanderfolgende Gruppen mit + * gleichem Schlüssel im Zeitfenster schliessen an denselben Undo-Schritt an (Griff-Zug, der je + * Mausschritt mehrere Elemente bewegt), [K4] S3. + */ + beginKeyedGroup(coalesceKey: string, now: number): void { + if (this.handle) core().doc_group_begin_keyed(this.handle, coalesceKey, now); + } + endGroup(): void { if (this.handle) core().doc_group_end(this.handle); } diff --git a/src/core/extra.ts b/src/core/extra.ts index 79eec142..10d83eb9 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -43,3 +43,5 @@ export { readPdfVectorPage, pdfPageToImport, pdfPageInfo, pdfMetersPerPt, isPdfF export type { PdfVectorPage, PdfVectorPath, PdfVectorText } from "../io/pdfVector"; export { readMesh, meshObjectsToImportedMeshes, formatMeshReport, isMeshFile, MESH_UNITS, MESH_UNIT_SCALE } from "../io/meshImport"; export type { MeshObject, MeshImportReport, MeshUnit, MeshUp, MeshPlacement } from "../io/meshImport"; +export { addItems, fieldOps, findItem, isOpsMutation, itemsOf, opsMutation, patchItem, patchItems, removeItems, replaceItem, setField, setFieldIfChanged } from "./opsBuild"; +export type { EntityCollection, EntityOf, ProjectMutation } from "./opsBuild"; diff --git a/src/core/opsBuild.test.ts b/src/core/opsBuild.test.ts new file mode 100644 index 00000000..083aa8c3 --- /dev/null +++ b/src/core/opsBuild.test.ts @@ -0,0 +1,115 @@ +// Op-Bauhelfer ([K4] S3): Ergebnis = das bisherige Projekt → Projekt-Muster (`map`/`filter`/Anhängen) +// über `diffToOps`, auf Zufallsprojekten; unveränderte Elemente bleiben identisch. +import { describe, expect, it } from "vitest"; +import { applyOps, diffToOps } from "./ops"; +import { + addItems, + fieldOps, + findItem, + isOpsMutation, + opsMutation, + patchItem, + patchItems, + removeItems, + setField, + setFieldIfChanged, +} from "./opsBuild"; +import { sampleProject } from "../model/sampleProject"; +import type { Project, Wall } from "../model/types"; + +function rng(seed: number): () => number { + let x = seed >>> 0; + return () => ((x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296); +} + +function project(seed: number): Project { + const r = rng(seed); + const n = 1 + Math.floor(r() * 40); + const base = sampleProject.walls; + const walls: Wall[] = Array.from({ length: n }, (_, i) => ({ ...base[i % base.length], id: `w${i}`, height: r() * 3 })); + return { ...sampleProject, walls }; +} + +/** Alter Weg: Projekt → Projekt, dann über die Differenz. */ +const viaDiff = (p: Project, next: Project): Project => applyOps(p, diffToOps(p, next)); + +describe("Op-Bauhelfer", () => { + it("patchItem = map über die Liste (Teilobjekt und Funktion), Zufall", () => { + for (let seed = 1; seed <= 300; seed++) { + const p = project(seed); + const r = rng(seed + 1000); + const id = `w${Math.floor(r() * (p.walls.length + 3))}`; // auch fehlende ids + const h = r(); + const a = applyOps(p, patchItem(p, "walls", id, { height: h })); + const b = viaDiff(p, { ...p, walls: p.walls.map((w) => (w.id === id ? { ...w, height: h } : w)) }); + expect(a).toEqual(b); + const f = (w: Wall): Wall => ({ ...w, start: { x: w.start.x + h, y: w.start.y } }); + expect(applyOps(p, patchItem(p, "walls", id, f))).toEqual(viaDiff(p, { ...p, walls: p.walls.map((w) => (w.id === id ? f(w) : w)) })); + // Unveränderte Elemente identisch. + const out = applyOps(p, patchItem(p, "walls", "w0", { height: 9 })); + if (p.walls.length > 1) expect(out.walls[1]).toBe(p.walls[1]); + } + }); + + it("patchItem: fehlendes Element oder gleiches Objekt → keine Op", () => { + expect(patchItem(sampleProject, "walls", "gibt-es-nicht", { height: 1 })).toEqual([]); + expect(patchItem(sampleProject, "walls", sampleProject.walls[0].id, (w) => w)).toEqual([]); + }); + + it("patchItems / removeItems / addItems = map / filter / Anhängen, Zufall", () => { + for (let seed = 1; seed <= 300; seed++) { + const p = project(seed); + const r = rng(seed + 7); + const ids = p.walls.filter(() => r() < 0.3).map((w) => w.id); + const set = new Set(ids); + const mv = (w: Wall): Wall => ({ ...w, start: { x: w.start.x, y: w.start.y + 1 }, end: { x: w.end.x, y: w.end.y + 1 } }); + expect(applyOps(p, patchItems(p, "walls", ids, mv))).toEqual(viaDiff(p, { ...p, walls: p.walls.map((w) => (set.has(w.id) ? mv(w) : w)) })); + expect(applyOps(p, removeItems(p, "walls", set))).toEqual(viaDiff(p, { ...p, walls: p.walls.filter((w) => !set.has(w.id)) })); + const extra: Wall[] = [{ ...p.walls[0], id: `neu${seed}` }]; + expect(applyOps(p, addItems("walls", extra))).toEqual(viaDiff(p, { ...p, walls: [...p.walls, ...extra] })); + const at = Math.floor(r() * p.walls.length); + expect(applyOps(p, addItems("walls", extra, at))).toEqual( + viaDiff(p, { ...p, walls: [...p.walls.slice(0, at), ...extra, ...p.walls.slice(at)] }), + ); + } + }); + + it("leere Änderungen ergeben keine Ops; Prädikat statt ids", () => { + expect(removeItems(sampleProject, "walls", [])).toEqual([]); + expect(addItems("walls", [])).toEqual([]); + expect(patchItems(sampleProject, "walls", () => false, (w) => ({ ...w }))).toEqual([]); + const first = sampleProject.walls[0].id; + expect(removeItems(sampleProject, "walls", (w) => w.id === first)).toEqual([{ kind: "remove", collection: "walls", ids: [first] }]); + expect(findItem(sampleProject, "walls", first)).toBe(sampleProject.walls[0]); + }); + + it("setField / setFieldIfChanged", () => { + expect(setField("name", "X")).toEqual({ kind: "setField", key: "name", value: "X" }); + expect(setField("geoAnchor", undefined)).toEqual({ kind: "setField", key: "geoAnchor" }); + expect(setFieldIfChanged(sampleProject, "name", sampleProject.name)).toEqual([]); + expect(applyOps(sampleProject, setFieldIfChanged(sampleProject, "name", "Y")).name).toBe("Y"); + }); + + it("fieldOps: Differenz nur über ein Feld = volle Differenz, Zufall", () => { + for (let seed = 1; seed <= 200; seed++) { + const p = project(seed); + const r = rng(seed + 99); + 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(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 })); + }); + + 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); + }); +}); diff --git a/src/core/opsBuild.ts b/src/core/opsBuild.ts new file mode 100644 index 00000000..81005b91 --- /dev/null +++ b/src/core/opsBuild.ts @@ -0,0 +1,155 @@ +// 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 +// nur das betroffene Element; unveränderte Elemente bleiben unberührt (Identität in der +// TS-Leseansicht, `applyOps`). +// +// Store: `applyChange(ops | (p) => ops, coalesceKey?)`. Wo eine Schnittstelle weiter eine +// Projekt → Projekt-Funktion erwartet (Befehle: `CommandResult.commit`), trägt +// {@link opsMutation} die Ops mit — `setProject` nimmt dann die Ops ohne Differenz. + +import type { Project } from "../model/types"; +import { applyOps, diffToOps } from "./ops"; +import type { CoreOp } from "./ops"; + +/** Projekt-Felder, die Listen von Elementen mit `id` sind (walls, drawings2d, rooms, …). */ +export type EntityCollection = { + [K in keyof Project]-?: NonNullable extends readonly (infer E)[] + ? E extends { id: string } + ? K + : never + : never; +}[keyof Project]; + +/** Elementtyp einer Liste. */ +export type EntityOf = NonNullable extends readonly (infer E)[] ? E : never; + +type AnyEntity = { id: string } & Record; + +/** Die Liste `collection` (fehlend = leer). */ +export function itemsOf(p: Project, collection: K): readonly EntityOf[] { + const v = (p as unknown as Record)[collection]; + return Array.isArray(v) ? (v as EntityOf[]) : []; +} + +/** Element `id` aus `collection` (erstes Vorkommen). */ +export function findItem(p: Project, collection: K, id: string): EntityOf | undefined { + return itemsOf(p, collection).find((e) => (e as { id: string }).id === id); +} + +/** Ersetzt ein Element (gleiche id, Position bleibt). */ +export function replaceItem(collection: K, entity: EntityOf): CoreOp { + return { kind: "replace", collection, entity: entity as unknown as AnyEntity }; +} + +/** + * Ändert Element `id` in `collection`: `patch` als Teilobjekt (`{ ...e, ...patch }`) oder Funktion. + * Leer, wenn das Element fehlt oder die Funktion dasselbe Objekt zurückgibt (keine Änderung). + */ +export function patchItem( + p: Project, + collection: K, + id: string, + patch: Partial> | ((e: EntityOf) => EntityOf), +): CoreOp[] { + const old = findItem(p, collection, id); + if (old === undefined) return []; + const next = typeof patch === "function" ? patch(old) : ({ ...old, ...patch } as EntityOf); + return next === old ? [] : [replaceItem(collection, next)]; +} + +/** + * Ändert alle Elemente, deren id in `ids` liegt (bzw. für die `ids(e)` wahr ist), mit `fn`; eine + * `replace`-Op je tatsächlich geändertem Element, in Listen-Reihenfolge. + */ +export function patchItems( + p: Project, + collection: K, + ids: ReadonlySet | readonly string[] | ((e: EntityOf) => boolean), + fn: (e: EntityOf) => EntityOf, +): CoreOp[] { + const hit = idTest(ids); + const ops: CoreOp[] = []; + for (const e of itemsOf(p, collection)) { + if (!hit(e)) continue; + const next = fn(e); + if (next !== e) ops.push(replaceItem(collection, next)); + } + return ops; +} + +/** Fügt Elemente an `at` (Default: Ende) ein; leer ohne Elemente. */ +export function addItems(collection: K, items: readonly EntityOf[], at?: number): CoreOp[] { + if (items.length === 0) return []; + const op: CoreOp = { kind: "add", collection, items: items as unknown as AnyEntity[] }; + if (at !== undefined) op.at = at; + return [op]; +} + +/** Entfernt die Elemente aus `ids` (bzw. für die `ids(e)` wahr ist), die es gibt; leer, wenn keines trifft. */ +export function removeItems( + p: Project, + collection: K, + ids: ReadonlySet | readonly string[] | ((e: EntityOf) => boolean), +): CoreOp[] { + const hit = idTest(ids); + const drop: string[] = []; + const seen = new Set(); + for (const e of itemsOf(p, collection)) { + const id = (e as { id: string }).id; + if (hit(e) && !seen.has(id)) { + seen.add(id); + drop.push(id); + } + } + return drop.length ? [{ kind: "remove", collection, ids: drop }] : []; +} + +/** Setzt ein Projekt-Feld (`undefined` ⇒ Feld entfernen). */ +export function setField(key: K, value: Project[K] | undefined): CoreOp { + return value === undefined ? { kind: "setField", key } : { kind: "setField", key, value }; +} + +/** Setzt ein Projekt-Feld nur, wenn sich der Wert (per Referenz) ändert. */ +export function setFieldIfChanged(p: Project, key: K, value: Project[K] | undefined): CoreOp[] { + return p[key] === value ? [] : [setField(key, value)]; +} + +function idTest(ids: ReadonlySet | readonly string[] | ((e: E) => boolean)): (e: E) => boolean { + if (typeof ids === "function") return ids; + const set = ids instanceof Set ? ids : new Set(ids as readonly string[]); + return (e) => set.has((e as unknown as { id: string }).id); +} + +// ── Projekt → Projekt mit mitgeführten Ops ───────────────────────────────── + +/** Projekt → Projekt-Funktion, die ihre Ops mitträgt (s. {@link opsMutation}). */ +export type ProjectMutation = ((p: Project) => Project) & { readonly toOps: (p: Project) => CoreOp[] }; + +/** + * 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. + */ +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).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}. + */ +export function fieldOps(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); +} diff --git a/src/state/historySlice.ts b/src/state/historySlice.ts index 00117599..910d80c1 100644 --- a/src/state/historySlice.ts +++ b/src/state/historySlice.ts @@ -34,8 +34,11 @@ export interface HistorySlice { redo: () => void; /** Verlauf leeren. */ clearHistory: () => void; - /** Alle Projekt-Änderungen in `fn` werden EIN Undo-Schritt. */ - groupChanges: (fn: () => void) => void; + /** + * Alle Projekt-Änderungen in `fn` werden EIN Undo-Schritt. Mit `coalesceKey` schliessen + * aufeinanderfolgende Gruppen mit gleichem Schlüssel (im Zeitfenster) an denselben Schritt an. + */ + groupChanges: (fn: () => void, coalesceKey?: string) => void; } let doc: ProjectDocument | null = null; @@ -82,9 +85,10 @@ export function createHistorySlice(api: StoreApi { + groupChanges: (fn, coalesceKey) => { const d = storeDocument(get().project); - d.beginGroup(); + if (coalesceKey) d.beginKeyedGroup(coalesceKey, Date.now()); + else d.beginGroup(); try { fn(); } finally {