[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:
Claude committed 2026-10-29 04:19:56 +00:00
1 parent 77b45c13a1
commit 256b7c0b4b
37 files changed
+582 -485

No files matched your search

+19 -25
View File
@@ -36,7 +36,7 @@ import { activePenSet, resolvePenColor, resolvePenWeight } from "./model/penSets
import { PenColorField } from "./ui/PenColorField";
import { generatePlan, computeKennzahlen, checkRoomProgram } from "./core";
import { programStatusLabel } from "./panels/KennzahlenSection";
import type { CategoryDisplayResolver } from "./core";
import type { CategoryDisplayResolver, ProjectMutation } from "./core";
import { sectionPlaneFromLevel, sectionUAxisModel } from "./core";
import { roofBaseElevation, roofGeometry } from "./core";
import { setDxfImportTrigger } from "./io/dxfImportHook";
@@ -156,8 +156,8 @@ import { useGripEditing } from "./state/useGripEditing";
import { usePanelHostBase } from "./state/usePanelHostBase";
import { useDockDragState } from "./state/useDockDragState";
import { useMouseSelectionHandlers } from "./state/useMouseSelectionHandlers";
import { activeGroupOps, addNewElementsToActiveGroup, containingGroupId, EMPTY_MEMBERSHIP } from "./state/groupActions";
import { addItems, fieldOps, isOpsMutation, opsMutation, patchItem, patchItems, removeItems, replaceItem, replaceWithMany, setFieldIfChanged } from "./core";
import { activeGroupOps, containingGroupId, EMPTY_MEMBERSHIP } from "./state/groupActions";
import { addItems, fieldOps, opsMutation, patchItem, patchItems, removeItems, replaceItem, replaceWithMany, setFieldIfChanged } from "./core";
import type { GroupMembership, MemberKind } from "./state/groupActions";
import { isLocked, lockMembersOps } from "./state/objectLock";
import { useProjectFileActions } from "./state/useProjectFileActions";
@@ -666,7 +666,7 @@ export default function App() {
// Wendet ein ToolResult an: Draft (+ Snap-Marker) zeigen, ggf. committen/abschließen.
const applyToolResult = (
res: { draft: ToolDraft | null; commit?: (p: Project) => Project; done?: boolean },
res: { draft: ToolDraft | null; commit?: ProjectMutation; done?: boolean },
snapResult: ReturnType<typeof snapFor>,
) => {
if (res.draft) setDraft({ ...res.draft, snap: snapResult });
@@ -937,23 +937,17 @@ export default function App() {
setDraft: (d) => cmdLatest.current.setDraft(d),
// Zeichnet man WÄHREND man eine Gruppe betreten hat (Isolation), wird
// das neue Element automatisch Mitglied dieser Gruppe (Nutzer-Wunsch:
// „wenn man etwas neu zeichnet ... zeichnet man in der Gruppe") — s.
// state/groupActions.ts::addNewElementsToActiveGroup (Diff vor/nach
// Commit über alle Elementarten, additiv zur eigentlichen Mutation).
// [K4] S3: Befehle mit mitgeführten Ops (`opsMutation`) gehen ohne Projekt-Differenz an den
// Kern; die Gruppen-Zuordnung kommt dann als weitere Ops dazu (`activeGroupOps`).
// „wenn man etwas neu zeichnet ... zeichnet man in der Gruppe"). [K4] S3:
// Befehle tragen ihre Ops mit (`opsMutation`); die Gruppen-Zuordnung kommt
// als weitere Ops dazu (`activeGroupOps`).
commit: (mutate) => {
const groupPath = cmdLatest.current.groupPath;
if (isOpsMutation(mutate)) {
cmdLatest.current.setProject(
opsMutation((p) => {
const ops = mutate.toOps(p);
return [...ops, ...activeGroupOps(p, ops, groupPath)];
}),
);
} else {
cmdLatest.current.setProject((p) => addNewElementsToActiveGroup(p, mutate(p), groupPath));
}
cmdLatest.current.setProject(
opsMutation((p) => {
const ops = mutate.toOps(p);
return [...ops, ...activeGroupOps(p, ops, groupPath)];
}),
);
},
isFloor: () => cmdLatest.current.activeLevel.kind === "floor",
// Frisch über `text`/`textbox` erzeugtes Element sofort inline editieren
@@ -1711,7 +1705,7 @@ export default function App() {
} = useProjectActions(applyChange, notify, planViewRef);
// IFC-Import: erst die Wahl Mesh/Bauteile (`IfcImportDialog`), dann [B3] Kontext-Meshes
// (`io/ifcImport.ts`) oder [B4] echte Bauteile (`io/ifcElements.ts`, übernommen über setProject).
// (`io/ifcImport.ts`) oder [B4] echte Bauteile (`io/ifcElements.ts`, übernommen als Ops).
const [pendingIfc, setPendingIfc] = useState<File | null>(null);
const importIfcFile = (f: File) => setPendingIfc(f);
const runIfcImport = (f: File, mode: IfcImportMode) => {
@@ -1722,12 +1716,13 @@ export default function App() {
.then(({ products, report, elements }) => {
let summary: ReturnType<typeof ifcElementsToProject>["summary"] | null = null;
let bounds: { x: number; y: number }[] = [];
setProject((p) => {
// Als Ops in einem Schritt ([K4] S3): ein IFC-Import = ein Undo-Schritt.
applyChange((p) => {
const r = ifcElementsToProject(p, products, elements, { fileName: f.name, geoOrigin: projectGeoOrigin(p) });
summary = r.summary;
const added = new Set(p.walls.map((w) => w.id));
bounds = r.project.walls.filter((w) => !added.has(w.id)).flatMap((w) => [w.start, w.end]);
return r.project;
return r.ops;
});
if (bounds.length) planViewRef.current?.fitBounds(bounds);
if (summary) {
@@ -1913,7 +1908,7 @@ export default function App() {
runImport,
} = useProjectFileActions(
project,
setProject,
applyChange,
setImportState,
setExportSaveFormat,
activeCategoryCode,
@@ -3124,10 +3119,9 @@ export default function App() {
// „Bild einfügen" (Werkzeug „image") — siehe state/useImportHandling.ts.
const { onImageOrPdfFileChosen } = useImageImportHandling({
project,
activeLevelId: activeLevel.id,
activeCategoryCode,
setProject,
applyChange,
notify,
setSelectedDrawingId,
setSelectedWallIds,
+22 -23
View File
@@ -94,8 +94,10 @@ import {
distinctImportLayers,
emptyProject,
generateElevationPlan,
diffToOps,
applyOps,
addItems,
fieldOps,
patchItem,
generatePlan,
generateSectionPlan,
planToRenderScene,
@@ -110,7 +112,7 @@ import {
validateProject,
sampleProject,
} from "../core";
import type { Project } from "../core";
import type { CoreOp, Project } from "../core";
import { serveStdio } from "./mcp";
type Args = { positional: string[]; flags: Map<string, string>; cmds: string[] };
@@ -396,7 +398,11 @@ async function importAny(path: string, args: Args): Promise<Project> {
...contoursToDrawings(parsed.contours, level.id, "byLayer", fallback, toCode, (l) => parsed.layerFillColors?.[l]),
...textsToDrawings(parsed.texts ?? [], level.id, "byLayer", fallback, toCode),
];
return applyOps(base, diffToOps(base, { ...base, layers, drawings2d: drawings, context: [...parsed.meshes] }));
return applyOps(base, [
...fieldOps(base, "layers", layers),
...fieldOps(base, "drawings2d", drawings),
...fieldOps(base, "context", [...parsed.meshes]),
]);
}
return fail(`Eingabeformat nicht unterstützt: .${ext} (obp, dxf, dwg, ifc, pdf, obj, stl, gltf, glb, ply)`);
}
@@ -436,6 +442,14 @@ async function convert(input: string | undefined, output: string | undefined, ar
return code === 0 ? runCmds(project, input, args) : code;
}
/** Ops: Kontext-Meshes anhängen und — wie in der App (siteSlice) — fehlende Kontext-Kategorien als Ebene ergänzen. */
function contextOps(project: Project, meshes: NonNullable<Project["context"]>): CoreOp[] {
return [
...(project.context ? addItems("context", meshes) : fieldOps(project, "context", meshes)),
...fieldOps(project, "layers", ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : [])))),
];
}
/** IFC in ein Projekt übernehmen (Kontext-Meshes, mit `--elements` als Bauteile); `report` = Bericht für `import-ifc`. */
async function ifcInto(project: Project, bytes: Uint8Array, fileName: string, args: Args): Promise<{ next: Project; report: unknown }> {
const group = args.flags.get("group");
@@ -444,7 +458,7 @@ async function ifcInto(project: Project, bytes: Uint8Array, fileName: string, ar
const { products, report, elements } = await readIfcElements(bytes);
const r = ifcElementsToProject(project, products, elements, { fileName, geoOrigin: projectGeoOrigin(project), group: grouping });
return {
next: applyOps(project, diffToOps(project, r.project)),
next: r.project,
report: { ...report, products: undefined, elements: r.summary, kept: elements.kept },
};
}
@@ -453,15 +467,7 @@ async function ifcInto(project: Project, bytes: Uint8Array, fileName: string, ar
const byClass: Record<string, number> = {};
for (const p of products) byClass[p.ifcClass] = (byClass[p.ifcClass] ?? 0) + 1;
const triangles = products.reduce((s, p) => s + p.indices.length / 3, 0);
const next = applyOps(
project,
diffToOps(project, {
...project,
context: [...(project.context ?? []), ...meshes],
// Wie in der App (siteSlice): fehlende Kontext-Kategorie als Ebene ergänzen.
layers: ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : []))),
}),
);
const next = applyOps(project, contextOps(project, meshes));
return { next, report: { ...report, byClass, triangles, contextObjects: meshes.length } };
}
@@ -508,14 +514,7 @@ async function meshInto(project: Project, bytes: Uint8Array, path: string, args:
return fail(`${path}: ${e instanceof Error ? e.message : String(e)}`);
}
const meshes = meshObjectsToImportedMeshes(read.objects, fileName, { placement, geoOrigin: projectGeoOrigin(project) });
const next = applyOps(
project,
diffToOps(project, {
...project,
context: [...(project.context ?? []), ...meshes],
layers: ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : []))),
}),
);
const next = applyOps(project, contextOps(project, meshes));
return { next, report: { ...read.report, contextObjects: meshes.length } };
}
@@ -796,8 +795,8 @@ async function execute(project: Project, file: string, command: string, rest: st
if (sec) await time("computeSection", () => computeSection(project, sec), Math.max(3, runs / 2));
if (elev) await time("generateElevationPlan", () => generateElevationPlan(project, elev), Math.max(3, runs / 2));
if (project.walls.length) {
const moved = { ...project, walls: [{ ...project.walls[0], height: (project.walls[0].height ?? 2.6) + 0.1 }, ...project.walls.slice(1)] };
await time("Op: diff+apply (1 Wand)", () => applyOps(project, diffToOps(project, moved)), runs * 20);
const w0 = project.walls[0];
await time("Op: patch+apply (1 Wand)", () => applyOps(project, patchItem(project, "walls", w0.id, { height: (w0.height ?? 2.6) + 0.1 })), runs * 20);
}
for (const [n, ms] of rows) process.stdout.write(`${n.padEnd(28)} ${ms.toFixed(2).padStart(9)} ms\n`);
return 0;
+3 -3
View File
@@ -7,7 +7,7 @@ import type { Command, CommandContext, CmdInput } from "../types";
import { explodeOps } from "../../editors/explode";
import { translateOps, translateProject } from "../../model/geoRebase";
import { applyOps } from "../../core/ops";
import { isOpsMutation } from "../../core";
import type { ProjectMutation } from "../../core";
import { joinCommand } from "./join";
import { defblockCommand } from "./defblock";
import { terrainCommand } from "./terrain";
@@ -45,13 +45,13 @@ function ctxOf(p: Project, ids: string[] = []): CommandContext {
function commitOf(cmd: Command, p: Project, inputs: CmdInput[], ids: string[] = []): { out: Project; viaOps: boolean } {
const ctx = ctxOf(p, ids);
let st = cmd.init();
let fn: ((p: Project) => Project) | undefined = cmd.autoRun?.(ctx).commit;
let fn: ProjectMutation | undefined = cmd.autoRun?.(ctx).commit;
for (const input of inputs) {
const [ns, res] = cmd.onInput(st, input, ctx);
st = ns;
if (res.commit) fn = res.commit;
}
return { out: fn ? fn(p) : p, viaOps: fn ? isOpsMutation(fn) : true };
return { out: fn ? fn(p) : p, viaOps: fn ? typeof fn.toOps === "function" : true };
}
describe("Editier-Befehle: Ops", () => {
+3 -2
View File
@@ -13,8 +13,9 @@
// Zustandsänderung ruft sie `emit()` → React-Komponenten (CommandLine, App)
// abonnieren via subscribe() und re-rendern.
import type { Project, Vec2 } from "../model/types";
import type { Vec2 } from "../model/types";
import type { SnapResult, ToolDraft } from "../tools/types";
import type { ProjectMutation } from "../core";
import { parseInput, resolvePoint } from "./parseInput";
import { getCommand, resolveCommand, autocomplete } from "./registry";
import type {
@@ -49,7 +50,7 @@ export interface EngineHost {
/** Vorschau setzen (oder löschen). */
setDraft(draft: ToolDraft | null): void;
/** Commit immutabel anwenden. */
commit(mutate: (p: Project) => Project): void;
commit(mutate: ProjectMutation): void;
/** Ist die aktive Ebene ein Geschoss? (für floorOnly-Befehle). */
isFloor(): boolean;
/**
+3 -2
View File
@@ -6,7 +6,8 @@ import { describe, expect, it } from "vitest";
import { COMMANDS } from "./registry";
import type { CmdInput, CommandContext } from "./types";
import { sampleProject } from "../model/sampleProject";
import { applyOps, diffToOps, validateOps } from "../core/ops";
import { applyOps, validateOps } from "../core/ops";
import { projectDiffOps } from "../core/projectDiff.testutil";
const level = sampleProject.drawingLevels.find((l) => l.kind === "floor")!;
const ctx: CommandContext = {
@@ -76,7 +77,7 @@ describe("Befehle mit feindlichen Eingaben", () => {
else [state, res] = cmd.onInput(state, hostile(opts), ctx);
if (res?.commit) {
const next = res.commit(sampleProject);
const ops = diffToOps(sampleProject, next);
const ops = projectDiffOps(sampleProject, next);
const applied = applyOps(sampleProject, ops);
validateOps(applied, ops, sampleProject); // darf melden, aber nicht werfen
}
+3 -2
View File
@@ -13,6 +13,7 @@ import type { Project, Vec2 } from "../model/types";
import type { TranslationKey } from "../i18n";
import type { DrawingLevel } from "../model/types";
import type { SnapResult, ToolDraft } from "../tools/types";
import type { ProjectMutation } from "../core";
export type { DraftShape, SnapResult, ToolDraft } from "../tools/types";
@@ -112,8 +113,8 @@ export interface CommandContext {
export interface CommandResult {
/** Neuer Vorschau-Zustand; null = nichts zu zeigen. */
draft: ToolDraft | null;
/** Bei Abschluss: immutable Mutation, die die Engine über setProject anwendet. */
commit?: (p: Project) => Project;
/** Bei Abschluss: Änderung mit mitgeführten Ops (`opsMutation`), die die Engine über setProject anwendet. */
commit?: ProjectMutation;
/** true → Befehl ist fertig und kehrt in den Ruhezustand zurück. */
done?: boolean;
/**
+10 -9
View File
@@ -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
View File
@@ -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
View File
@@ -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";
+6 -5
View File
@@ -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
View File
@@ -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
+6 -8
View File
@@ -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
View File
@@ -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;
}
+19
View File
@@ -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;
}
+3 -2
View File
@@ -6,7 +6,8 @@ import "../engine/fileioWasm.setup";
import { describe, expect, it } from "vitest";
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
import { applyOps, diffToOps, validateProject } from "../core/ops";
import { applyOps, validateProject } from "../core/ops";
import { projectDiffOps } from "../core/projectDiff.testutil";
import { exportIfcSpf } from "../export/exportIfc";
import { emptyProject, sampleProject } from "../model/sampleProject";
import type { Column, Opening, Project, Vec2, Wall } from "../model/types";
@@ -143,7 +144,7 @@ describe("IFC-Import als Bauteile: Rundreise Demo-Haus", () => {
it("über Ops angewandt und gespeichert/geladen bleibt alles gleich", async () => {
const { project: next } = await importInto(emptyProject, sampleProject);
const applied = applyOps(emptyProject, diffToOps(emptyProject, next));
const applied = applyOps(emptyProject, projectDiffOps(emptyProject, next));
expect(applied.walls).toEqual(next.walls);
expect(applied.openings).toEqual(next.openings);
const back = parseProjectFile(serializeProject(applied));
+29 -23
View File
@@ -5,10 +5,14 @@
// konnte, kommt wie beim Mesh-Import als Kontext-Mesh (`ifcImport.ts`).
//
// Keine Geometrie-Rechnung hier: TS ordnet nur zu (Geschoss nach Höhe, Typ nach Schichten) und setzt
// die Objekte zusammen. Das Projekt wird nicht verändert — der Aufrufer übernimmt das Ergebnis über
// `setProject` (App) bzw. `diffToOps`/`applyOps` (CLI), also über Ops.
// die Objekte zusammen. Das Projekt wird nicht verändert — das Ergebnis sind Ops ([K4] S3), die der
// Aufrufer übernimmt (App: Store `applyChange`, ein Undo-Schritt; CLI: `applyOps`).
import { ensureContextCategories } from "../model/contextCategories";
import { applyOps } from "../core/ops";
import type { CoreOp } from "../core/ops";
import { addItems, fieldOps } from "../core/opsBuild";
import type { EntityOf } from "../core/opsBuild";
import type {
Ceiling,
CeilingType,
@@ -287,8 +291,8 @@ function flatCategories(list: LayerCategory[], out: LayerCategory[] = []): Layer
}
/**
* Setzt die erkannten Bauteile und die übrigen Kontext-Meshes ins Projekt (neues Objekt, das alte
* bleibt unverändert). Geschosse werden nach Höhe wiederverwendet (±5 mm) oder angelegt, Wand- und
* Setzt die erkannten Bauteile und die übrigen Kontext-Meshes ins Projekt: `ops` (für den Store),
* `project` = `applyOps(project, ops)` (neues Objekt, das alte bleibt unverändert). Geschosse werden nach Höhe wiederverwendet (±5 mm) oder angelegt, Wand- und
* Deckentypen nach Schichten (Material + Dicke) wiederverwendet oder angelegt, Materialien nach Namen.
*/
export function ifcElementsToProject(
@@ -296,7 +300,7 @@ export function ifcElementsToProject(
products: IfcProduct[],
elements: IfcElementsData,
opts: IfcElementsOptions,
): { project: Project; summary: IfcElementsSummary } {
): { ops: CoreOp[]; project: Project; summary: IfcElementsSummary } {
const stamp = Date.now().toString(36);
const newId = (kind: string) => `ifc-${kind}-${stamp}-${counter++}`;
const summary: IfcElementsSummary = {
@@ -559,25 +563,27 @@ export function ifcElementsToProject(
withClass(elements.walls) + withClass(elements.openings.filter((o) => o.kind !== "hole")) + withClass(elements.slabs) + withClass(elements.columns) + withClass(elements.spaces) +
products.filter((p) => p.classifications?.length).length;
const next: Project = {
...project,
drawingLevels: levels,
components,
wallTypes,
...(ceilingTypes.length || project.ceilingTypes ? { ceilingTypes } : {}),
walls: [...project.walls, ...walls],
openings: [...(project.openings ?? []), ...openings],
ceilings: [...(project.ceilings ?? []), ...ceilings],
columns: [...(project.columns ?? []), ...columns],
rooms: [...(project.rooms ?? []), ...rooms],
// Fehlende Listen werden (wie früher beim Ersetzen des Projekts) leer angelegt.
const list = <K extends "openings" | "ceilings" | "columns" | "rooms">(key: K, items: EntityOf<K>[]): CoreOp[] =>
project[key] ? addItems(key, items) : fieldOps(project, key, items as Project[K]);
const ops: CoreOp[] = [
...fieldOps(project, "drawingLevels", levels),
...fieldOps(project, "components", components),
...fieldOps(project, "wallTypes", wallTypes),
...(ceilingTypes.length || project.ceilingTypes ? fieldOps(project, "ceilingTypes", ceilingTypes) : []),
...addItems("walls", walls),
...list("openings", openings),
...list("ceilings", ceilings),
...list("columns", columns),
...list("rooms", rooms),
...(meshes.length
? {
context: [...(project.context ?? []), ...meshes],
layers: ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : []))),
}
: {}),
};
return { project: next, summary };
? [
...(project.context ? addItems("context", meshes) : fieldOps(project, "context", meshes)),
...fieldOps(project, "layers", ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : [])))),
]
: []),
];
return { ops, project: applyOps(project, ops), summary };
}
/** Meldung zum Bauteil-Import; `tr` übersetzt (Kern kennt kein i18n). */
+46
View File
@@ -71,3 +71,49 @@ describe("Migration 1 → 2: Legacy-Türen werden Öffnungen", () => {
expect(r.project.openings!.some((o) => o.id === `${existing}-t` && o.kind === "door")).toBe(true);
});
});
describe("Laden und Speichern im Kern ([K4] S4)", () => {
// Früher: TS `JSON.parse` → Prüfung/Migration → `JSON.stringify({ formatVersion, ...rest }, null, 2)`.
// Heute liest, migriert und schreibt der Kern; die Datei muss Zeichen für Zeichen gleich bleiben
// (Zahlen wie JS `String(n)`, Index-Schlüssel wie ein JS-Objekt vorn).
const reference = (p: object): string => JSON.stringify({ formatVersion: PROJECT_FORMAT_VERSION, ...p }, null, 2);
const TRICKY = [0.000005, 1.5e-7, 1e21, 2 ** 60, 2 ** 53 + 2, -0, 0.1 + 0.2, 1e16, 2.7755575615628914e-17, -1e-6];
it("Speichern nach Öffnen = JSON.stringify der Leseansicht (Beispiel, knifflige Zahlen, Index-Schlüssel)", () => {
const odd = {
...structuredClone(sampleProject),
walls: sampleProject.walls.map((w, i) => ({ ...w, height: TRICKY[i % TRICKY.length] })),
zukunft: { b: 1, "21": "x\u0001\n😀", "10": [1.0, 2.5e-7], "007": null, "4294967295": 0 },
};
const texts = [JSON.stringify(sampleProject), JSON.stringify(odd), JSON.stringify(odd, null, 2).replace(/: 2,/g, ": 2.0,")];
for (const text of texts) {
const r = parseProjectFile(text);
expect(r.ok).toBe(true);
if (!r.ok) continue;
const saved = serializeProject(r.project);
expect(saved).toBe(reference(r.project));
const { formatVersion: _v, ...raw } = JSON.parse(text) as Record<string, unknown>;
expect(saved).toBe(reference(raw));
}
});
it("Index-Schlüssel stehen vorn, aufsteigend (wie JSON.parse in JS)", () => {
const text = `{"walls":[],"layers":[],"drawingLevels":[],"m":{"x":1,"10":2,"2":3,"01":4}}`;
const r = parseProjectFile(text);
expect(r.ok && Object.keys((r.project as unknown as { m: object }).m)).toEqual(["2", "10", "x", "01"]);
expect(r.ok && serializeProject(r.project)).toBe(r.ok && reference(r.project));
});
it("migrierte Datei wird im neuen Format gespeichert", () => {
const old = { ...structuredClone(sampleProject), formatVersion: 1, doors: [{ id: "TX", hostWallId: "W1", position: 0.5, width: 0.9, height: 2.1 }] };
const r = parseProjectFile(JSON.stringify(old));
expect(r.ok).toBe(true);
if (!r.ok) return;
const saved = serializeProject(r.project);
expect(saved).toBe(reference(r.project));
expect(JSON.parse(saved).doors).toBeUndefined();
const again = parseProjectFile(saved);
expect(again.ok && again.migratedFrom).toBeNull();
expect(again.ok && serializeProject(again.project)).toBe(saved);
});
});
+12 -13
View File
@@ -1,5 +1,7 @@
// Projektdatei-Format (`.obp`/`.obpt`/Alt-`.json`): Versionierung, Migration und EIN Parser für alle
// Ladestellen. Gerechnet wird im Rust-Kern (`src-tauri/core/src/project_format.rs`, [K4]).
// Ladestellen. Gerechnet wird im Rust-Kern (`src-tauri/core/src/project_format.rs`, [K4] S4): der Kern
// liest den Text, migriert und lädt das Ergebnis direkt in ein Kern-Dokument; Speichern schreibt der
// Kern aus dem Dokument (Zeichen für Zeichen wie `JSON.stringify(…, null, 2)`).
//
// Regeln:
// • Jede gespeicherte Datei trägt `formatVersion` (s. {@link PROJECT_FORMAT_VERSION}).
@@ -9,26 +11,23 @@
// • Tolerant lesen: fehlende Listen werden leer ergänzt, unbekannte Felder bleiben erhalten und
// werden gemeldet (nicht gelöscht).
// • Was kein Dossier-Projekt ist, ist ein Fehler mit Meldung — nie ein stilles `console.warn`.
//
// Im Store öffnet `openProjectFile` (projectSlice) die Datei im Store-Dokument (mit Verlauf); diese
// Fassade lädt ins gemeinsame Abfrage-Dokument (CLI, MCP, Tests) — die Abfragen auf dem gelesenen
// Projekt laufen danach ohne erneute Übergabe.
import type { Project } from "../model/types";
import { core } from "../engine/coreWasm";
import { documentFor } from "../core/document";
import { documentFor, sharedDocument } from "../core/document";
import type { LoadFileResult } from "../core/document";
/** Aktuelle Version des Dateiformats (muss `PROJECT_FORMAT_VERSION` im Kern entsprechen — Test). */
export const PROJECT_FORMAT_VERSION = 2;
export type ParseProjectResult =
| { ok: true; project: Project; warnings: string[]; migratedFrom: number | null }
| { ok: false; error: string };
export type ParseProjectResult = LoadFileResult;
/** Liest eine Projektdatei (Text) tolerant ein, migriert und prüft sie. */
/** Liest eine Projektdatei (Text) tolerant ein, migriert und prüft sie (Kern, gemeinsames Dokument). */
export function parseProjectFile(text: string): ParseProjectResult {
return JSON.parse(core().project_parse(text, Date.now())) as ParseProjectResult;
}
/** Wie {@link parseProjectFile}, für ein bereits geparstes Objekt. */
export function parseProjectObject(raw: unknown): ParseProjectResult {
return parseProjectFile(JSON.stringify(raw ?? null));
return sharedDocument().loadFile(text);
}
/** Serialisiert ein Projekt für die Datei (mit aktueller Formatversion vorne). */
+1 -1
View File
@@ -22,7 +22,7 @@ function bigProject(n: number): Project {
describe("Messung Store-Aktionen, 3000 Wände", () => {
it("Griff ziehen, Auswahl verschieben, Eigenschaft tippen", () => {
st().setProject(bigProject(3000));
st().loadProject(bigProject(3000));
st().clearHistory();
const depth0 = st().undoDepth;
+2 -2
View File
@@ -1,5 +1,5 @@
// [K4] S3 zweite Etappe: Store-Aktionen erzeugen Ops direkt (`applyChange`, `opsMutation`) statt
// Projekt → Projekt + `diffToOps`. Geprüft: Ops gehen unverändert an den Kern (Verlauf, Prüfung),
// Projekt → Projekt + Projekt-Differenz (gelöscht). Geprüft: Ops gehen unverändert an den Kern (Verlauf, Prüfung),
// Leseansicht und Kern-Dokument bleiben gleich — auch über Zufallsfolgen der umgestellten
// Aktionen mit Undo bis zum Anfang und Redo bis zum Ende.
import { beforeEach, describe, expect, it } from "vitest";
@@ -40,7 +40,7 @@ function expectMirror(): void {
}
beforeEach(() => {
st().setProject(structuredClone(sampleProject));
st().loadProject(structuredClone(sampleProject));
st().clearHistory();
});
+12 -5
View File
@@ -17,18 +17,25 @@ const UNSAVED = "unsaved";
/** Schlüssel der Wiederherstellungskopie für eine Datei (oder ein ungespeichertes Projekt). */
export const autosaveKey = (path: string | null): string => PREFIX + (path ?? UNSAVED);
export const writeAutosave = (path: string | null, project: Project): Promise<void> =>
saveProject(autosaveKey(path), project);
/** Sichert den Datei-Text des Projekts (`serializeProject`, wie beim Speichern; [K4] S4). */
export const writeAutosave = (path: string | null, text: string): Promise<void> =>
saveProject(autosaveKey(path), text);
export const readAutosave = (path: string | null): Promise<{ project: Project; savedAt: number } | null> =>
loadProjectRecord(autosaveKey(path));
/** Liest die Kopie als Datei-Text (ältere Kopien als Objekt werden zu Text) — Wiederherstellen lädt sie
* wie eine Datei (`openProjectFile`: Migration, Prüfung). */
export const readAutosave = async (path: string | null): Promise<{ text: string; savedAt: number } | null> => {
const r = await loadProjectRecord(autosaveKey(path));
if (!r) return null;
return { text: typeof r.project === "string" ? r.project : JSON.stringify(r.project), savedAt: r.savedAt };
};
export const clearAutosave = (path: string | null): Promise<void> => deleteProject(autosaveKey(path));
/** Eine angebotene Wiederherstellung. */
export interface AutosaveRecovery {
path: string | null;
project: Project;
/** Datei-Text der Kopie. */
text: string;
savedAt: number;
}
+16 -44
View File
@@ -8,7 +8,6 @@
import { describe, it, expect } from "vitest";
import {
activeGroupOps,
addNewElementsToActiveGroup,
applyGroupDimming,
applyGroupDimmingToPlan,
containingGroupId,
@@ -220,36 +219,36 @@ describe("applyGroupDimmingToPlan", () => {
});
});
describe("addNewElementsToActiveGroup", () => {
describe("activeGroupOps ([K4] S3: neue Elemente in die aktive Gruppe, als Ops)", () => {
const g1: Group = { id: "g1", wallIds: ["w1"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: [] };
const line = (id: string) =>
({ id, type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } } }) as Project["drawings2d"][number];
/** Wendet `ops` plus die Gruppen-Ops an (wie `EngineHost.commit` in App.tsx). */
const commit = (before: Project, ops: CoreOp[], path: string[]) => applyOps(before, [...ops, ...activeGroupOps(before, ops, path)]);
it("neu gezeichnetes Element wird Mitglied der aktiven (innersten) Gruppe", () => {
const before = project([g1]);
const after: Project = { ...before, drawings2d: [line("d1")] };
const result = addNewElementsToActiveGroup(before, after, ["g1"]);
const result = commit(project([g1]), addItems("drawings2d", [line("d1")]), ["g1"]);
const g = result.groups!.find((x) => x.id === "g1")!;
expect(g.drawingIds).toEqual(["d1"]);
expect(g.wallIds).toEqual(["w1"]); // bestehende Mitgliedschaft bleibt
});
it("ohne aktive Gruppe (groupPath leer) bleibt das Projekt unverändert", () => {
const before = project([g1]);
const after: Project = { ...before, drawings2d: [line("d1")] };
const result = addNewElementsToActiveGroup(before, after, []);
expect(result).toBe(after); // unverändert (Referenzgleichheit)
it("ohne aktive Gruppe (groupPath leer) keine zusätzlichen Ops", () => {
expect(activeGroupOps(project([g1]), addItems("drawings2d", [line("d1")]), [])).toEqual([]);
});
it("keine Änderung (before === after) ist ein No-op", () => {
const p = project([g1]);
expect(addNewElementsToActiveGroup(p, p, ["g1"])).toBe(p);
it("ohne neue Elemente (nur Ersetzen) keine zusätzlichen Ops", () => {
const p: Project = { ...project([g1]), drawings2d: [line("d0")] };
expect(activeGroupOps(p, [replaceItem("drawings2d", { ...line("d0"), color: "#f00" })], ["g1"])).toEqual([]);
expect(activeGroupOps(p, [], ["g1"])).toEqual([]);
});
it("unbekannte aktive Gruppe: keine zusätzlichen Ops", () => {
expect(activeGroupOps(project([g1]), addItems("drawings2d", [line("d1")]), ["gx"])).toEqual([]);
});
it("mehrere neue Elemente auf einmal (z. B. Feld/Array) werden alle Mitglied", () => {
const before = project([g1]);
const after: Project = { ...before, drawings2d: [line("d1"), line("d2"), line("d3")] };
const result = addNewElementsToActiveGroup(before, after, ["g1"]);
const result = commit(project([g1]), addItems("drawings2d", [line("d1"), line("d2"), line("d3")]), ["g1"]);
const g = result.groups!.find((x) => x.id === "g1")!;
expect(g.drawingIds.sort()).toEqual(["d1", "d2", "d3"]);
});
@@ -257,39 +256,12 @@ describe("addNewElementsToActiveGroup", () => {
it("verschachtelt: neues Element landet in der INNERSTEN (aktiven) Gruppe, nicht der äusseren", () => {
const inner: Group = { id: "g1", wallIds: [], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: [] };
const outer: Group = { id: "g2", wallIds: [], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: ["g1"] };
const before = project([inner, outer]);
const after: Project = { ...before, drawings2d: [line("d1")] };
const result = addNewElementsToActiveGroup(before, after, ["g2", "g1"]);
const result = commit(project([inner, outer]), addItems("drawings2d", [line("d1")]), ["g2", "g1"]);
expect(result.groups!.find((x) => x.id === "g1")!.drawingIds).toEqual(["d1"]);
expect(result.groups!.find((x) => x.id === "g2")!.drawingIds).toEqual([]);
});
});
describe("activeGroupOps ([K4] S3: Ops statt Differenz)", () => {
const mk = (id: string): Group => ({ id, wallIds: ["w1"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: [] });
const line = (id: string) =>
({ id, type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } } }) as Project["drawings2d"][number];
const wall = (id: string) => ({ id, start: { x: 0, y: 0 }, end: { x: 1, y: 0 } }) as unknown as Project["walls"][number];
it("gleiches Ergebnis wie addNewElementsToActiveGroup, Zufall", () => {
let x = 11;
const r = () => ((x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296);
for (let n = 0; n < 200; n++) {
const before: Project = { ...project([mk("g1"), mk("g2")]), drawings2d: [line("d0")], walls: [wall("w0")] };
const ops: CoreOp[] = [];
const k = Math.floor(r() * 4);
if (k >= 1) ops.push(...addItems("drawings2d", [line(`a${n}`), line(`b${n}`)], r() < 0.5 ? 0 : undefined));
if (k >= 2) ops.push(...addItems("walls", [wall(`w${n}x`)]));
if (k >= 3) ops.push(replaceItem("drawings2d", { ...line("d0"), color: "#f00" }));
const path = r() < 0.2 ? [] : r() < 0.5 ? ["g1"] : ["g2", "g1", "gx"];
const after = applyOps(before, ops);
const legacy = addNewElementsToActiveGroup(before, after, path);
const viaOps = applyOps(before, [...ops, ...activeGroupOps(before, ops, path)]);
expect(viaOps).toEqual(legacy);
}
});
});
describe("ungroup", () => {
it("löst genau EIN Level auf; Untergruppen bleiben als eigene Gruppen bestehen", () => {
const inner: Group = { id: "g1", wallIds: ["w1"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: [] };
+5 -44
View File
@@ -255,47 +255,6 @@ export function applyGroupDimmingToPlan(plan: Plan, project: Project, groupPath:
return { ...plan, primitives, underlay };
}
/** IDs, die in `after` neu hinzugekommen sind (in `before` noch nicht vorhanden). */
function newIds(before: { id: string }[], after: { id: string }[]): string[] {
const beforeIds = new Set(before.map((x) => x.id));
return after.filter((x) => !beforeIds.has(x.id)).map((x) => x.id);
}
/**
* Zeichnet man WÄHREND man eine Gruppe betreten hat (Isolation) ein neues
* Element, wird es automatisch Mitglied dieser (innersten) Gruppe — man
* zeichnet ja SICHTLICH „in" ihr (Nutzer-Wunsch, Vectorworks-Verhalten).
* Vergleicht `before`/`after` je Elementart auf neu hinzugekommene IDs (Diff
* über die commit-Mutation) und hängt sie an die aktive Gruppe an. `before`
* === `after` (keine Änderung) oder `groupPath` leer → `after` unverändert.
*/
export function addNewElementsToActiveGroup(
before: Project,
after: Project,
groupPath: string[],
): Project {
if (groupPath.length === 0 || before === after) return after;
const activeId = groupPath[groupPath.length - 1];
const g = (after.groups ?? []).find((x) => x.id === activeId);
if (!g) return after;
const added: GroupMembership = {
wallIds: newIds(before.walls, after.walls),
drawingIds: newIds(before.drawings2d, after.drawings2d),
ceilingIds: newIds(before.ceilings ?? [], after.ceilings ?? []),
roomIds: newIds(before.rooms ?? [], after.rooms ?? []),
stairIds: newIds(before.stairs ?? [], after.stairs ?? []),
columnIds: newIds(before.columns ?? [], after.columns ?? []),
roofIds: newIds(before.roofs ?? [], after.roofs ?? []),
openingIds: newIds(before.openings ?? [], after.openings ?? []),
};
if (KEYS.every((k) => added[k].length === 0)) return after;
const merged: Group = { ...g, ...mergeMembership(g, added) };
return {
...after,
groups: (after.groups ?? []).map((x) => (x.id === activeId ? merged : x)),
};
}
/** Liste je Mitgliedsart. */
const COLLECTION_OF: Record<MemberKind, EntityCollection> = {
wallIds: "walls",
@@ -309,9 +268,11 @@ const COLLECTION_OF: Record<MemberKind, EntityCollection> = {
};
/**
* Wie {@link addNewElementsToActiveGroup}, für eine Änderung als Ops ([K4] S3): die zusätzlichen
* Ops, die die neu eingefügten Elemente (`add`-Ops) der aktiven Gruppe zuschlagen — ohne Differenz
* über alle Listen. Leer ohne aktive Gruppe oder ohne neue Elemente.
* Zeichnet man WÄHREND man eine Gruppe betreten hat (Isolation) ein neues Element, wird es
* automatisch Mitglied dieser (innersten) Gruppe — man zeichnet ja SICHTLICH „in" ihr
* (Nutzer-Wunsch, Vectorworks-Verhalten). Für eine Änderung als Ops ([K4] S3): die zusätzlichen
* Ops, die die neu eingefügten Elemente (`add`-Ops) der aktiven Gruppe zuschlagen. Leer ohne
* aktive Gruppe oder ohne neue Elemente.
*/
export function activeGroupOps(before: Project, ops: readonly CoreOp[], groupPath: string[]): CoreOp[] {
if (groupPath.length === 0) return [];
+2 -1
View File
@@ -3,6 +3,7 @@
import { describe, it, expect, beforeEach } from "vitest";
import { getState, setState } from "./appStore";
import { emptyProject } from "../model/sampleProject";
import { setField } from "../core";
beforeEach(() => {
setState({ project: emptyProject, undoDepth: 0, redoDepth: 0, canUndo: false, canRedo: false });
@@ -11,7 +12,7 @@ beforeEach(() => {
describe("Undo/Redo über den Anfang hinaus", () => {
it("drei Schritte, mehrmals ganz zurück und vor", () => {
for (const name of ["A", "B", "C"]) getState().setProject((p) => ({ ...p, name }));
for (const name of ["A", "B", "C"]) getState().applyChange([setField("name", name)]);
expect(getState().project.name).toBe("C");
for (let round = 0; round < 3; round++) {
for (let k = 0; k < 6; k++) getState().undo();
+44 -42
View File
@@ -8,12 +8,13 @@
// laufen. Die Slice tippt daher nur ihre eigenen Felder; `get()` liefert
// RootState (siehe appStore.ts), wir greifen punktuell auf View-Felder zu.
import { applyOps, diffToOps } from "../core/ops";
import { applyOps } from "../core/ops";
import type { CoreOp } from "../core/ops";
import type { ProjectMutation } from "../core";
import type { LoadFileResult } from "../core/document";
import {
addItems,
fieldOps,
isOpsMutation,
patchItem,
patchItems,
removeItems,
@@ -75,21 +76,32 @@ export interface ProjectSlice {
// ── Projekt direkt setzen (für Werkzeuge/Transformationen aus App) ────────
/**
* Ersetzt das Projekt (Teil-/Updater wie React-setState). `coalesceKey`:
* NUR für bekannte Hochfrequenz-Aktionen (Griff-Ziehen, Inline-Text-Tippen)
* — verschmilzt aufeinanderfolgende Aufrufe mit demselben Key innerhalb
* `COALESCE_WINDOW_MS` zu EINEM Undo-Schritt, s. Kommentar bei der
* Implementierung unten.
* Änderung als Projekt → Projekt-Funktion MIT mitgeführten Ops (`opsMutation`, Schnittstellen wie
* `CommandResult.commit`); der Kern bekommt die Ops ([K4] S3 — keine Projekt-Differenz mehr).
* `coalesceKey`: NUR für bekannte Hochfrequenz-Aktionen (Griff-Ziehen, Inline-Text-Tippen) —
* gleicher Key im Zeitfenster = EIN Undo-Schritt. Ein anderes Projekt als Ganzes:
* {@link loadProject}/{@link openProjectFile}.
*/
setProject: (next: Project | ((p: Project) => Project), coalesceKey?: string) => void;
setProject: (next: ProjectMutation, coalesceKey?: string) => void;
/**
* Änderung direkt als Ops ([K4] S3): `ops` oder ein Op-Bauer auf dem aktuellen Projekt
* (`core/opsBuild.ts`). Geht ohne `diffToOps` an den Kern (Prüfung, Verlauf); sonst wie
* (`core/opsBuild.ts`). Geht direkt an den Kern (Prüfung, Verlauf); sonst wie
* {@link setProject} (gleicher `coalesceKey` im Zeitfenster = ein Undo-Schritt).
*/
applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[]), coalesceKey?: string) => void;
/** Die zuletzt angewendeten Ops (JSON-serialisierbar), jüngste zuletzt. */
recentOps: () => CoreOp[][];
/**
* Ein anderes Projekt übernehmen (Neu, Musterhaus; [K4] S4): lädt es als Ganzes ins Kern-Dokument
* und leert den Verlauf (Rückgängig führt nicht ins vorherige Projekt).
*/
loadProject: (next: Project) => void;
/**
* Projektdatei (Text) öffnen (Öffnen, Vorlage, Wiederherstellen): der Kern liest, migriert, prüft
* und lädt sie direkt (`ProjectDocument.loadFile`), der Verlauf wird geleert. Bei Fehler bleibt
* das Projekt unverändert.
*/
openProjectFile: (text: string) => LoadFileResult;
// ── Zeichnungsebenen (Levels/Geschosse) ──────────────────────────────────
toggleLevelVisible: (id: string) => void;
@@ -485,32 +497,12 @@ export function createProjectSlice(
return { project: res.project, ...historyPatch(doc) };
};
// Bequemer immutabler Projekt-Updater (wie setProject in App). Zweiter,
// optionaler Parameter `coalesceKey`: NUR von den paar bekannten
// Hochfrequenz-Aktionen (Grip-Drag & Co., s. u.) gesetzt — alle anderen
// Aktionen rufen ohne Key auf und pushen damit IMMER diskret (kein
// Koaleszieren zwischen unterschiedlichen Aktionen möglich, auch nicht bei
// zufällig identischem Timing in Tests).
// [K4] S3: Projekt → Projekt-Funktionen gehen über `diffToOps` (Adapter für die Aktionen, die noch
// nicht umgestellt sind); Funktionen aus `opsMutation` tragen ihre Ops mit und sparen die Differenz.
const setProject = (
next: Project | ((p: Project) => Project),
coalesceKey?: string,
) =>
set((s) => {
if (isOpsMutation(next)) return commitOps(s, next.toOps(s.project), coalesceKey);
const wanted =
typeof next === "function" ? (next as (p: Project) => Project)(s.project) : next;
// No-Op-Schutz: echte Immutable-Updates liefern bei tatsächlicher
// Änderung immer eine NEUE Referenz — bleibt sie gleich, gab es keine
// Änderung, also kein History-Eintrag (und `set` selbst benachrichtigt
// dann ebenfalls nicht, da der Patch leer ist).
if (wanted === s.project) return {};
// Das Projekt ändert sich NUR über Ops (core/ops.ts): die gewünschte Änderung wird in
// eine Op-Folge übersetzt; der Kern prüft (NaN, doppelte ids), wendet an und zeichnet den
// Undo-Schritt auf.
return commitOps(s, diffToOps(s.project, wanted), coalesceKey);
});
// Änderung mit mitgeführten Ops (`opsMutation`). Zweiter, optionaler Parameter `coalesceKey`: NUR
// von den paar bekannten Hochfrequenz-Aktionen (Grip-Drag & Co.) gesetzt — alle anderen Aktionen
// rufen ohne Key auf und pushen damit IMMER diskret. Das Projekt ändert sich NUR über Ops: der Kern
// prüft (NaN, doppelte ids), wendet an und zeichnet den Undo-Schritt auf ([K4] S3).
const setProject = (next: ProjectMutation, coalesceKey?: string) =>
set((s) => commitOps(s, next.toOps(s.project), coalesceKey));
// Änderung direkt als Ops (ohne Differenz), s. `ProjectSlice.applyChange`.
const applyChange = (
@@ -531,6 +523,19 @@ export function createProjectSlice(
applyChange,
recentOps: () => opLog.slice(),
loadProject: (next) => {
const doc = storeDocument(get().project);
doc.load(next);
set({ project: next, ...historyPatch(doc) });
},
openProjectFile: (text) => {
const doc = storeDocument(get().project);
const r = doc.loadFile(text);
if (r.ok) set({ project: r.project, ...historyPatch(doc) });
return r;
},
// ── Zeichnungsebenen ───────────────────────────────────────────────────
toggleLevelVisible: (id) =>
applyChange((p) => patchItem(p, "drawingLevels", id, (z) => ({ ...z, visible: !z.visible }))),
@@ -1894,18 +1899,16 @@ export function drawingVertices(
* Bild-/PDF-Import). Direkt selektiert zurückgegeben, damit Griffe/Objekt-Info
* sofort zum Verschieben/Skalieren bereitstehen.
*/
export function addImageDrawing2d(
project: Project,
export function imageDrawing2d(
levelId: string,
categoryCode: string,
src: string,
at: Vec2,
widthM: number,
heightM: number,
): { project: Project; id: string } {
const id = uniqueId("dr2d");
const d: Drawing2D = {
id,
): Drawing2D {
return {
id: uniqueId("dr2d"),
type: "drawing2d",
levelId,
categoryCode,
@@ -1916,7 +1919,6 @@ export function addImageDrawing2d(
src,
},
};
return { project: { ...project, drawings2d: [...project.drawings2d, d] }, id };
}
/**
+8 -4
View File
@@ -23,9 +23,13 @@ const DB_VERSION = 1;
interface ProjectRecord {
name: string;
savedAt: number;
project: Project;
/** Projekt als Objekt oder als Datei-Text (Autosave, `serializeProject`). */
project: StoredProject;
}
/** Gespeicherter Inhalt: Projekt-Objekt oder Datei-Text. */
export type StoredProject = Project | string;
/** `true`, sobald die Fehlmeldung „IndexedDB nicht verfügbar" geloggt wurde (nur einmal). */
let warnedUnavailable = false;
@@ -88,7 +92,7 @@ function openDb(): Promise<IDBDatabase> {
* Speichert ein Projekt unter `name` (überschreibt einen vorhandenen
* Datensatz gleichen Namens). Ohne IndexedDB: no-op (wirft nicht).
*/
export async function saveProject(name: string, project: Project): Promise<void> {
export async function saveProject(name: string, project: StoredProject): Promise<void> {
if (!name) return;
if (!isAvailable()) {
warnUnavailableOnce();
@@ -114,7 +118,7 @@ export async function saveProject(name: string, project: Project): Promise<void>
* Lädt ein Projekt nach Namen. Liefert `null`, wenn es nicht existiert, die
* Umgebung IndexedDB nicht unterstützt oder der Zugriff fehlschlägt.
*/
export async function loadProject(name: string): Promise<Project | null> {
export async function loadProject(name: string): Promise<StoredProject | null> {
if (!name) return null;
if (!isAvailable()) {
warnUnavailableOnce();
@@ -135,7 +139,7 @@ export async function loadProject(name: string): Promise<Project | null> {
}
/** Wie {@link loadProject}, mit Speicherzeitpunkt (ms seit Epoche). */
export async function loadProjectRecord(name: string): Promise<{ project: Project; savedAt: number } | null> {
export async function loadProjectRecord(name: string): Promise<{ project: StoredProject; savedAt: number } | null> {
if (!name || !isAvailable()) return null;
try {
const db = await openDb();
+1 -1
View File
@@ -14,7 +14,7 @@ beforeEach(() => {
components: sampleProject.components.map((c, i) => (i === 0 ? { ...c, colorPenId: "p1" } : c)),
walls: sampleProject.walls.map((w, i) => (i === 0 ? { ...w, colorPenId: "p1" } : w)),
};
st().setProject(p);
st().loadProject(p);
st().clearHistory();
});
+51 -8
View File
@@ -1,18 +1,20 @@
// setProject läuft über Ops (core/ops.ts): das Ergebnis muss dem gewünschten Projekt gleichen,
// ungültige Änderungen werden zurückgerollt, Ops werden protokolliert und sind JSON-fähig.
// setProject läuft über Ops (core/ops.ts, `opsMutation`): das Ergebnis muss dem gewünschten Projekt
// gleichen, ungültige Änderungen werden zurückgerollt, Ops werden protokolliert und sind JSON-fähig.
// Laden ([K4] S4): `loadProject`/`openProjectFile` ersetzen das Projekt im Kern und leeren den Verlauf.
import { describe, expect, it } from "vitest";
import { getState } from "./appStore";
import { sampleProject } from "../model/sampleProject";
import { emptyProject, sampleProject } from "../model/sampleProject";
import { addItems, opsMutation, patchItem, serializeProject } from "../core";
const st = () => getState();
describe("setProject über CoreOps", () => {
it("Änderung kommt unverändert an, Op wird protokolliert (JSON-fähig), Undo stellt zurück", () => {
st().setProject(structuredClone(sampleProject));
st().loadProject(structuredClone(sampleProject));
const before = st().project;
const w = before.walls[0];
const wanted = { ...before, walls: [{ ...w, height: (w.height ?? 2.6) + 1 }, ...before.walls.slice(1)] };
st().setProject(wanted);
st().setProject(opsMutation((p) => patchItem(p, "walls", w.id, { height: (w.height ?? 2.6) + 1 })));
expect(st().project).toEqual(wanted);
const ops = st().recentOps();
expect(ops.length).toBeGreaterThan(0);
@@ -26,15 +28,56 @@ describe("setProject über CoreOps", () => {
it("NaN-Änderung wird verworfen, Projekt bleibt, Undo-Stapel unverändert", () => {
const before = st().project;
const depth = st().undoDepth;
const w = before.walls[0];
st().setProject({ ...before, walls: [{ ...w, height: NaN }, ...before.walls.slice(1)] });
st().setProject(opsMutation((p) => patchItem(p, "walls", p.walls[0].id, { height: NaN })));
expect(st().project).toBe(before);
expect(st().undoDepth).toBe(depth);
});
it("doppelte ids beim Einfügen werden verworfen", () => {
const before = st().project;
st().setProject({ ...before, walls: [...before.walls, { ...before.walls[0] }] });
st().setProject(opsMutation((p) => addItems("walls", [{ ...p.walls[0] }])));
expect(st().project).toBe(before);
});
});
describe("Projekt laden ([K4] S4)", () => {
it("loadProject: Projekt als Ganzes, Verlauf leer, Leseansicht = übergebenes Objekt", () => {
st().loadProject(structuredClone(sampleProject));
st().setProject(opsMutation((p) => patchItem(p, "walls", p.walls[0].id, { height: 9 })));
expect(st().canUndo).toBe(true);
const next = structuredClone(emptyProject);
st().loadProject(next);
expect(st().project).toBe(next);
expect(st().undoDepth).toBe(0);
st().undo();
expect(st().project).toBe(next);
// Kern-Dokument = Leseansicht (Speichern aus dem Kern).
expect(JSON.parse(serializeProject(st().project))).toEqual({ ...next, formatVersion: 2 });
});
it("openProjectFile: Kern liest, migriert und lädt direkt; Verlauf leer; kaputte Datei ändert nichts", () => {
st().loadProject(structuredClone(sampleProject));
st().setProject(opsMutation((p) => patchItem(p, "walls", p.walls[0].id, { height: 9 })));
const before = st().project;
const bad = st().openProjectFile("{kaputt");
expect(bad.ok).toBe(false);
expect(st().project).toBe(before);
expect(st().undoDepth).toBe(1);
const doors = [{ id: "TX", hostWallId: sampleProject.walls[0].id, position: 0.5, width: 0.9, height: 2.1 }];
const old = { ...structuredClone(sampleProject), formatVersion: 1, doors };
const r = st().openProjectFile(JSON.stringify(old));
expect(r.ok && r.migratedFrom).toBe(1);
expect(st().undoDepth).toBe(0);
expect(st().redoDepth).toBe(0);
expect(st().project.formatVersion).toBe(2);
expect(st().project.openings?.some((o) => o.id === "TX" && o.kind === "door")).toBe(true);
expect("doors" in st().project).toBe(false);
// Danach normal weiterarbeiten: ein Schritt, Undo zurück auf den geladenen Stand.
const loaded = st().project;
st().setProject(opsMutation((p) => patchItem(p, "walls", p.walls[0].id, { height: 7 })));
st().undo();
expect(st().project).toEqual(loaded);
expect(serializeProject(st().project)).toBe(JSON.stringify({ formatVersion: 2, ...loaded }, null, 2));
});
});
+11 -13
View File
@@ -9,12 +9,14 @@
import type { DragEvent } from "react";
import { useRef } from "react";
import { addImageDrawing2d } from "./projectSlice";
import { imageDrawing2d } from "./projectSlice";
import { addItems } from "../core";
import type { CoreOp } from "../core/ops";
import type { NotifyKind } from "./notifySlice";
import { defaultImageSizeM, readImageFile } from "../io/imageAsset";
import { rasterizePdfPages } from "../io/pdfImport";
import { t } from "../i18n";
import type { Project, Vec2 } from "../model/types";
import type { Vec2 } from "../model/types";
/**
* „Bild einfügen" (Werkzeug „image"): kein Klick-Platzieren (Datei-Auswahl ist
@@ -23,10 +25,10 @@ import type { Project, Vec2 } from "../model/types";
* (Griffe/Objekt-Info stehen direkt zum Verschieben/Skalieren bereit).
*/
export function useImageImportHandling(opts: {
project: Project;
activeLevelId: string;
activeCategoryCode: string;
setProject: (next: Project | ((p: Project) => Project)) => void;
/** Änderung als Ops (Store `applyChange`): alle Bilder eines Einfügens = ein Undo-Schritt. */
applyChange: (ops: readonly CoreOp[]) => void;
notify: (message: string, kind?: NotifyKind) => void;
setSelectedDrawingId: (id: string | null) => void;
setSelectedWallIds: (ids: string[]) => void;
@@ -44,10 +46,9 @@ export function useImageImportHandling(opts: {
onImageOrPdfFileChosen: (file: File) => void;
} {
const {
project,
activeLevelId,
activeCategoryCode,
setProject,
applyChange,
notify,
setSelectedDrawingId,
setSelectedWallIds,
@@ -65,17 +66,14 @@ export function useImageImportHandling(opts: {
const insertImageDrawings = (
assets: { src: string; naturalWidth: number; naturalHeight: number }[],
) => {
let cur = project;
let lastId: string | null = null;
assets.forEach((a, i) => {
const drawings = assets.map((a, i) => {
const { widthM, heightM } = defaultImageSizeM(a.naturalWidth, a.naturalHeight);
const cascade = i * 0.3;
const at: Vec2 = { x: -widthM / 2 + cascade, y: -heightM / 2 - cascade };
const r = addImageDrawing2d(cur, activeLevelId, activeCategoryCode, a.src, at, widthM, heightM);
cur = r.project;
lastId = r.id;
return imageDrawing2d(activeLevelId, activeCategoryCode, a.src, at, widthM, heightM);
});
setProject(cur);
applyChange(addItems("drawings2d", drawings));
const lastId = drawings.length ? drawings[drawings.length - 1].id : null;
if (lastId) {
setSelectedDrawingId(lastId);
setSelectedWallIds([]);
+2 -2
View File
@@ -18,7 +18,7 @@ import type { CopyMode, TransformOp } from "../tools/transform";
import type { CommandEngine } from "../commands/engine";
import type { CommandLineHandle } from "../ui/CommandLine";
import type { Drawing2D, Project, Vec2 } from "../model/types";
import type { CoreOp } from "../core";
import type { CoreOp, ProjectMutation } from "../core";
import { differenceDrawings, intersectionDrawings, unionDrawings } from "../editors/booleanOps";
import type { BooleanResult } from "../editors/booleanOps";
import { groupSelection, mergeMembership, ungroup, EMPTY_MEMBERSHIP } from "./groupActions";
@@ -236,7 +236,7 @@ export function useActiveToolKeys(
toolStateRef: MutableRefObject<ToolState>,
setDraft: (draft: ToolDraft | null) => void,
setActiveTool: (id: ToolId) => void,
setProject: (next: Project | ((p: Project) => Project)) => void,
setProject: (next: ProjectMutation) => void,
): void {
useEffect(() => {
if (activeTool === "select") return;
+2 -2
View File
@@ -7,7 +7,7 @@
import { opsMutation, patchItem, removeItems } from "../core";
import type { Project, Vec2 } from "../model/types";
import type { CategoryDisplayResolver } from "../core";
import type { CategoryDisplayResolver, ProjectMutation } from "../core";
import type { DisplayResolver } from "../viewport/Viewport3D";
import type { PlanSelection, MarqueeSelection } from "../views/plan/PlanView";
import type { Pick3dHit } from "../viewport/Wasm3DViewport";
@@ -42,7 +42,7 @@ export function useMouseSelectionHandlers(opts: {
/** `coalesceKey`: s. `projectSlice.ts` `setProject` — von `commitTextEdit`
* genutzt, damit EIN Tipp-Vorgang EINEN Undo-Schritt erzeugt (wie beim
* Griff-Ziehen), statt bei jedem Tastendruck einen neuen zu pushen. */
setProject: (updater: (p: Project) => Project, coalesceKey?: string) => void;
setProject: (updater: ProjectMutation, coalesceKey?: string) => void;
activeLevelId: string;
visibleCodes: Set<string>;
categoryDisplay: CategoryDisplayResolver & DisplayResolver;
+2 -2
View File
@@ -9,7 +9,7 @@
import { applyFillMode } from "./fillMode";
import { addItems, fieldOps, opsMutation, patchItem, patchItems, removeItems, removeRoofHole, setFieldIfChanged, setRoofEdge } from "../core";
import type { CoreOp } from "../core";
import type { CoreOp, ProjectMutation } from "../core";
import { useMemo, type RefObject } from "react";
import type { DrawingLevel, Layout, Project } from "../model/types";
import { resolvePenColor } from "../model/penSets";
@@ -107,7 +107,7 @@ function captureCameraState(
export function usePanelHostBase(opts: {
project: Project;
setProject: (updater: (p: Project) => Project) => void;
setProject: (updater: ProjectMutation) => void;
/** Änderung direkt als Ops ([K4] S3), s. `ProjectSlice.applyChange`. */
applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[]), coalesceKey?: string) => void;
activeLevelId: string;
+55 -72
View File
@@ -8,7 +8,7 @@
import { getState, useStore } from "./appStore";
import type { NotifyKind } from "./notifySlice";
import { parseProjectFile, parseProjectObject, serializeProject } from "../io/projectFormat";
import { serializeProject } from "../io/projectFormat";
import { AUTOSAVE_INTERVAL_MS, clearAutosave, createAutosaveTracker, readAutosave, writeAutosave } from "./autosave";
import type { AutosaveRecovery } from "./autosave";
import { useEffect, useRef, useState } from "react";
@@ -44,6 +44,8 @@ import type { LockInfo } from "../native/projectFile";
import { addRecentProject, removeRecentProject } from "./recentProjects";
import { emptyProject, sampleProject } from "../model/sampleProject";
import { flattenCategories } from "../model/types";
import { addItems, fieldOps } from "../core";
import type { CoreOp } from "../core/ops";
import type { ContextObject, Drawing2D, Project, Vec2 } from "../model/types";
import type { PlanViewHandle } from "../views/plan/PlanView";
@@ -140,11 +142,12 @@ const errorText = (err: unknown): string => (err instanceof Error ? err.message
/**
* Liest Projekt-Text über den gemeinsamen Format-Parser (Version, Migration, Toleranz) und
* meldet Fehler sichtbar statt nur in der Konsole. `null` = nicht ladbar.
* Öffnet Projekt-Text im Kern (`openProjectFile`: Version, Migration, Toleranz; direkt ins
* Kern-Dokument, Verlauf leer) und meldet Fehler sichtbar statt nur in der Konsole. `null` = nicht
* ladbar (das bisherige Projekt bleibt).
*/
function readProjectOrReport(content: string, notify: (msg: string, kind?: NotifyKind) => void): Project | null {
const r = parseProjectFile(content);
function openProjectOrReport(content: string, notify: (msg: string, kind?: NotifyKind) => void): Project | null {
const r = getState().openProjectFile(content);
if (!r.ok) {
notify(`${t("project.open.failed")} ${r.error}`, "error");
return null;
@@ -155,7 +158,7 @@ function readProjectOrReport(content: string, notify: (msg: string, kind?: Notif
export function useProjectFileActions(
project: Project,
setProject: (next: Project | ((p: Project) => Project)) => void,
applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[])) => void,
setImportState: (next: ImportDialogState) => void,
setExportSaveFormat: (format: ExportSaveFormat | null) => void,
activeCategoryCode: string,
@@ -172,13 +175,9 @@ export function useProjectFileActions(
const projectFileInputRef = useRef<HTMLInputElement>(null);
// Meldungen als Toast (window.alert ist im Tauri-WKWebView wirkungslos).
const notify = useStore((s) => s.notify);
// Ein anderes Projekt übernehmen (Neu, Vorlage, Öffnen, Wiederherstellen): ersetzt das Projekt und
// leert den Undo-Verlauf — sonst führte Rückgängig über das Laden hinaus ins vorherige Projekt, und
// jede Änderung dort verwarf den Redo-Stapel.
const replaceProject = (next: Project) => {
setProject(next);
getState().clearHistory();
};
// Ein anderes Projekt übernehmen (Neu, Vorlage, Öffnen, Wiederherstellen) lädt es im Kern als Ganzes
// (`loadProject`/`openProjectFile`, [K4] S4) und leert den Undo-Verlauf — sonst führte Rückgängig über
// das Laden hinaus ins vorherige Projekt, und jede Änderung dort verwarf den Redo-Stapel.
// Verstecktes Datei-Input für „Neu aus Vorlage" (Datei wählen) — derselbe
// Browser-Fallback wie `projectFileInputRef`, nur mit `.obpt`-Filter.
const projectTemplateFileInputRef = useRef<HTMLInputElement>(null);
@@ -231,22 +230,20 @@ export function useProjectFileActions(
const id = window.setInterval(() => {
const p = projectRef.current;
if (!autosaveTracker.shouldWrite(p, lastSavedProjectRef.current)) return;
void writeAutosave(openedProjectPathRef.current, p);
void writeAutosave(openedProjectPathRef.current, serializeProject(p));
}, AUTOSAVE_INTERVAL_MS);
return () => window.clearInterval(id);
}, []);
const offerRecovery = (path: string | null) => {
void readAutosave(path).then((r) => {
if (r) setRecovery({ path, project: r.project, savedAt: r.savedAt });
if (r) setRecovery({ path, text: r.text, savedAt: r.savedAt });
});
};
// Start: Kopie eines nie gespeicherten Projekts aus der letzten Sitzung?
useEffect(() => offerRecovery(null), []);
const onRecoverRestore = () => {
if (!recovery) return;
const parsed = parseProjectObject(recovery.project);
if (parsed.ok) replaceProject(parsed.project); // bleibt „ungespeichert" bis zum Speichern
else notify(`${t("project.open.failed")} ${parsed.error}`, "error");
openProjectOrReport(recovery.text, notify); // bleibt „ungespeichert" bis zum Speichern
setRecovery(null);
};
const onRecoverDiscard = () => {
@@ -450,29 +447,23 @@ export function useProjectFileActions(
// `guardDiscard`: bei ungespeicherten Änderungen erst der Dialog, s. o.
const onNewProject = () => guardDiscard(() => {
releaseCurrentProjectLock();
replaceProject(emptyProject);
getState().loadProject(emptyProject);
lastSavedProjectRef.current = emptyProject;
});
// Übernimmt ein neues, noch UNGESPEICHERTES Projekt aus Vorlagen-Inhalt
// (Musterhaus ODER eine gewählte `.obpt`-Datei): grobe Form-Prüfung wie beim
// normalen Öffnen, aber bewusst OHNE Pfad/Lock zu setzen — die Vorlage
// bleibt unangetastet, das nächste „Speichern" fragt nach einem neuen Ort.
// Ersetzt ebenfalls das bisherige Projekt → über `guardDiscard`.
const applyTemplateContent = (content: string): boolean => {
try {
const parsed = readProjectOrReport(content, notify);
if (!parsed) return false;
guardDiscard(() => {
releaseCurrentProjectLock();
replaceProject(parsed);
lastSavedProjectRef.current = parsed;
});
return true;
} catch (err) {
console.error("Vorlage konnte nicht geladen werden:", err);
return false;
}
// (eine gewählte `.obpt`-Datei): Prüfung wie beim normalen Öffnen, aber
// bewusst OHNE Pfad/Lock zu setzen — die Vorlage bleibt unangetastet, das
// nächste „Speichern" fragt nach einem neuen Ort. Ersetzt ebenfalls das
// bisherige Projekt → über `guardDiscard` (der Kern lädt erst danach; eine
// kaputte Datei lässt das bisherige Projekt stehen).
const applyTemplateContent = (content: string): void => {
guardDiscard(() => {
const loaded = openProjectOrReport(content, notify);
if (!loaded) return;
releaseCurrentProjectLock();
lastSavedProjectRef.current = loaded;
});
};
// „Neu aus Vorlage: Musterhaus" — das eingebaute Demo-Haus (model/sampleProject.ts)
// als Start eines neuen Projekts. `structuredClone`, damit spätere Bearbeitung
@@ -481,7 +472,7 @@ export function useProjectFileActions(
const onNewProjectFromSample = () => guardDiscard(() => {
releaseCurrentProjectLock();
const next = structuredClone(sampleProject);
replaceProject(next);
getState().loadProject(next);
lastSavedProjectRef.current = next;
});
// „Neu aus Vorlage: Datei wählen…" — native `.obpt`-Dialog unter Tauri, sonst
@@ -521,24 +512,19 @@ export function useProjectFileActions(
// die Form, gibt einen evtl. vorher gehaltenen Lock frei und merkt sich Pfad
// + ob WIR den Schreib-Lock für die neue Datei halten.
const applyOpenedProjectFile = (path: string, content: string, lockOwned: boolean) => {
try {
const parsed = readProjectOrReport(content, notify);
if (!parsed) {
guardDiscard(() => {
const loaded = openProjectOrReport(content, notify);
if (!loaded) {
if (lockOwned) void releaseProjectLock(path);
return;
}
guardDiscard(() => {
releaseCurrentProjectLock();
replaceProject(parsed);
lastSavedProjectRef.current = parsed;
openedProjectPathRef.current = path;
projectLockOwnedRef.current = lockOwned;
addRecentProject(path, parsed.name || "modell");
offerRecovery(path);
});
} catch (err) {
console.error("Projekt-Import fehlgeschlagen:", err);
}
releaseCurrentProjectLock();
lastSavedProjectRef.current = loaded;
openedProjectPathRef.current = path;
projectLockOwnedRef.current = lockOwned;
addRecentProject(path, loaded.name || "modell");
offerRecovery(path);
});
};
// Öffnen unter Tauri: nativer Dialog (echter Pfad) → Lock versuchen. Klappt
// er → Projekt übernehmen. Schon gesperrt → Konflikt-Dialog (kein
@@ -652,19 +638,15 @@ export function useProjectFileActions(
const onProjectFileChosen = (file: File) => {
const r = new FileReader();
r.onload = () => {
try {
const parsed = readProjectOrReport(String(r.result ?? ""), notify);
if (!parsed) return;
// Browser-Pfad hat keinen echten Dateipfad → kein Lock für die neue
// Datei, aber ein evtl. vorher (unter Tauri) gehaltener Lock wird frei.
guardDiscard(() => {
releaseCurrentProjectLock();
replaceProject(parsed);
lastSavedProjectRef.current = parsed;
});
} catch (err) {
console.error("Projekt-Import fehlgeschlagen:", err);
}
const content = String(r.result ?? "");
// Browser-Pfad hat keinen echten Dateipfad → kein Lock für die neue
// Datei, aber ein evtl. vorher (unter Tauri) gehaltener Lock wird frei.
guardDiscard(() => {
const loaded = openProjectOrReport(content, notify);
if (!loaded) return;
releaseCurrentProjectLock();
lastSavedProjectRef.current = loaded;
});
};
r.readAsText(file);
};
@@ -675,10 +657,15 @@ export function useProjectFileActions(
// Bestätigte Import-Entscheidung ausführen: ggf. neue Zeichnung anlegen, die
// 2D-Konturen als Drawing2D anhängen, optional die Meshes als Kontext
// übernehmen. Reihenfolge: erst Ebene (echte ID), dann Drawings/Kontext.
// Alles als Ops in EINER Gruppe ([K4] S3): ein Import = ein Undo-Schritt.
const runImport = (decision: ImportDecision) => {
// Hinweis bleibt, bis PlanView den neuen Plan gezeichnet hat (endBusyAfterPaint):
// der Aufbau nach dem Einhängen blockiert noch einmal mehrere Sekunden.
beginBusy(t("busy.import"));
getState().groupChanges(() => runImportSteps(decision));
setImportState(null);
};
const runImportSteps = (decision: ImportDecision) => {
const levelId =
decision.target.kind === "new"
? addDrawingLevel(decision.target.name)
@@ -699,17 +686,14 @@ export function useProjectFileActions(
codeByLayer = plan.codeByLayer;
if (plan.parent) {
const parent = plan.parent;
setProject((p) => ({ ...p, layers: [...p.layers, parent] }));
applyChange((p) => fieldOps(p, "layers", [...p.layers, parent]));
}
}
// PDF-Strichmuster ([76]): passenden Linienstil nehmen oder Strichmuster-Stil anlegen (vor den Zeichnungen).
const dashPlan = planDashLineStyles(decision.parsed.layerDashes, project.lineStyles);
if (dashPlan.created.length) {
const created = dashPlan.created;
setProject((p) => ({
...p,
lineStyles: [...p.lineStyles, ...created.filter((c) => !p.lineStyles.some((l) => l.id === c.id))],
}));
applyChange((p) => addItems("lineStyles", created.filter((c) => !p.lineStyles.some((l) => l.id === c.id))));
}
let drawings = buildDrawings(
decision,
@@ -737,7 +721,6 @@ export function useProjectFileActions(
}
// Auf die Ziel-Ebene wechseln, damit die importierte Geometrie sichtbar ist.
setActiveLevelId(levelId);
setImportState(null);
};
return {
+3 -2
View File
@@ -6,6 +6,7 @@
// bleibt abgeleitet. Bezeichner englisch, UI-Text via t().
import type { DrawingLevel, Project, Vec2 } from "../model/types";
import type { ProjectMutation } from "../core";
/** Werkzeug-Identität. */
export type ToolId =
@@ -274,8 +275,8 @@ export interface ToolDraft {
export interface ToolResult {
/** Neuer Vorschau-Zustand; null = nichts zu zeigen. */
draft: ToolDraft | null;
/** Bei Abschluss: Mutation, die App über setProject anwendet. */
commit?: (p: Project) => Project;
/** Bei Abschluss: Änderung mit mitgeführten Ops (`opsMutation`), die App über setProject anwendet. */
commit?: ProjectMutation;
/** true → Werkzeug ist fertig und kehrt in seinen Ruhezustand zurück. */
done?: boolean;
}