Merge [K4][7][8] Ops, Pruefung und Undo/Redo im Rust-Kern; Fix Redo-Verlust (Ausschnitt-Leiste schrieb automatisch ins Projekt), Neu/Oeffnen leeren den Verlauf, Browser-Oeffnen liest Text
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
35 files changed
+1701
-432
No files matched your search
@@ -0,0 +1,23 @@
|
||||
// Maintainer-Fund 28.10.: mehrmals ganz zurück und wieder vor — der Redo-Stapel darf dabei nicht verloren gehen,
|
||||
// auch nicht mit überzähligen Undo/Redo-Aufrufen an den Enden.
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { getState, setState } from "./appStore";
|
||||
import { emptyProject } from "../model/sampleProject";
|
||||
|
||||
beforeEach(() => {
|
||||
setState({ project: emptyProject, undoDepth: 0, redoDepth: 0, canUndo: false, canRedo: false });
|
||||
getState().clearHistory();
|
||||
});
|
||||
|
||||
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 }));
|
||||
expect(getState().project.name).toBe("C");
|
||||
for (let round = 0; round < 3; round++) {
|
||||
for (let k = 0; k < 6; k++) getState().undo();
|
||||
expect(getState().project.name).toBe(emptyProject.name);
|
||||
for (let k = 0; k < 6; k++) getState().redo();
|
||||
expect(getState().project.name).toBe("C");
|
||||
}
|
||||
});
|
||||
});
|
||||
+13
-12
@@ -23,11 +23,12 @@ import { HISTORY_LIMIT } from "./historySlice";
|
||||
beforeEach(() => {
|
||||
setState({
|
||||
project: sampleProject,
|
||||
undoStack: [],
|
||||
redoStack: [],
|
||||
undoDepth: 0,
|
||||
redoDepth: 0,
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
});
|
||||
getState().clearHistory();
|
||||
});
|
||||
|
||||
describe("Undo/Redo", () => {
|
||||
@@ -59,7 +60,7 @@ describe("Undo/Redo", () => {
|
||||
});
|
||||
|
||||
it("undo bei leerem Stack ist ein No-Op (kein Crash)", () => {
|
||||
expect(getState().undoStack.length).toBe(0);
|
||||
expect(getState().undoDepth).toBe(0);
|
||||
const before = getState().project;
|
||||
|
||||
expect(() => getState().undo()).not.toThrow();
|
||||
@@ -69,7 +70,7 @@ describe("Undo/Redo", () => {
|
||||
});
|
||||
|
||||
it("redo bei leerem Stack ist ein No-Op (kein Crash)", () => {
|
||||
expect(getState().redoStack.length).toBe(0);
|
||||
expect(getState().redoDepth).toBe(0);
|
||||
const before = getState().project;
|
||||
|
||||
expect(() => getState().redo()).not.toThrow();
|
||||
@@ -81,27 +82,27 @@ describe("Undo/Redo", () => {
|
||||
it("eine neue Aktion nach undo() verwirft den Redo-Stack", () => {
|
||||
getState().toggleLevelVisible("eg");
|
||||
getState().undo();
|
||||
expect(getState().redoStack.length).toBe(1);
|
||||
expect(getState().redoDepth).toBe(1);
|
||||
|
||||
getState().toggleLevelVisible("og");
|
||||
|
||||
expect(getState().redoStack.length).toBe(0);
|
||||
expect(getState().redoDepth).toBe(0);
|
||||
expect(getState().canRedo).toBe(false);
|
||||
// Die neue Aktion selbst bleibt natürlich undo-fähig.
|
||||
expect(getState().canUndo).toBe(true);
|
||||
});
|
||||
|
||||
it("die allererste Änderung bleibt exakt EIN Undo-Schritt (kein Start-Eintrag)", () => {
|
||||
expect(getState().undoStack.length).toBe(0);
|
||||
expect(getState().undoDepth).toBe(0);
|
||||
getState().toggleLevelVisible("eg");
|
||||
expect(getState().undoStack.length).toBe(1);
|
||||
expect(getState().undoDepth).toBe(1);
|
||||
});
|
||||
|
||||
it("history-Stack verwirft die ältesten Einträge über HISTORY_LIMIT hinaus", () => {
|
||||
for (let i = 0; i < HISTORY_LIMIT + 10; i++) {
|
||||
getState().toggleLevelVisible("eg");
|
||||
}
|
||||
expect(getState().undoStack.length).toBe(HISTORY_LIMIT);
|
||||
expect(getState().undoDepth).toBe(HISTORY_LIMIT);
|
||||
});
|
||||
|
||||
it("ein Grip-Drag (viele setProject-Aufrufe in Serie) koalesziert zu EINEM Undo-Schritt", () => {
|
||||
@@ -118,19 +119,19 @@ describe("Undo/Redo", () => {
|
||||
const w1After = getState().project.walls.find((w) => w.id === "W1");
|
||||
expect(w1After?.start).toEqual({ x: 2, y: 0 });
|
||||
// Trotz 20 Aufrufen: genau EIN Undo-Schritt.
|
||||
expect(getState().undoStack.length).toBe(1);
|
||||
expect(getState().undoDepth).toBe(1);
|
||||
|
||||
getState().undo();
|
||||
|
||||
const w1Restored = getState().project.walls.find((w) => w.id === "W1");
|
||||
expect(w1Restored?.start).toEqual({ x: 0, y: 0 });
|
||||
expect(getState().undoStack.length).toBe(0);
|
||||
expect(getState().undoDepth).toBe(0);
|
||||
});
|
||||
|
||||
it("zwei Drags auf UNTERSCHIEDLICHE Griffe erzeugen ZWEI Undo-Schritte", () => {
|
||||
getState().moveGripOf(null, "W1", 0, { x: 1, y: 0 });
|
||||
getState().moveGripOf(null, "W1", 1, { x: 6, y: 0 });
|
||||
|
||||
expect(getState().undoStack.length).toBe(2);
|
||||
expect(getState().undoDepth).toBe(2);
|
||||
});
|
||||
});
|
||||
+68
-80
@@ -1,107 +1,95 @@
|
||||
// History-Slice: Undo/Redo für das Projekt-Modell. Reine Snapshot-Historie —
|
||||
// dank immutabler Updates in `projectSlice.ts` (jede echte Änderung liefert
|
||||
// eine NEUE `Project`-Referenz mit structural sharing) ist ein Stack aus
|
||||
// `Project`-Werten billig (kein Deep-Clone nötig, unveränderte Teilbäume
|
||||
// werden zwischen den Snapshots geteilt).
|
||||
// History-Slice: Undo/Redo für das Projekt-Modell ([8], [K4] S3). Der Verlauf liegt im Rust-Kern
|
||||
// (`src-tauri/core/src/ops.rs`, `document.rs`): je Schritt die Vorwärts- und die inversen Ops —
|
||||
// keine Projekt-Schnappschüsse mehr. Gleicher `coalesceKey` im Zeitfenster = ein Schritt (Drag,
|
||||
// Regler), Gruppen (`groupChanges`) fassen mehrere Änderungen zusammen; begrenzt auf
|
||||
// {@link HISTORY_LIMIT} Schritte und {@link HISTORY_MAX_BYTES}.
|
||||
//
|
||||
// Die eigentliche Buchführung (WANN wird gepusht, Koaleszenz von Drag-Serien)
|
||||
// lebt bewusst in `projectSlice.ts` bei `setProject` selbst — das ist die
|
||||
// EINZIGE Stelle, durch die jede Projekt-Mutation läuft. Dieses Modul liefert
|
||||
// nur den reaktiven Zustand (Stacks + Flags) und die `undo`/`redo`-Aktionen,
|
||||
// die DIREKT über `set()` schreiben (NICHT über `setProject`), damit sie
|
||||
// keinen neuen History-Eintrag erzeugen (sonst Endlosschleife/kaputte
|
||||
// Historie). Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
// `setProject` (projectSlice.ts) ist die EINZIGE Stelle, durch die jede Projekt-Mutation läuft: es
|
||||
// übergibt die Ops dem Kern-Dokument des Stores ({@link storeDocument}). `undo`/`redo` holen die
|
||||
// Ops vom Kern und führen die TS-Leseansicht damit nach (direkt über `set()`, kein neuer Schritt).
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { ProjectDocument, setPrimaryDocument } from "../core/document";
|
||||
import type { StoreApi } from "./store";
|
||||
|
||||
/** Obergrenze der Undo-Tiefe — ältere Einträge fallen hinten raus (Speicher/Performance). */
|
||||
/** Obergrenze der Undo-Tiefe — ältere Schritte fallen hinten raus. */
|
||||
export const HISTORY_LIMIT = 100;
|
||||
/** Ungefähre Speichergrenze des Verlaufs (Bytes) — ältere Schritte fallen hinten raus. */
|
||||
export const HISTORY_MAX_BYTES = 256 * 1024 * 1024;
|
||||
|
||||
/** Felder, die diese Slice in den RootState beisteuert. */
|
||||
export interface HistorySlice {
|
||||
/** Ältere Projekt-Stände (oben = zuletzt verlassener Stand, für `undo`). */
|
||||
undoStack: Project[];
|
||||
/** Durch `undo` verlassene Stände (oben = zuletzt verlassener, für `redo`). */
|
||||
redoStack: Project[];
|
||||
/** Abgeleitet aus `undoStack.length > 0` — bequem für UI-Bindings (Buttons/Menüs). */
|
||||
/** Anzahl Undo-Schritte im Kern. */
|
||||
undoDepth: number;
|
||||
/** Anzahl Redo-Schritte im Kern. */
|
||||
redoDepth: number;
|
||||
/** Abgeleitet aus `undoDepth > 0` — bequem für UI-Bindings (Buttons/Menüs). */
|
||||
canUndo: boolean;
|
||||
/** Abgeleitet aus `redoStack.length > 0`. */
|
||||
/** Abgeleitet aus `redoDepth > 0`. */
|
||||
canRedo: boolean;
|
||||
/** Einen Schritt zurück. No-Op (kein Crash), wenn der Undo-Stack leer ist. */
|
||||
/** Einen Schritt zurück. No-Op (kein Crash), wenn nichts rückgängig zu machen ist. */
|
||||
undo: () => void;
|
||||
/** Einen Schritt vor. No-Op (kein Crash), wenn der Redo-Stack leer ist. */
|
||||
/** Einen Schritt vor. No-Op (kein Crash), wenn nichts wiederherzustellen ist. */
|
||||
redo: () => void;
|
||||
/** Verlauf leeren. */
|
||||
clearHistory: () => void;
|
||||
/** Alle Projekt-Änderungen in `fn` werden EIN Undo-Schritt. */
|
||||
groupChanges: (fn: () => void) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reines Patch-Berechnen für einen History-Push — von `setProject` (in
|
||||
* `projectSlice.ts`) bei jeder ECHTEN Projekt-Änderung aufgerufen (kein
|
||||
* Store-Zugriff nötig, daher hier als freie Funktion statt Store-Aktion: so
|
||||
* lässt sich der Push in EINEM gemeinsamen `set()`-Aufruf mit der eigentlichen
|
||||
* `project`-Änderung zusammenfassen, statt einen zweiten, verschachtelten
|
||||
* `set()`-Aufruf auszulösen).
|
||||
*
|
||||
* Eine neue Aktion verwirft immer die Redo-Historie (Standardverhalten jedes
|
||||
* Undo/Redo-Systems: sobald der Nutzer nach einem `undo()` etwas Neues tut,
|
||||
* ist der alte "vordere" Zweig weg).
|
||||
*/
|
||||
export function pushHistoryPatch(
|
||||
undoStack: Project[],
|
||||
prevProject: Project,
|
||||
): Pick<HistorySlice, "undoStack" | "redoStack" | "canUndo" | "canRedo"> {
|
||||
const next = [...undoStack, prevProject];
|
||||
if (next.length > HISTORY_LIMIT) next.shift();
|
||||
return { undoStack: next, redoStack: [], canUndo: true, canRedo: false };
|
||||
}
|
||||
let doc: ProjectDocument | null = null;
|
||||
|
||||
/**
|
||||
* Baut `undo`/`redo` + initialen Zustand. `onAfterJump` wird nach jedem
|
||||
* Sprung aufgerufen (projectSlice.ts nutzt das, um die Koaleszenz-Buchführung
|
||||
* für Drag-Serien zurückzusetzen — sonst könnte eine neue Aktion direkt nach
|
||||
* einem `undo()` fälschlich mit der VORHERIGEN Serie verschmolzen und dadurch
|
||||
* NIE auf dem Undo-Stack landen).
|
||||
* Das Kern-Dokument des Stores (mit Verlauf), beim ersten Gebrauch aus `project` geöffnet. Es ist
|
||||
* zugleich das Dokument, über das die Abfragen auf dem aktuellen Projekt laufen (`documentFor`).
|
||||
*/
|
||||
export function createHistorySlice(
|
||||
api: StoreApi<HistorySlice & { project: Project }>,
|
||||
onAfterJump?: () => void,
|
||||
): HistorySlice {
|
||||
export function storeDocument(project: Project): ProjectDocument {
|
||||
if (!doc) {
|
||||
doc = new ProjectDocument(project);
|
||||
doc.setHistoryLimits(HISTORY_LIMIT, HISTORY_MAX_BYTES);
|
||||
setPrimaryDocument(doc);
|
||||
}
|
||||
return doc;
|
||||
}
|
||||
|
||||
/** Verlaufs-Felder für den Store aus dem Stand im Kern. */
|
||||
export function historyPatch(d: ProjectDocument): Pick<HistorySlice, "undoDepth" | "redoDepth" | "canUndo" | "canRedo"> {
|
||||
const h = d.historyState();
|
||||
return { undoDepth: h.undo, redoDepth: h.redo, canUndo: h.undo > 0, canRedo: h.redo > 0 };
|
||||
}
|
||||
|
||||
/** Baut `undo`/`redo` + initialen Zustand. */
|
||||
export function createHistorySlice(api: StoreApi<HistorySlice & { project: Project }>): HistorySlice {
|
||||
const { set, get } = api;
|
||||
|
||||
const jump = (dir: "undo" | "redo") => {
|
||||
const { project } = get();
|
||||
const d = storeDocument(project);
|
||||
const next = dir === "undo" ? d.undo(project) : d.redo(project);
|
||||
set(next ? { project: next, ...historyPatch(d) } : historyPatch(d));
|
||||
};
|
||||
|
||||
return {
|
||||
undoStack: [],
|
||||
redoStack: [],
|
||||
undoDepth: 0,
|
||||
redoDepth: 0,
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
|
||||
undo: () => {
|
||||
const { undoStack, redoStack, project } = get();
|
||||
if (undoStack.length === 0) return;
|
||||
const prev = undoStack[undoStack.length - 1];
|
||||
const rest = undoStack.slice(0, -1);
|
||||
set({
|
||||
project: prev,
|
||||
undoStack: rest,
|
||||
redoStack: [...redoStack, project],
|
||||
canUndo: rest.length > 0,
|
||||
canRedo: true,
|
||||
});
|
||||
onAfterJump?.();
|
||||
undo: () => jump("undo"),
|
||||
redo: () => jump("redo"),
|
||||
clearHistory: () => {
|
||||
const d = storeDocument(get().project);
|
||||
d.clearHistory();
|
||||
set(historyPatch(d));
|
||||
},
|
||||
|
||||
redo: () => {
|
||||
const { undoStack, redoStack, project } = get();
|
||||
if (redoStack.length === 0) return;
|
||||
const next = redoStack[redoStack.length - 1];
|
||||
const rest = redoStack.slice(0, -1);
|
||||
set({
|
||||
project: next,
|
||||
undoStack: [...undoStack, project],
|
||||
redoStack: rest,
|
||||
canUndo: true,
|
||||
canRedo: rest.length > 0,
|
||||
});
|
||||
onAfterJump?.();
|
||||
groupChanges: (fn) => {
|
||||
const d = storeDocument(get().project);
|
||||
d.beginGroup();
|
||||
try {
|
||||
fn();
|
||||
} finally {
|
||||
d.endGroup();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -16,8 +16,8 @@ beforeEach(() => {
|
||||
vi.spyOn(Date, "now").mockImplementation(() => clock++);
|
||||
setState({
|
||||
project: { ...sampleProject, components: sampleProject.components.slice(0, 1), customPalettes: [] },
|
||||
undoStack: [],
|
||||
redoStack: [],
|
||||
undoDepth: 0,
|
||||
redoDepth: 0,
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
});
|
||||
|
||||
@@ -32,8 +32,8 @@ beforeEach(() => {
|
||||
...sampleProject,
|
||||
drawings2d: [circleDrawing, arcDrawing],
|
||||
},
|
||||
undoStack: [],
|
||||
redoStack: [],
|
||||
undoDepth: 0,
|
||||
redoDepth: 0,
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
});
|
||||
|
||||
@@ -38,8 +38,8 @@ const leaderTwoBends: Drawing2D = {
|
||||
beforeEach(() => {
|
||||
setState({
|
||||
project: { ...sampleProject, drawings2d: [leaderNoBends, leaderTwoBends] },
|
||||
undoStack: [],
|
||||
redoStack: [],
|
||||
undoDepth: 0,
|
||||
redoDepth: 0,
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
});
|
||||
|
||||
@@ -57,8 +57,8 @@ function makeRoom(over: Partial<Room> = {}): Room {
|
||||
beforeEach(() => {
|
||||
setState({
|
||||
project: { ...sampleProject, drawings2d: [pentagon], rooms: [makeRoom()] },
|
||||
undoStack: [],
|
||||
redoStack: [],
|
||||
undoDepth: 0,
|
||||
redoDepth: 0,
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
});
|
||||
|
||||
@@ -36,8 +36,8 @@ const lockedDrawing: Drawing2D = {
|
||||
beforeEach(() => {
|
||||
setState({
|
||||
project: { ...sampleProject, walls: [lockedWall], drawings2d: [lockedDrawing] },
|
||||
undoStack: [],
|
||||
redoStack: [],
|
||||
undoDepth: 0,
|
||||
redoDepth: 0,
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
});
|
||||
|
||||
@@ -21,8 +21,8 @@ beforeEach(() => {
|
||||
vi.spyOn(Date, "now").mockImplementation(() => clock++);
|
||||
setState({
|
||||
project: { ...sampleProject, components: sampleProject.components.slice(0, 1), pens: [], penSets: [], activePenSetId: undefined },
|
||||
undoStack: [],
|
||||
redoStack: [],
|
||||
undoDepth: 0,
|
||||
redoDepth: 0,
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
});
|
||||
|
||||
@@ -21,8 +21,8 @@ const openPoly: Drawing2D = {
|
||||
beforeEach(() => {
|
||||
setState({
|
||||
project: { ...sampleProject, drawings2d: [openPoly] },
|
||||
undoStack: [],
|
||||
redoStack: [],
|
||||
undoDepth: 0,
|
||||
redoDepth: 0,
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
});
|
||||
|
||||
@@ -24,8 +24,8 @@ function setPolyline(geom: Extract<Drawing2D["geom"], { shape: "polyline" }>) {
|
||||
};
|
||||
setState({
|
||||
project: { ...sampleProject, drawings2d: [d] },
|
||||
undoStack: [],
|
||||
redoStack: [],
|
||||
undoDepth: 0,
|
||||
redoDepth: 0,
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
});
|
||||
|
||||
@@ -60,8 +60,8 @@ beforeEach(() => {
|
||||
...sampleProject,
|
||||
drawings2d: [plainText, textBox, rotatedTextBox],
|
||||
},
|
||||
undoStack: [],
|
||||
redoStack: [],
|
||||
undoDepth: 0,
|
||||
redoDepth: 0,
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
});
|
||||
|
||||
@@ -16,8 +16,8 @@ import { DEFAULT_PRESETS } from "../text/richText";
|
||||
beforeEach(() => {
|
||||
setState({
|
||||
project: { ...sampleProject, textStyles: undefined },
|
||||
undoStack: [],
|
||||
redoStack: [],
|
||||
undoDepth: 0,
|
||||
redoDepth: 0,
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
});
|
||||
|
||||
+16
-39
@@ -8,7 +8,7 @@
|
||||
// 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, validateOps } from "../core/ops";
|
||||
import { diffToOps } from "../core/ops";
|
||||
import type { CoreOp } from "../core/ops";
|
||||
import { withVertexType, type PolylineVertexType } from "../core";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
@@ -54,7 +54,7 @@ import { textFrameCorners } from "../text/textFrame";
|
||||
import { DEFAULT_PRESETS, type TextStylePreset } from "../text/richText";
|
||||
import { t } from "../i18n";
|
||||
import type { StoreApi } from "./store";
|
||||
import { createHistorySlice, pushHistoryPatch } from "./historySlice";
|
||||
import { createHistorySlice, historyPatch, storeDocument } from "./historySlice";
|
||||
import type { HistorySlice } from "./historySlice";
|
||||
import type { NotifyKind } from "./notifySlice";
|
||||
|
||||
@@ -422,7 +422,7 @@ export interface ProjectSlice {
|
||||
* `get()`/`set` typsicher auf `activeLevelId` zugreifen können. Die
|
||||
* History-Felder gehören ebenfalls dazu: `setProject` (unten) ist der EINZIGE
|
||||
* Durchlaufpunkt jeder Projekt-Mutation und pusht dort bei jeder ECHTEN
|
||||
* Änderung auf `undoStack`.
|
||||
* Änderung einen Undo-Schritt im Kern-Dokument auf.
|
||||
*/
|
||||
type ProjectSliceDeps = {
|
||||
activeLevelId: string;
|
||||
@@ -436,32 +436,16 @@ export function createProjectSlice(
|
||||
): ProjectSlice & HistorySlice {
|
||||
const { set, get } = api;
|
||||
|
||||
// Koaleszenz-Buchführung für Drag-Serien (Griff ziehen, Element verschieben,
|
||||
// Kante ziehen, …): diese Aktionen rufen `setProject` bei JEDEM
|
||||
// Maus-Move-Schritt auf (kein separates Draft/Preview + Commit-Muster wie
|
||||
// bei den Zeichenwerkzeugen — dort läuft die Vorschau über lokalen
|
||||
// `draft`-State in App.tsx, und `setProject` wird erst einmal beim Commit
|
||||
// aufgerufen, siehe `applyToolResult`/`onToolCommit` in App.tsx). Ohne
|
||||
// Koaleszenz würde EIN Drag zig Undo-Schritte erzeugen. Ephemer (wie ein
|
||||
// Ref) — kein reaktiver State nötig, wird bei jedem `setProject`-Aufruf neu
|
||||
// bewertet und bei `undo`/`redo` zurückgesetzt (siehe `onAfterJump` unten).
|
||||
let lastCoalesceKey: string | undefined;
|
||||
let lastCoalesceAt = 0;
|
||||
const COALESCE_WINDOW_MS = 400;
|
||||
// Koaleszenz von Drag-Serien (Griff ziehen, Element verschieben, Kante ziehen, …): diese
|
||||
// Aktionen rufen `setProject` bei JEDEM Maus-Move-Schritt mit einem `coalesceKey` auf (kein
|
||||
// Draft/Commit-Muster wie bei den Zeichenwerkzeugen, deren Vorschau über lokalen `draft`-State
|
||||
// in App.tsx läuft). Gleicher Schlüssel innerhalb des Zeitfensters = EIN Undo-Schritt; die
|
||||
// Buchführung (Schlüssel, Zeitfenster, Rücksetzen nach Undo/Redo) liegt im Kern (`ops.rs`).
|
||||
// Protokoll der angewendeten Ops (jüngste zuletzt) — Rohstoff für Undo-Verlauf [84], Makros [85].
|
||||
const opLog: CoreOp[][] = [];
|
||||
const OP_LOG_LIMIT = 200;
|
||||
|
||||
const history = createHistorySlice(
|
||||
api as unknown as StoreApi<HistorySlice & { project: Project }>,
|
||||
() => {
|
||||
// Nach einem Sprung (undo/redo) muss die NÄCHSTE Aktion garantiert
|
||||
// pushen, auch wenn sie zufällig denselben coalesceKey trägt wie die
|
||||
// Serie vor dem Sprung — sonst würde sie mit der alten Serie
|
||||
// verschmolzen und verschwände spurlos (kein Undo-Eintrag).
|
||||
lastCoalesceKey = undefined;
|
||||
},
|
||||
);
|
||||
const history = createHistorySlice(api as unknown as StoreApi<HistorySlice & { project: Project }>);
|
||||
|
||||
// Bequemer immutabler Projekt-Updater (wie setProject in App). Zweiter,
|
||||
// optionaler Parameter `coalesceKey`: NUR von den paar bekannten
|
||||
@@ -482,28 +466,21 @@ export function createProjectSlice(
|
||||
// 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, validiert und angewendet. Verstösse (NaN, doppelte ids)
|
||||
// werden zurückgerollt und gemeldet.
|
||||
// eine Op-Folge übersetzt; der Kern prüft (NaN, doppelte ids), wendet an und zeichnet den
|
||||
// Undo-Schritt auf. Verstösse werden zurückgerollt und gemeldet.
|
||||
const ops = diffToOps(s.project, wanted);
|
||||
if (ops.length === 0) return {};
|
||||
const nextProject = applyOps(s.project, ops);
|
||||
const problems = validateOps(nextProject, ops, s.project);
|
||||
if (problems.length > 0) {
|
||||
const doc = storeDocument(s.project);
|
||||
const res = doc.commit(s.project, ops, coalesceKey, Date.now());
|
||||
if ("problems" in res) {
|
||||
const problems = res.problems;
|
||||
console.warn("Projektänderung verworfen:", problems);
|
||||
queueMicrotask(() => get().notify(`${t("project.change.rejected")} ${problems[0]}`, "error"));
|
||||
return {};
|
||||
}
|
||||
opLog.push(ops);
|
||||
if (opLog.length > OP_LOG_LIMIT) opLog.shift();
|
||||
const now = Date.now();
|
||||
const coalesced =
|
||||
coalesceKey !== undefined &&
|
||||
coalesceKey === lastCoalesceKey &&
|
||||
now - lastCoalesceAt < COALESCE_WINDOW_MS;
|
||||
lastCoalesceKey = coalesceKey;
|
||||
lastCoalesceAt = now;
|
||||
if (coalesced) return { project: nextProject };
|
||||
return { project: nextProject, ...pushHistoryPatch(s.undoStack, s.project) };
|
||||
return { project: res.project, ...historyPatch(doc) };
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -31,8 +31,8 @@ beforeEach(() => {
|
||||
...sampleProject,
|
||||
drawingLevels: [floor("A"), floor("B"), floor("C"), floor("D")],
|
||||
},
|
||||
undoStack: [],
|
||||
redoStack: [],
|
||||
undoDepth: 0,
|
||||
redoDepth: 0,
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
});
|
||||
|
||||
@@ -27,8 +27,8 @@ beforeEach(() => {
|
||||
...sampleProject,
|
||||
drawings2d: [rect("A"), rect("B"), rect("C"), rect("D")],
|
||||
},
|
||||
undoStack: [],
|
||||
redoStack: [],
|
||||
undoDepth: 0,
|
||||
redoDepth: 0,
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
});
|
||||
|
||||
@@ -40,8 +40,8 @@ const baseProject = {
|
||||
beforeEach(() => {
|
||||
setState({
|
||||
project: JSON.parse(JSON.stringify(baseProject)),
|
||||
undoStack: [],
|
||||
redoStack: [],
|
||||
undoDepth: 0,
|
||||
redoDepth: 0,
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
});
|
||||
@@ -62,15 +62,14 @@ describe("moveRoofGrip — Eckpunkt-Resize", () => {
|
||||
});
|
||||
|
||||
it("hochfrequente Drags koaleszieren zu EINEM Undo-Schritt", () => {
|
||||
// Saubere Koaleszenz-Grenze: eine diskrete (keyless) Aktion setzt
|
||||
// lastCoalesceKey zurück, damit der erste Drag garantiert pusht (der
|
||||
// Coalesce-Zustand ist ein Modul-Closure und überlebt sonst zwischen Tests).
|
||||
// Saubere Koaleszenz-Grenze: eine diskrete (keyless) Aktion setzt den
|
||||
// Koaleszenz-Schlüssel im Kern zurück, danach Verlauf leeren.
|
||||
getState().updateRoof("RF1", { overhang: 0.1 });
|
||||
setState({ undoStack: [], canUndo: false });
|
||||
getState().clearHistory();
|
||||
getState().moveRoofGrip("RF1", 2, { x: 5, y: 3 });
|
||||
getState().moveRoofGrip("RF1", 2, { x: 5.5, y: 3.5 });
|
||||
getState().moveRoofGrip("RF1", 2, { x: 7, y: 5 });
|
||||
expect(getState().undoStack.length).toBe(1);
|
||||
expect(getState().undoDepth).toBe(1);
|
||||
getState().undo();
|
||||
// Nach einem Undo wieder der Ausgangsumriss.
|
||||
expect(getState().project.roofs![0].outline).toEqual(baseProject.roofs![0].outline);
|
||||
|
||||
@@ -18,16 +18,18 @@ describe("setProject über CoreOps", () => {
|
||||
expect(ops.length).toBeGreaterThan(0);
|
||||
expect(JSON.parse(JSON.stringify(ops.at(-1)))).toEqual(ops.at(-1));
|
||||
st().undo();
|
||||
expect(st().project).toBe(before);
|
||||
// Undo kommt als inverse Ops aus dem Kern: inhaltlich gleich, unveränderte Elemente identisch.
|
||||
expect(st().project).toEqual(before);
|
||||
expect(st().project.walls[1]).toBe(before.walls[1]);
|
||||
});
|
||||
|
||||
it("NaN-Änderung wird verworfen, Projekt bleibt, Undo-Stapel unverändert", () => {
|
||||
const before = st().project;
|
||||
const depth = st().undoStack.length;
|
||||
const depth = st().undoDepth;
|
||||
const w = before.walls[0];
|
||||
st().setProject({ ...before, walls: [{ ...w, height: NaN }, ...before.walls.slice(1)] });
|
||||
expect(st().project).toBe(before);
|
||||
expect(st().undoStack.length).toBe(depth);
|
||||
expect(st().undoDepth).toBe(depth);
|
||||
});
|
||||
|
||||
it("doppelte ids beim Einfügen werden verworfen", () => {
|
||||
|
||||
@@ -1255,6 +1255,11 @@ export function usePanelHostBase(opts: {
|
||||
// aktuellen Stand an — Name automatisch die aktive Zeichnungskombination
|
||||
// (falls deren Sichtbarkeits-Map exakt passt) oder sonst das aktive Blatt
|
||||
// (Nutzer-Wunsch). Wählt den neuen Ausschnitt sofort an (Tab wird aktiv).
|
||||
viewSnapshotAutoName: (): string => {
|
||||
const combo = matchingComboName(listDrawingCombos(), loadDrawingCombo, snapshotDrawingVisibility());
|
||||
return combo ?? project.drawingLevels.find((l) => l.id === activeLevelId)?.name ?? activeLevelId;
|
||||
},
|
||||
|
||||
onCaptureViewSnapshotAuto: (): string => {
|
||||
const drawingVisibility = snapshotDrawingVisibility();
|
||||
const combo = matchingComboName(listDrawingCombos(), loadDrawingCombo, drawingVisibility);
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//
|
||||
// Extrahiert aus App.tsx. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import { useStore } from "./appStore";
|
||||
import { getState, useStore } from "./appStore";
|
||||
import type { NotifyKind } from "./notifySlice";
|
||||
import { parseProjectFile, parseProjectObject, serializeProject } from "../io/projectFormat";
|
||||
import { AUTOSAVE_INTERVAL_MS, clearAutosave, createAutosaveTracker, readAutosave, writeAutosave } from "./autosave";
|
||||
@@ -172,6 +172,13 @@ 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();
|
||||
};
|
||||
// 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);
|
||||
@@ -238,7 +245,7 @@ export function useProjectFileActions(
|
||||
const onRecoverRestore = () => {
|
||||
if (!recovery) return;
|
||||
const parsed = parseProjectObject(recovery.project);
|
||||
if (parsed.ok) setProject(parsed.project); // bleibt „ungespeichert" bis zum Speichern
|
||||
if (parsed.ok) replaceProject(parsed.project); // bleibt „ungespeichert" bis zum Speichern
|
||||
else notify(`${t("project.open.failed")} ${parsed.error}`, "error");
|
||||
setRecovery(null);
|
||||
};
|
||||
@@ -443,7 +450,7 @@ export function useProjectFileActions(
|
||||
// `guardDiscard`: bei ungespeicherten Änderungen erst der Dialog, s. o.
|
||||
const onNewProject = () => guardDiscard(() => {
|
||||
releaseCurrentProjectLock();
|
||||
setProject(emptyProject);
|
||||
replaceProject(emptyProject);
|
||||
lastSavedProjectRef.current = emptyProject;
|
||||
});
|
||||
|
||||
@@ -458,7 +465,7 @@ export function useProjectFileActions(
|
||||
if (!parsed) return false;
|
||||
guardDiscard(() => {
|
||||
releaseCurrentProjectLock();
|
||||
setProject(parsed);
|
||||
replaceProject(parsed);
|
||||
lastSavedProjectRef.current = parsed;
|
||||
});
|
||||
return true;
|
||||
@@ -474,7 +481,7 @@ export function useProjectFileActions(
|
||||
const onNewProjectFromSample = () => guardDiscard(() => {
|
||||
releaseCurrentProjectLock();
|
||||
const next = structuredClone(sampleProject);
|
||||
setProject(next);
|
||||
replaceProject(next);
|
||||
lastSavedProjectRef.current = next;
|
||||
});
|
||||
// „Neu aus Vorlage: Datei wählen…" — native `.obpt`-Dialog unter Tauri, sonst
|
||||
@@ -498,7 +505,7 @@ export function useProjectFileActions(
|
||||
const onProjectTemplateFileChosen = (file: File) => {
|
||||
const r = new FileReader();
|
||||
r.onload = () => applyTemplateContent(String(r.result ?? ""));
|
||||
r.readAsArrayBuffer(file);
|
||||
r.readAsText(file);
|
||||
};
|
||||
|
||||
// Gibt den Lock der zuletzt geöffneten Projektdatei frei (falls wir ihn
|
||||
@@ -522,7 +529,7 @@ export function useProjectFileActions(
|
||||
}
|
||||
guardDiscard(() => {
|
||||
releaseCurrentProjectLock();
|
||||
setProject(parsed);
|
||||
replaceProject(parsed);
|
||||
lastSavedProjectRef.current = parsed;
|
||||
openedProjectPathRef.current = path;
|
||||
projectLockOwnedRef.current = lockOwned;
|
||||
@@ -652,14 +659,14 @@ export function useProjectFileActions(
|
||||
// Datei, aber ein evtl. vorher (unter Tauri) gehaltener Lock wird frei.
|
||||
guardDiscard(() => {
|
||||
releaseCurrentProjectLock();
|
||||
setProject(parsed);
|
||||
replaceProject(parsed);
|
||||
lastSavedProjectRef.current = parsed;
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("Projekt-Import fehlgeschlagen:", err);
|
||||
}
|
||||
};
|
||||
r.readAsArrayBuffer(file);
|
||||
r.readAsText(file);
|
||||
};
|
||||
|
||||
const importParentName = (decision: ImportDecision): string =>
|
||||
|
||||
Reference in new issue
Block a user