Merge [K4][6][8] Aktionen erzeugen Ops direkt (Griffe, Objekt-Info, Auswahl, Zeichenbefehle ohne diffToOps), Gruppen mit Schluessel, schnelleres applyOps
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
60 files changed
+1780
-817
No files matched your search
@@ -210,6 +210,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);
|
||||
}
|
||||
|
||||
@@ -50,3 +50,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,130 @@
|
||||
// [K4] S3: `applyOps` führt die Leseansicht mit Op-Serien nach (z. B. 300 `replace` beim Verschieben
|
||||
// einer Auswahl). Die schnelle Fassung (Listen innerhalb eines Aufrufs nur einmal kopiert, id-Index
|
||||
// je Liste) muss genau das Ergebnis der einfachen Fassung liefern — hier als Referenz festgehalten.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { applyOps } from "./ops";
|
||||
import type { CoreOp } from "./ops";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Project } from "../model/types";
|
||||
|
||||
type Entity = { id: string } & Record<string, unknown>;
|
||||
|
||||
/** Referenz: die einfache Fassung (je Op eine neue Liste, lineare Suche). */
|
||||
function referenceApplyOps(project: Project, ops: readonly CoreOp[]): Project {
|
||||
let cur = project as unknown as Record<string, unknown>;
|
||||
const listOf = (c: string): Entity[] => (Array.isArray(cur[c]) ? (cur[c] as Entity[]) : []);
|
||||
for (const op of ops) {
|
||||
switch (op.kind) {
|
||||
case "setField": {
|
||||
if (op.value !== undefined && op.at !== undefined && !(op.key in cur)) {
|
||||
const entries = Object.entries(cur);
|
||||
entries.splice(Math.max(0, Math.min(entries.length, op.at)), 0, [op.key, op.value]);
|
||||
cur = Object.fromEntries(entries);
|
||||
break;
|
||||
}
|
||||
const next = { ...cur };
|
||||
if (op.value === undefined) delete next[op.key];
|
||||
else next[op.key] = op.value;
|
||||
cur = next;
|
||||
break;
|
||||
}
|
||||
case "add": {
|
||||
const list = listOf(op.collection);
|
||||
const at = op.at === undefined ? list.length : Math.max(0, Math.min(list.length, op.at));
|
||||
cur = { ...cur, [op.collection]: [...list.slice(0, at), ...op.items, ...list.slice(at)] };
|
||||
break;
|
||||
}
|
||||
case "replace": {
|
||||
const list = listOf(op.collection);
|
||||
const idx = list.findIndex((e) => e.id === op.entity.id);
|
||||
if (idx < 0) cur = { ...cur, [op.collection]: [...list, op.entity] };
|
||||
else {
|
||||
const out = list.slice();
|
||||
out[idx] = op.entity;
|
||||
cur = { ...cur, [op.collection]: out };
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "remove": {
|
||||
const drop = new Set(op.ids);
|
||||
cur = { ...cur, [op.collection]: listOf(op.collection).filter((e) => !drop.has(e.id)) };
|
||||
break;
|
||||
}
|
||||
case "reorder": {
|
||||
const list = listOf(op.collection);
|
||||
const byId = new Map(list.map((e) => [e.id, e]));
|
||||
const ordered = op.ids.map((id) => byId.get(id)).filter((e): e is Entity => e !== undefined);
|
||||
const inOps = new Set(op.ids);
|
||||
cur = { ...cur, [op.collection]: [...ordered, ...list.filter((e) => !inOps.has(e.id))] };
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return cur as unknown as Project;
|
||||
}
|
||||
|
||||
function rng(seed: number): () => number {
|
||||
let x = seed >>> 0;
|
||||
return () => ((x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296);
|
||||
}
|
||||
|
||||
/** Zufällige Op-Folge, auch Unsinn (fehlende ids, Doppelungen, Felder ohne Liste). */
|
||||
function randomOps(p: Project, seed: number): CoreOp[] {
|
||||
const r = rng(seed);
|
||||
const pick = <T,>(a: readonly T[]): T => a[Math.floor(r() * a.length)];
|
||||
const colls = ["walls", "drawings2d", "rooms", "nope", "name"];
|
||||
const ids = [...p.walls.map((w) => w.id), ...p.drawings2d.map((d) => d.id), "x1", "x2", "x3"];
|
||||
const ops: CoreOp[] = [];
|
||||
const n = 1 + Math.floor(r() * 25);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const c = pick(colls);
|
||||
const k = r();
|
||||
if (k < 0.45) ops.push({ kind: "replace", collection: c, entity: { id: pick(ids), v: Math.floor(r() * 100) } });
|
||||
else if (k < 0.6) {
|
||||
const items = Array.from({ length: Math.floor(r() * 3) }, () => ({ id: pick(ids), a: r() }));
|
||||
ops.push(r() < 0.5 ? { kind: "add", collection: c, items } : { kind: "add", collection: c, items, at: Math.floor(r() * 20) - 3 });
|
||||
} else if (k < 0.72) ops.push({ kind: "remove", collection: c, ids: [pick(ids), pick(ids)] });
|
||||
else if (k < 0.82) ops.push({ kind: "reorder", collection: c, ids: [pick(ids), pick(ids), pick(ids)] });
|
||||
else if (k < 0.9) ops.push({ kind: "setField", key: pick(colls), value: r() < 0.5 ? [{ id: pick(ids) }] : r() });
|
||||
else if (k < 0.95) ops.push({ kind: "setField", key: pick(colls) });
|
||||
else ops.push({ kind: "setField", key: `neu${Math.floor(r() * 3)}`, value: r(), at: Math.floor(r() * 5) });
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
describe("applyOps (schnelle Fassung) = Referenz", () => {
|
||||
it("2000 zufällige Op-Folgen: gleiches JSON, gleiche Feld-Reihenfolge, Original unberührt", () => {
|
||||
const snap = JSON.stringify(sampleProject);
|
||||
for (let seed = 1; seed <= 2000; seed++) {
|
||||
const ops = randomOps(sampleProject, seed);
|
||||
const a = applyOps(sampleProject, ops);
|
||||
const b = referenceApplyOps(sampleProject, ops);
|
||||
expect(JSON.stringify(a)).toBe(JSON.stringify(b));
|
||||
}
|
||||
expect(JSON.stringify(sampleProject)).toBe(snap);
|
||||
});
|
||||
|
||||
it("unberührte Listen und Elemente behalten ihre Identität", () => {
|
||||
const w = sampleProject.walls;
|
||||
const out = applyOps(sampleProject, [
|
||||
{ kind: "replace", collection: "walls", entity: { ...w[0], height: 7 } },
|
||||
{ kind: "replace", collection: "walls", entity: { ...w[1], height: 8 } },
|
||||
]);
|
||||
expect(out.drawings2d).toBe(sampleProject.drawings2d);
|
||||
expect(out.walls[2]).toBe(w[2]);
|
||||
expect(out.walls[0].height).toBe(7);
|
||||
expect(sampleProject.walls[0]).toBe(w[0]);
|
||||
expect(applyOps(sampleProject, [])).toBe(sampleProject);
|
||||
});
|
||||
|
||||
it("vom Aufrufer übergebene Werte werden nicht verändert", () => {
|
||||
const list = [{ id: "a" }, { id: "b" }];
|
||||
const out = applyOps(sampleProject, [
|
||||
{ kind: "setField", key: "walls", value: list },
|
||||
{ kind: "replace", collection: "walls", entity: { id: "a", z: 1 } },
|
||||
{ kind: "add", collection: "walls", items: [{ id: "c" }] },
|
||||
]);
|
||||
expect(list).toEqual([{ id: "a" }, { id: "b" }]);
|
||||
expect(out.walls).toEqual([{ id: "a", z: 1 }, { id: "b" }, { id: "c" }]);
|
||||
});
|
||||
});
|
||||
+73
-19
@@ -106,11 +106,27 @@ function diffList(collection: string, va: Entity[], vb: Entity[], ops: CoreOp[])
|
||||
}
|
||||
}
|
||||
|
||||
/** Wendet eine Op-Folge rein an (kein Zugriff auf Store/UI). */
|
||||
/**
|
||||
* 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
|
||||
* `replace`-Serien (Auswahl verschieben: hunderte Elemente) über einen id-Index angesprochen —
|
||||
* Ergebnis gleich der einfachen Fassung (Test `ops.apply.test.ts`).
|
||||
*/
|
||||
export function applyOps(project: Project, ops: readonly CoreOp[]): Project {
|
||||
let cur = project as unknown as Record<string, unknown>;
|
||||
for (const op of ops) cur = applyOne(cur, op);
|
||||
return cur as unknown as Project;
|
||||
if (ops.length === 0) return project;
|
||||
const st: ApplyState = { cur: { ...(project as unknown as Record<string, unknown>) }, owned: new Set(), index: new Map() };
|
||||
for (const op of ops) applyOne(st, op);
|
||||
return st.cur as unknown as Project;
|
||||
}
|
||||
|
||||
/** Zustand eines `applyOps`-Aufrufs: `cur` ist eine eigene Kopie der obersten Ebene; Listen in
|
||||
* `owned` wurden in diesem Aufruf neu angelegt (dürfen verändert werden), `index` = id → Position
|
||||
* (erstes Vorkommen) solcher Listen. */
|
||||
interface ApplyState {
|
||||
cur: Record<string, unknown>;
|
||||
owned: Set<string>;
|
||||
/** `null` = einmal linear gesucht, der Index wird bei der nächsten Suche gebaut. */
|
||||
index: Map<string, Map<string, number> | null>;
|
||||
}
|
||||
|
||||
function listOf(cur: Record<string, unknown>, collection: string): Entity[] {
|
||||
@@ -118,43 +134,81 @@ function listOf(cur: Record<string, unknown>, collection: string): Entity[] {
|
||||
return Array.isArray(v) ? (v as Entity[]) : [];
|
||||
}
|
||||
|
||||
function applyOne(cur: Record<string, unknown>, op: CoreOp): Record<string, unknown> {
|
||||
/** Setzt `collection` auf eine neue (eigene) Liste; ein vorhandener Index verfällt. */
|
||||
function putList(st: ApplyState, collection: string, list: Entity[]): void {
|
||||
st.cur[collection] = list;
|
||||
st.owned.add(collection);
|
||||
st.index.delete(collection);
|
||||
}
|
||||
|
||||
function applyOne(st: ApplyState, op: CoreOp): void {
|
||||
const cur = st.cur;
|
||||
switch (op.kind) {
|
||||
case "setField": {
|
||||
// Der Wert gehört dem Aufrufer: nie verändern.
|
||||
st.owned.delete(op.key);
|
||||
st.index.delete(op.key);
|
||||
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);
|
||||
st.cur = Object.fromEntries(entries);
|
||||
return;
|
||||
}
|
||||
const next = { ...cur };
|
||||
if (op.value === undefined) delete next[op.key];
|
||||
else next[op.key] = op.value;
|
||||
return next;
|
||||
if (op.value === undefined) delete cur[op.key];
|
||||
else cur[op.key] = op.value;
|
||||
return;
|
||||
}
|
||||
case "add": {
|
||||
const list = listOf(cur, op.collection);
|
||||
const at = op.at === undefined ? list.length : Math.max(0, Math.min(list.length, op.at));
|
||||
return { ...cur, [op.collection]: [...list.slice(0, at), ...op.items, ...list.slice(at)] };
|
||||
putList(st, op.collection, [...list.slice(0, at), ...op.items, ...list.slice(at)]);
|
||||
return;
|
||||
}
|
||||
case "replace": {
|
||||
const list = listOf(cur, op.collection);
|
||||
const idx = list.findIndex((e) => e.id === op.entity.id);
|
||||
if (idx < 0) return { ...cur, [op.collection]: [...list, op.entity] };
|
||||
const out = list.slice();
|
||||
out[idx] = op.entity;
|
||||
return { ...cur, [op.collection]: out };
|
||||
const c = op.collection;
|
||||
let list: Entity[];
|
||||
if (st.owned.has(c)) list = cur[c] as Entity[];
|
||||
else {
|
||||
list = listOf(cur, c).slice();
|
||||
putList(st, c, list);
|
||||
}
|
||||
// Erste Suche in dieser Liste linear (ein Drag-Schritt), ab der zweiten über den Index.
|
||||
let idx = st.index.get(c);
|
||||
let at: number | undefined;
|
||||
if (idx === undefined) {
|
||||
st.index.set(c, null);
|
||||
const i = list.findIndex((e) => e?.id === op.entity.id);
|
||||
at = i < 0 ? undefined : i;
|
||||
} else {
|
||||
if (idx === null) {
|
||||
idx = new Map();
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const id = list[i]?.id;
|
||||
if (!idx.has(id)) idx.set(id, i);
|
||||
}
|
||||
st.index.set(c, idx);
|
||||
}
|
||||
at = idx.get(op.entity.id);
|
||||
}
|
||||
if (at === undefined) {
|
||||
idx?.set(op.entity.id, list.length);
|
||||
list.push(op.entity);
|
||||
} else list[at] = op.entity;
|
||||
return;
|
||||
}
|
||||
case "remove": {
|
||||
const drop = new Set(op.ids);
|
||||
return { ...cur, [op.collection]: listOf(cur, op.collection).filter((e) => !drop.has(e.id)) };
|
||||
putList(st, op.collection, listOf(cur, op.collection).filter((e) => !drop.has(e.id)));
|
||||
return;
|
||||
}
|
||||
case "reorder": {
|
||||
const list = listOf(cur, op.collection);
|
||||
const byId = new Map(list.map((e) => [e.id, e]));
|
||||
const ordered = op.ids.map((id) => byId.get(id)).filter((e): e is Entity => e !== undefined);
|
||||
const inOps = new Set(op.ids);
|
||||
return { ...cur, [op.collection]: [...ordered, ...list.filter((e) => !inOps.has(e.id))] };
|
||||
putList(st, op.collection, [...ordered, ...list.filter((e) => !inOps.has(e.id))]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user