[K4][8] Op-Bauhelfer (core/opsBuild.ts), Gruppen mit Schlüssel im Store
- `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
This commit is contained in:
5 files changed
+289
-4
No files matched your search
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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";
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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<Project[K]> extends readonly (infer E)[]
|
||||
? E extends { id: string }
|
||||
? K
|
||||
: never
|
||||
: never;
|
||||
}[keyof Project];
|
||||
|
||||
/** Elementtyp einer Liste. */
|
||||
export type EntityOf<K extends EntityCollection> = NonNullable<Project[K]> extends readonly (infer E)[] ? E : never;
|
||||
|
||||
type AnyEntity = { id: string } & Record<string, unknown>;
|
||||
|
||||
/** Die Liste `collection` (fehlend = leer). */
|
||||
export function itemsOf<K extends EntityCollection>(p: Project, collection: K): readonly EntityOf<K>[] {
|
||||
const v = (p as unknown as Record<string, unknown>)[collection];
|
||||
return Array.isArray(v) ? (v as EntityOf<K>[]) : [];
|
||||
}
|
||||
|
||||
/** Element `id` aus `collection` (erstes Vorkommen). */
|
||||
export function findItem<K extends EntityCollection>(p: Project, collection: K, id: string): EntityOf<K> | undefined {
|
||||
return itemsOf(p, collection).find((e) => (e as { id: string }).id === id);
|
||||
}
|
||||
|
||||
/** Ersetzt ein Element (gleiche id, Position bleibt). */
|
||||
export function replaceItem<K extends EntityCollection>(collection: K, entity: EntityOf<K>): 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<K extends EntityCollection>(
|
||||
p: Project,
|
||||
collection: K,
|
||||
id: string,
|
||||
patch: Partial<EntityOf<K>> | ((e: EntityOf<K>) => EntityOf<K>),
|
||||
): CoreOp[] {
|
||||
const old = findItem(p, collection, id);
|
||||
if (old === undefined) return [];
|
||||
const next = typeof patch === "function" ? patch(old) : ({ ...old, ...patch } as EntityOf<K>);
|
||||
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<K extends EntityCollection>(
|
||||
p: Project,
|
||||
collection: K,
|
||||
ids: ReadonlySet<string> | readonly string[] | ((e: EntityOf<K>) => boolean),
|
||||
fn: (e: EntityOf<K>) => EntityOf<K>,
|
||||
): 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<K extends EntityCollection>(collection: K, items: readonly EntityOf<K>[], 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<K extends EntityCollection>(
|
||||
p: Project,
|
||||
collection: K,
|
||||
ids: ReadonlySet<string> | readonly string[] | ((e: EntityOf<K>) => boolean),
|
||||
): CoreOp[] {
|
||||
const hit = idTest(ids);
|
||||
const drop: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
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<K extends keyof Project>(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<K extends keyof Project>(p: Project, key: K, value: Project[K] | undefined): CoreOp[] {
|
||||
return p[key] === value ? [] : [setField(key, value)];
|
||||
}
|
||||
|
||||
function idTest<E>(ids: ReadonlySet<string> | 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<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}.
|
||||
*/
|
||||
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);
|
||||
}
|
||||
@@ -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<HistorySlice & { project: Proje
|
||||
d.clearHistory();
|
||||
set(historyPatch(d));
|
||||
},
|
||||
groupChanges: (fn) => {
|
||||
groupChanges: (fn, coalesceKey) => {
|
||||
const d = storeDocument(get().project);
|
||||
d.beginGroup();
|
||||
if (coalesceKey) d.beginKeyedGroup(coalesceKey, Date.now());
|
||||
else d.beginGroup();
|
||||
try {
|
||||
fn();
|
||||
} finally {
|
||||
|
||||
Reference in new issue
Block a user