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
@@ -176,8 +176,31 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
kommen über `planDomains` aus dem Dokument ([K3d]); übrig in `generatePlan`: 2D-Zeichnungen, Schatten/Baurecht, Abzugskörper.
|
||||
Ziel: Plan/Schnitt/Ansicht, 3D, Export rechnen mit `doc`-Handle statt flach gesammelter Arrays; TS-Sammler/-Adapter werden gelöscht
|
||||
([K3d] hängt hier dran: Plan-Puffer v2 mit Pick-IDs und vollem Primitive-Umfang).
|
||||
- ○ **S3 Änderungen kommen aus Rust**: Befehle (Zustandsautomaten, Werkzeuge) erzeugen Ops im Kern; Undo/Redo, Validierung
|
||||
- ◐ **S3 Änderungen kommen aus Rust**: Befehle (Zustandsautomaten, Werkzeuge) erzeugen Ops im Kern; Undo/Redo, Validierung
|
||||
(`validateOps`) und Gruppen/Ebenen-Logik wandern nach Rust; `diffToOps` entfällt, TS hält nur noch eine Leseansicht.
|
||||
**Erste Etappe (28.10.): Ops, Prüfung, Undo/Redo im Kern.** `core/src/ops.rs` (Op, Prüfung bitgleich zur TS-Fassung — gleiche
|
||||
Ablehnungen und Meldungen; NaN/±Infinity reisen als Marken `"\u0001NaN"`, weil JSON sie nicht kennt), `document.rs`
|
||||
`commit`/`undo`/`redo`: atomar anwenden, prüfen, bei Verstoss über die inversen Ops zurückrollen; Verlauf als **inverse Ops**
|
||||
statt Schnappschüssen (feine Inverse je Op, Feld-Sicherung nur bei Alt-Doppelungen/fehlendem Feld; Feld-Position wird mit
|
||||
zurückgegeben, Undo ist JSON-exakt). coalesceKey + Zeitfenster (400 ms) und Gruppen (`doc_group_begin/end`, Store
|
||||
`groupChanges`) = ein Schritt; Drag-Serien werden verdichtet (wachsen nicht je Mausbewegung); Grenzen 100 Schritte /
|
||||
256 MiB (älteste fallen weg). Store: `setProject` → `diffToOps` → `ProjectDocument.commit` (Kern) → TS führt die
|
||||
Leseansicht mit denselben Ops nach (`applyOps`); `undo`/`redo` holen die Ops aus dem Kern (`doc_undo`/`doc_redo`).
|
||||
TS-Snapshot-Undo und TS-`validateOps`/`validateProject`-Rechnung gelöscht (Fassaden über `ops_validate`/`project_validate`).
|
||||
Das Store-Dokument ist zugleich das Abfrage-Dokument (`documentFor` → kein zweiter Spiegel). Store-Felder
|
||||
`undoStack/redoStack` → `undoDepth/redoDepth`, `clearHistory()`.
|
||||
**Entscheid Richtung (28.10.):** halb umgedreht. Der Kern ist Autorität für Prüfung und Verlauf; das TS-Projekt ist eine
|
||||
Leseansicht, die nur mit Ops nachgeführt wird, die der Kern angenommen (`commit`) oder geliefert (Undo/Redo) hat — so kann
|
||||
sie nicht auseinanderlaufen (Test: 1000 Zufallsänderungen, Undo bis Anfang/Redo bis Ende, Kern-JSON == TS-Projekt).
|
||||
`diffToOps` bleibt vorerst als Adapter, weil ~50 Store-Aktionen, Griffe, Panels und `src/commands` noch Projekt → Projekt
|
||||
liefern; die volle Umkehr (ganzes Projekt als JSON zurück) ist verworfen: sie kostet je Schritt Parse-Zeit und zerstört die
|
||||
Objekt-Identität unveränderter Elemente, auf der die Plan-/3D-Caches beruhen. Patches (Ops) erhalten sie. Änderungen vorbei an
|
||||
den Ops (direktes `setState` in Tests) zieht der Spiegel per Differenz nach und leert den Verlauf.
|
||||
**Messung** (Linux-Container): Kern nativ (release), 5000 Wände: commit 51 µs, Undo 37 µs, Redo 36 µs je Schritt. Über WASM im
|
||||
Store-Weg (vitest, 3000 Wände, 500 Schritte): 2,6 ms/Schritt, davon `diffToOps`+`applyOps` in TS ≈ 2,0 ms, Kern-Commit ≈ 0,4 ms;
|
||||
Undo 0,08 ms, Redo 0,07 ms; Verlauf ≈ 780 KiB für 500 Schritte.
|
||||
Offen: Befehle/Store-Aktionen erzeugen Ops direkt (dann entfällt `diffToOps`, der grösste Kostenanteil); `applyOps` bleibt als
|
||||
Patch-Anwendung der Leseansicht; Ebenen-/Gruppen-Logik (`groupActions.ts`) nach Rust; Undo-Verlauf als Liste in der UI [84].
|
||||
- ○ **S4 Typen aus Rust**: `types.ts` wird aus den Rust-Strukturen erzeugt (ts-rs); Datei-I/O (`projectFormat`, Migration, IFC/DXF/
|
||||
STEP-Ex- und -Import) im Kern.
|
||||
Offene Entscheide/Risiken: Kosten der JSON-Übergabe bei grossen Projekten (Teil-Updates statt Neuaufbau), Struktur-Sharing im
|
||||
@@ -268,8 +291,14 @@ Entscheid CLA vs. Verzicht auf Dual Licensing.
|
||||
|
||||
- ◐ **[6] Jede Aktion ist ein Befehl mit JSON-Parametern.** Registratur vorhanden, aber interaktiv;
|
||||
Panels/Griffe ändern das Projekt direkt. · L
|
||||
- ○ **[7] Zentrale Validierung nach jedem Befehl.** · M
|
||||
- ◐ **[8] Undo über Befehle.** Undo existiert (Snapshots, coalesceKey), nicht befehlsbasiert. · M
|
||||
- ◐ **[7] Zentrale Validierung nach jedem Befehl.** 28.10.: jede Projektänderung wird im Kern geprüft (`ops.rs`, NaN/neue doppelte
|
||||
ids → Rücknahme mit Meldung); weitere Regeln (Bezüge, Geometrie) offen. · M
|
||||
- ◐ **[8] Undo über Befehle.** 28.10.: Verlauf im Rust-Kern als inverse Ops (coalesceKey, Gruppen, Speichergrenze), keine
|
||||
28.10. (Mac-Test Maintainer): nach mehrmaligem Ganz-zurück/Vor war Redo weg. Ursache: die Ausschnitt-Leiste legte bei
|
||||
leerem `viewSnapshots` automatisch einen Ausschnitt an (Projektänderung → neuer Verlaufsschritt). Jetzt nur Anzeige-Tab
|
||||
ohne Projektänderung; Neu/Öffnen/Vorlage/Wiederherstellen leeren den Verlauf; Browser-Öffnen liest Text statt
|
||||
ArrayBuffer. Tests: `history.roundtrip.test.ts`, e2e „Mehrmals ganz zurück und wieder vor“.
|
||||
Snapshots mehr ([K4] S3). Offen: Befehle erzeugen Ops direkt statt `diffToOps`. · M
|
||||
- ◐ **[9] MCP-Brücke.** Headless `dossier-cli … mcp`; Brücke zum offenen Fenster fehlt. · M
|
||||
|
||||
### Daten
|
||||
|
||||
@@ -77,3 +77,29 @@ test("Rückgängig/Wiederholen per Tastatur und Menü", async ({ page }) => {
|
||||
await page.getByRole("option", { name: "Wiederholen" }).click();
|
||||
await expect(elementRows(page)).toHaveCount(1);
|
||||
});
|
||||
|
||||
// Maintainer-Fund 28.10.: mehrmals ganz zurück bis zum leeren Projekt und wieder vor — irgendwann war
|
||||
// der Redo-Stapel weg (Neu/Öffnen lagen im Undo-Verlauf, das leere Startprojekt war erreichbar).
|
||||
test("Mehrmals ganz zurück und wieder vor: Redo bleibt vollständig", async ({ page }) => {
|
||||
await startNewProject(page);
|
||||
await openTab(page, "Elemente");
|
||||
await pickWallTool(page);
|
||||
await commandInput(page).focus();
|
||||
await typeCommand(page, "0,0");
|
||||
await typeCommand(page, "5,0");
|
||||
await typeCommand(page, "5,4");
|
||||
await typeCommand(page, "0,4");
|
||||
await finishCommand(page);
|
||||
await expect(elementRows(page)).toHaveCount(3);
|
||||
await blurFocus(page);
|
||||
|
||||
for (let round = 0; round < 3; round++) {
|
||||
// Mehr Rückgängig als Schritte: über den Anfang hinaus darf nichts passieren.
|
||||
for (let k = 0; k < 6; k++) await page.keyboard.press("ControlOrMeta+z");
|
||||
await expect(elementRows(page)).toHaveCount(0);
|
||||
for (let k = 0; k < 6; k++) await page.keyboard.press("ControlOrMeta+Shift+z");
|
||||
await expect(elementRows(page)).toHaveCount(3);
|
||||
}
|
||||
// „Neues Projekt" ist nicht rückgängig zu machen (Verlauf beginnt neu).
|
||||
await expect(page.locator(".project-name")).toHaveText("Leeres Projekt");
|
||||
});
|
||||
@@ -28,15 +28,7 @@ async function chooseFile(page: Page, menuItem: string | RegExp, file: string |
|
||||
await (await chooser).setFiles(file);
|
||||
}
|
||||
|
||||
// BEKANNTER FEHLER (28.10.): `onProjectFileChosen` (src/state/useProjectFileActions.ts) liest die Datei mit
|
||||
// `readAsArrayBuffer` und macht `String(r.result)` daraus („[object ArrayBuffer]") — im Browser-Pfad
|
||||
// meldet die App „Die Datei ist kein gültiges JSON". Unter Tauri (nativer Dialog) tritt es nicht auf.
|
||||
// Fix: `r.readAsText(file)`. Bis dahin ist die Erwartung umgekehrt (`test.fail`); sobald der Fehler
|
||||
// behoben ist, schlägt diese Markierung an und wird entfernt.
|
||||
const OPEN_BUG = "Projekt öffnen im Browser: readAsArrayBuffer + String(result) → „kein gültiges JSON“";
|
||||
|
||||
test("Beispielprojekt aus Datei öffnen (.obp-Fixture der CLI)", async ({ page }) => {
|
||||
test.fail(true, OPEN_BUG);
|
||||
await startNewProject(page);
|
||||
await chooseFile(page, "Projekt öffnen", BEISPIEL_OBP);
|
||||
await discardIfAsked(page);
|
||||
@@ -56,7 +48,6 @@ test("Speichern: .obp-Download mit gültigem Projekt-JSON", async ({ page }) =>
|
||||
});
|
||||
|
||||
test("Speichern und Laden: .obp-Rundreise", async ({ page }) => {
|
||||
test.fail(true, OPEN_BUG);
|
||||
await startNewProject(page);
|
||||
await openSample(page);
|
||||
|
||||
|
||||
+371
-148
@@ -1,93 +1,17 @@
|
||||
//! Projekt-Dokument und Ops ([K4], Stufe S1): Rust hält das Projekt als JSON-Baum und wendet die
|
||||
//! Op-Folgen an, die TS aus `core/ops.ts` erzeugt (`setField`/`add`/`replace`/`remove`/`reorder`).
|
||||
//! Die Ops werden atomar angewendet und geprüft (doppelte ids); bei Verstoss bleibt das Dokument
|
||||
//! unverändert. Später lesen die Ableitungen (Plan, Schnitt, 3D, Kennzahlen, Export) direkt dieses
|
||||
//! Dokument statt flacher TS-Sammler.
|
||||
//! Projekt-Dokument ([K4], Stufen S1/S3): Rust hält das Projekt als JSON-Baum, wendet Op-Folgen
|
||||
//! (`ops.rs`) atomar an, prüft sie (NaN, neue doppelte ids → Rücknahme mit Meldungen) und führt den
|
||||
//! Undo/Redo-Verlauf als inverse Ops. Die Ableitungen (Kennzahlen, 3D, Export …) lesen die
|
||||
//! typisierte Sicht [`Document::project`].
|
||||
//!
|
||||
//! JSON kennt weder `undefined` noch NaN: fehlende Felder fehlen, nicht endliche Zahlen prüft TS
|
||||
//! vor dem Senden (`validateOps`).
|
||||
//! TS hält eine Leseansicht des Projekts und wendet genau die Ops an, die der Kern angenommen
|
||||
//! (`commit`) oder für Undo/Redo geliefert hat (`core/document.ts`).
|
||||
|
||||
use crate::model::Project;
|
||||
pub use crate::ops::Op;
|
||||
use crate::ops::{has_dup, id_of, unique_ids, History};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Map, Value};
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// Eine Änderung am Projekt (Spiegel von `CoreOp` in `core/ops.ts`).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Op {
|
||||
Add { collection: String, items: Vec<Value>, at: Option<usize> },
|
||||
Replace { collection: String, entity: Value },
|
||||
Remove { collection: String, ids: Vec<String> },
|
||||
Reorder { collection: String, ids: Vec<String> },
|
||||
SetField { key: String, value: Option<Value> },
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> Option<&str> {
|
||||
v.get("id").and_then(Value::as_str)
|
||||
}
|
||||
|
||||
impl Op {
|
||||
pub fn from_json(v: &Value) -> Result<Op, String> {
|
||||
let kind = v.get("kind").and_then(Value::as_str).ok_or("Op ohne kind")?;
|
||||
let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_owned).ok_or(format!("Op {kind}: {k} fehlt"));
|
||||
let ids = |k: &str| -> Result<Vec<String>, String> {
|
||||
v.get(k)
|
||||
.and_then(Value::as_array)
|
||||
.ok_or(format!("Op {kind}: {k} fehlt"))?
|
||||
.iter()
|
||||
.map(|x| x.as_str().map(str::to_owned).ok_or(format!("Op {kind}: {k} enthält Nicht-Text")))
|
||||
.collect()
|
||||
};
|
||||
Ok(match kind {
|
||||
"add" => {
|
||||
let items = v.get("items").and_then(Value::as_array).ok_or("Op add: items fehlt")?.clone();
|
||||
if items.iter().any(|e| id_of(e).is_none()) {
|
||||
return Err("Op add: Element ohne id".into());
|
||||
}
|
||||
let at = match v.get("at") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(a) => Some(a.as_f64().filter(|x| x.is_finite()).map(|x| x.max(0.0) as usize).ok_or("Op add: at ungültig")?),
|
||||
};
|
||||
Op::Add { collection: s("collection")?, items, at }
|
||||
}
|
||||
"replace" => {
|
||||
let entity = v.get("entity").cloned().ok_or("Op replace: entity fehlt")?;
|
||||
if id_of(&entity).is_none() {
|
||||
return Err("Op replace: Element ohne id".into());
|
||||
}
|
||||
Op::Replace { collection: s("collection")?, entity }
|
||||
}
|
||||
"remove" => Op::Remove { collection: s("collection")?, ids: ids("ids")? },
|
||||
"reorder" => Op::Reorder { collection: s("collection")?, ids: ids("ids")? },
|
||||
"setField" => Op::SetField { key: s("key")?, value: v.get("value").filter(|x| !x.is_null()).cloned() },
|
||||
other => return Err(format!("Unbekannte Op: {other}")),
|
||||
})
|
||||
}
|
||||
|
||||
fn key(&self) -> &str {
|
||||
match self {
|
||||
Op::Add { collection, .. } | Op::Replace { collection, .. } | Op::Remove { collection, .. } | Op::Reorder { collection, .. } => collection,
|
||||
Op::SetField { key, .. } => key,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Liste mit lauter `id`-tragenden Elementen (leer zählt mit).
|
||||
fn is_id_list(v: &Value) -> bool {
|
||||
v.as_array().is_some_and(|a| a.iter().all(|e| id_of(e).is_some()))
|
||||
}
|
||||
|
||||
fn unique_ids(list: &[Value]) -> bool {
|
||||
let mut seen = HashSet::new();
|
||||
list.iter().all(|e| seen.insert(id_of(e).unwrap_or("")))
|
||||
}
|
||||
|
||||
fn has_dup(v: Option<&Value>) -> bool {
|
||||
match v {
|
||||
Some(v) if is_id_list(v) => !unique_ids(v.as_array().unwrap()),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Document {
|
||||
@@ -96,12 +20,14 @@ pub struct Document {
|
||||
/// genau diese Felder neu ein.
|
||||
typed: Option<Project>,
|
||||
dirty: HashSet<String>,
|
||||
/// Undo/Redo-Verlauf (inverse Ops, `ops::History`).
|
||||
history: History,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
pub fn from_json(text: &str) -> Result<Document, String> {
|
||||
match serde_json::from_str::<Value>(text) {
|
||||
Ok(Value::Object(root)) => Ok(Document { root, typed: None, dirty: HashSet::new() }),
|
||||
Ok(Value::Object(root)) => Ok(Document { root, typed: None, dirty: HashSet::new(), history: History::default() }),
|
||||
Ok(_) => Err("Projekt ist kein JSON-Objekt".into()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
@@ -133,7 +59,7 @@ impl Document {
|
||||
let mut failed = None;
|
||||
if let Some(t) = self.typed.as_mut() {
|
||||
for key in &dirty {
|
||||
if let Err(e) = t.set_field(key, self.root.get(key)) {
|
||||
if let Err(e) = t.set_field(key, self.root.get(key).filter(|v| !v.is_null())) {
|
||||
failed = Some(e);
|
||||
break;
|
||||
}
|
||||
@@ -159,12 +85,20 @@ impl Document {
|
||||
slot.as_array_mut().unwrap()
|
||||
}
|
||||
|
||||
fn apply_one(&mut self, op: &Op) {
|
||||
|
||||
/// Wendet eine Op ohne Aufzeichnung an (Semantik wie `applyOps` in TS).
|
||||
fn apply_raw(&mut self, op: &Op) {
|
||||
match op {
|
||||
Op::SetField { key, value } => match value {
|
||||
Some(v) => {
|
||||
self.root.insert(key.clone(), v.clone());
|
||||
}
|
||||
Op::SetField { key, value, at } => match value {
|
||||
Some(v) => match at {
|
||||
Some(i) if !self.root.contains_key(key) => {
|
||||
let i = (*i).min(self.root.len());
|
||||
self.root.shift_insert(i, key.clone(), v.clone());
|
||||
}
|
||||
_ => {
|
||||
self.root.insert(key.clone(), v.clone());
|
||||
}
|
||||
},
|
||||
None => {
|
||||
self.root.shift_remove(key);
|
||||
}
|
||||
@@ -188,76 +122,183 @@ impl Document {
|
||||
}
|
||||
Op::Reorder { collection, ids } => {
|
||||
let list = std::mem::take(self.list_mut(collection));
|
||||
let mut ordered = Vec::with_capacity(list.len());
|
||||
let mut rest = Vec::new();
|
||||
let listed: HashSet<&str> = ids.iter().map(String::as_str).collect();
|
||||
for id in ids {
|
||||
if let Some(e) = list.iter().find(|e| id_of(e) == Some(id.as_str())) {
|
||||
ordered.push(e.clone());
|
||||
}
|
||||
}
|
||||
let mut by_id: HashMap<&str, &Value> = HashMap::new();
|
||||
for e in &list {
|
||||
if !id_of(e).is_some_and(|i| listed.contains(i)) {
|
||||
rest.push(e.clone());
|
||||
// Erstes Vorkommen gewinnt (wie bisher `find`).
|
||||
if let Some(i) = id_of(e) {
|
||||
by_id.entry(i).or_insert(e);
|
||||
}
|
||||
}
|
||||
ordered.extend(rest);
|
||||
let mut ordered: Vec<Value> = ids.iter().filter_map(|id| by_id.get(id.as_str()).map(|e| (*e).clone())).collect();
|
||||
ordered.extend(list.iter().filter(|e| !id_of(e).is_some_and(|i| listed.contains(i))).cloned());
|
||||
*self.list_mut(collection) = ordered;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wendet `ops` atomar an. Verstösse (neue doppelte ids) → `Err(Meldungen)`, Dokument unverändert.
|
||||
pub fn apply(&mut self, ops: &[Op]) -> Result<(), Vec<String>> {
|
||||
/// Wendet eine Op an und liefert (inverse Ops in Anwendungsreihenfolge, normalisierte
|
||||
/// Vorwärts-Op). Listen bekommen feine Inverse (`replace` ↔ altes Element, `add` ↔ `remove`,
|
||||
/// `remove` ↔ `add` an den alten Positionen, `reorder` ↔ alte Reihenfolge), wo das exakt ist
|
||||
/// (`add`: ids neu und eindeutig; `reorder`: alle ids eindeutig); sonst (fehlendes Feld, kein
|
||||
/// Array, Alt-Doppelungen) wird das ganze Feld samt Position gesichert. Ohne Hash über die ganze
|
||||
/// Liste — ein Drag-Schritt kostet nur das Suchen des Elements.
|
||||
fn apply_recorded(&mut self, op: &Op) -> (Vec<Op>, Op) {
|
||||
let key = op.key();
|
||||
let old = self.root.get(key);
|
||||
let snapshot = || {
|
||||
let at = self.root.keys().position(|k| k == key);
|
||||
Op::SetField { key: key.to_owned(), value: old.cloned(), at }
|
||||
};
|
||||
let clean = match op {
|
||||
Op::SetField { .. } => None,
|
||||
Op::Reorder { .. } => old.and_then(Value::as_array).filter(|a| a.iter().all(|e| id_of(e).is_some()) && unique_ids(a)),
|
||||
_ => old.and_then(Value::as_array),
|
||||
};
|
||||
let mut forward = op.clone();
|
||||
let inverse = match (op, clean) {
|
||||
(_, None) => vec![snapshot()],
|
||||
(Op::Add { collection, items, .. }, Some(list)) => {
|
||||
let mut new_ids: HashSet<&str> = HashSet::with_capacity(items.len());
|
||||
let fresh = items.iter().all(|e| id_of(e).is_some_and(|i| new_ids.insert(i)))
|
||||
&& !list.iter().any(|e| id_of(e).is_some_and(|i| new_ids.contains(i)));
|
||||
if fresh {
|
||||
vec![Op::Remove { collection: collection.clone(), ids: items.iter().filter_map(id_of).map(str::to_owned).collect() }]
|
||||
} else {
|
||||
vec![snapshot()]
|
||||
}
|
||||
}
|
||||
(Op::Replace { collection, entity }, Some(list)) => match list.iter().position(|e| id_of(e) == id_of(entity)) {
|
||||
Some(i) => {
|
||||
// Direkt ersetzen (spart die zweite Suche in `apply_raw`).
|
||||
let slot = &mut self.root.get_mut(key).and_then(Value::as_array_mut).expect("Liste geprüft")[i];
|
||||
let prev = std::mem::replace(slot, entity.clone());
|
||||
return (vec![Op::Replace { collection: collection.clone(), entity: prev }], forward);
|
||||
}
|
||||
None => {
|
||||
// Aufgezeichnet als `add` (so trifft jedes aufgezeichnete `replace` ein vorhandenes Element).
|
||||
forward = Op::Add { collection: collection.clone(), items: vec![entity.clone()], at: None };
|
||||
vec![Op::Remove { collection: collection.clone(), ids: vec![id_of(entity).unwrap_or("").to_owned()] }]
|
||||
}
|
||||
},
|
||||
(Op::Remove { collection, ids }, Some(list)) => {
|
||||
let drop: HashSet<&str> = ids.iter().map(String::as_str).collect();
|
||||
let mut runs: Vec<Op> = Vec::new();
|
||||
let mut prev: Option<usize> = None;
|
||||
for (i, e) in list.iter().enumerate() {
|
||||
if !id_of(e).is_some_and(|x| drop.contains(x)) {
|
||||
continue;
|
||||
}
|
||||
match runs.last_mut() {
|
||||
Some(Op::Add { items, .. }) if prev.is_some_and(|p| p + 1 == i) => items.push(e.clone()),
|
||||
_ => runs.push(Op::Add { collection: collection.clone(), items: vec![e.clone()], at: Some(i) }),
|
||||
}
|
||||
prev = Some(i);
|
||||
}
|
||||
runs
|
||||
}
|
||||
(Op::Reorder { collection, .. }, Some(list)) => {
|
||||
vec![Op::Reorder { collection: collection.clone(), ids: list.iter().filter_map(id_of).map(str::to_owned).collect() }]
|
||||
}
|
||||
(Op::SetField { .. }, Some(_)) => unreachable!("setField hat keine Liste"),
|
||||
};
|
||||
self.apply_raw(op);
|
||||
(inverse, forward)
|
||||
}
|
||||
|
||||
/// Wendet `ops` atomar an und prüft sie (`ops::validate`). Verstösse → `Err(Meldungen)`,
|
||||
/// Dokument unverändert. Ok → (Vorwärts-Ops normalisiert, inverse Ops). `sanitize`: die Ops
|
||||
/// können Nicht-endlich-Marken enthalten (s. `ops.rs`).
|
||||
fn apply_checked(&mut self, ops: &[Op], sanitize: bool) -> Result<(Vec<Op>, Vec<Op>), Vec<String>> {
|
||||
// Alt-Doppelungen der Listen merken, in die eingefügt oder die gesetzt wird.
|
||||
let mut had_dup: HashSet<String> = HashSet::new();
|
||||
for op in ops {
|
||||
if matches!(op, Op::Add { .. } | Op::SetField { .. }) && !had_dup.contains(op.key()) && has_dup(self.root.get(op.key())) {
|
||||
had_dup.insert(op.key().to_owned());
|
||||
}
|
||||
}
|
||||
let mut inverses: Vec<Vec<Op>> = Vec::with_capacity(ops.len());
|
||||
let mut forward: Vec<Op> = Vec::with_capacity(ops.len());
|
||||
for op in ops {
|
||||
let (inv, fwd) = self.apply_recorded(op);
|
||||
inverses.push(inv);
|
||||
forward.push(fwd);
|
||||
}
|
||||
let problems = crate::ops::validate(&self.root, ops, &|k| had_dup.contains(k));
|
||||
if !problems.is_empty() {
|
||||
for inv in inverses.iter().rev() {
|
||||
for op in inv {
|
||||
self.apply_raw(op);
|
||||
}
|
||||
}
|
||||
return Err(problems);
|
||||
}
|
||||
if sanitize {
|
||||
// Angenommene Nicht-endlich-Marken (zu tief für die Prüfung) als null speichern.
|
||||
let keys: HashSet<&str> = ops.iter().map(Op::key).collect();
|
||||
for k in keys {
|
||||
if let Some(v) = self.root.get_mut(k) {
|
||||
crate::ops::sanitize_non_finite(v);
|
||||
}
|
||||
}
|
||||
crate::ops::sanitize_ops(&mut forward);
|
||||
}
|
||||
for op in ops {
|
||||
self.dirty.insert(op.key().to_owned());
|
||||
}
|
||||
// Zustand der berührten Felder sichern (Rücknahme) und Alt-Doppelungen merken.
|
||||
let mut saved: Vec<(String, Option<Value>)> = Vec::new();
|
||||
let mut had_dup: HashSet<String> = HashSet::new();
|
||||
Ok((forward, inverses.into_iter().rev().flatten().collect()))
|
||||
}
|
||||
|
||||
/// Wendet `ops` atomar an, ohne Verlauf (Abgleich des Spiegels). Verstösse (NaN, neue
|
||||
/// doppelte ids) → `Err(Meldungen)`, Dokument unverändert.
|
||||
pub fn apply(&mut self, ops: &[Op]) -> Result<(), Vec<String>> {
|
||||
self.apply_checked(ops, false).map(|_| ())
|
||||
}
|
||||
|
||||
/// Wie [`Document::apply`]; `sanitize` = die Ops können Nicht-endlich-Marken enthalten.
|
||||
pub fn apply_marked(&mut self, ops: &[Op], sanitize: bool) -> Result<(), Vec<String>> {
|
||||
self.apply_checked(ops, sanitize).map(|_| ())
|
||||
}
|
||||
|
||||
/// Eine Benutzer-Änderung: anwenden, prüfen und als Undo-Schritt aufzeichnen (`key` =
|
||||
/// `coalesceKey`, `now` = Zeit in ms für das Koaleszenz-Fenster).
|
||||
pub fn commit(&mut self, ops: &[Op], key: Option<&str>, now: f64, sanitize: bool) -> Result<(), Vec<String>> {
|
||||
let (forward, inverse) = self.apply_checked(ops, sanitize)?;
|
||||
self.history.record(forward, inverse, key, now);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_unchecked(&mut self, ops: &[Op]) {
|
||||
for op in ops {
|
||||
let k = op.key().to_owned();
|
||||
if !saved.iter().any(|(s, _)| *s == k) {
|
||||
if has_dup(self.root.get(&k)) {
|
||||
had_dup.insert(k.clone());
|
||||
}
|
||||
saved.push((k.clone(), self.root.get(&k).cloned()));
|
||||
}
|
||||
self.apply_raw(op);
|
||||
self.dirty.insert(op.key().to_owned());
|
||||
}
|
||||
for op in ops {
|
||||
self.apply_one(op);
|
||||
}
|
||||
let mut problems = Vec::new();
|
||||
let mut checked: HashSet<&str> = HashSet::new();
|
||||
for op in ops {
|
||||
let (key, is_add, is_set) = match op {
|
||||
Op::Add { collection, .. } => (collection.as_str(), true, false),
|
||||
Op::SetField { key, .. } => (key.as_str(), false, true),
|
||||
_ => continue,
|
||||
};
|
||||
if (is_add || is_set) && checked.insert(key) && !had_dup.contains(key) {
|
||||
if let Some(v) = self.root.get(key) {
|
||||
let relevant = is_add || v.as_array().is_some_and(|a| !a.is_empty()) && is_id_list(v);
|
||||
if relevant && is_id_list(v) && !unique_ids(v.as_array().unwrap()) {
|
||||
problems.push(format!("Doppelte ids in „{key}\"."));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if problems.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
for (k, old) in saved {
|
||||
match old {
|
||||
Some(v) => {
|
||||
self.root.insert(k, v);
|
||||
}
|
||||
None => {
|
||||
self.root.shift_remove(&k);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(problems)
|
||||
}
|
||||
|
||||
/// Einen Schritt zurück; liefert die angewendeten Ops (für die TS-Leseansicht), `None` = nichts.
|
||||
pub fn undo(&mut self) -> Option<Vec<Op>> {
|
||||
let step = self.history.pop_undo()?;
|
||||
self.apply_unchecked(&step.inverse);
|
||||
let ops = step.inverse.clone();
|
||||
self.history.push_redo(step);
|
||||
Some(ops)
|
||||
}
|
||||
|
||||
/// Einen Schritt vor; liefert die angewendeten Ops, `None` = nichts.
|
||||
pub fn redo(&mut self) -> Option<Vec<Op>> {
|
||||
let step = self.history.pop_redo()?;
|
||||
self.apply_unchecked(&step.forward);
|
||||
let ops = step.forward.clone();
|
||||
self.history.push_undo(step);
|
||||
Some(ops)
|
||||
}
|
||||
|
||||
pub fn history(&self) -> &History {
|
||||
&self.history
|
||||
}
|
||||
|
||||
pub fn history_mut(&mut self) -> &mut History {
|
||||
&mut self.history
|
||||
}
|
||||
}
|
||||
|
||||
@@ -325,4 +366,186 @@ mod tests {
|
||||
assert!(Op::from_json(&json!({"kind":"add","collection":"w","items":[{"x":1}]})).is_err());
|
||||
assert!(Op::from_json(&json!({"kind":"nope"})).is_err());
|
||||
}
|
||||
|
||||
/// Deterministischer Zufall (LCG wie in den TS-Tests).
|
||||
struct Rng(u64);
|
||||
impl Rng {
|
||||
fn next(&mut self) -> f64 {
|
||||
self.0 = (self.0.wrapping_mul(1664525).wrapping_add(1013904223)) % 4294967296;
|
||||
self.0 as f64 / 4294967296.0
|
||||
}
|
||||
fn below(&mut self, n: usize) -> usize {
|
||||
((self.next() * n as f64) as usize).min(n.saturating_sub(1))
|
||||
}
|
||||
}
|
||||
|
||||
fn ids(d: &Document, c: &str) -> Vec<String> {
|
||||
d.field(c).and_then(Value::as_array).map(|a| a.iter().filter_map(id_of).map(str::to_owned).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Zufällige Op-Folge auf dem aktuellen Stand (manchmal mit Verstoss: doppelte id, NaN).
|
||||
fn random_ops(d: &Document, r: &mut Rng, n: usize) -> Vec<Op> {
|
||||
let mut out = Vec::new();
|
||||
let colls = ["walls", "ceilings", "rooms", "neu"];
|
||||
for k in 0..1 + r.below(3) {
|
||||
let c = colls[r.below(colls.len())].to_owned();
|
||||
let cur = ids(d, &c);
|
||||
let pick = r.next();
|
||||
let op = if pick < 0.25 || cur.is_empty() {
|
||||
let at = if r.next() < 0.5 { Some(r.below(cur.len() + 2)) } else { None };
|
||||
let id = if r.next() < 0.03 && !cur.is_empty() { cur[0].clone() } else { format!("z{n}-{k}") };
|
||||
let h = if r.next() < 0.03 { json!("\u{1}NaN") } else { json!(r.next()) };
|
||||
json!({"kind":"add","collection":c,"items":[{"id":id,"h":h}],"at":at})
|
||||
} else if pick < 0.5 {
|
||||
let id = &cur[r.below(cur.len())];
|
||||
json!({"kind":"replace","collection":c,"entity":{"id":id,"h":r.next(),"n":n}})
|
||||
} else if pick < 0.65 {
|
||||
let mut drop = vec![cur[r.below(cur.len())].clone()];
|
||||
if r.next() < 0.5 {
|
||||
drop.push(cur[r.below(cur.len())].clone());
|
||||
}
|
||||
json!({"kind":"remove","collection":c,"ids":drop})
|
||||
} else if pick < 0.75 {
|
||||
let mut p = cur.clone();
|
||||
for i in (1..p.len()).rev() {
|
||||
p.swap(i, r.below(i + 1));
|
||||
}
|
||||
p.truncate(1 + r.below(p.len()));
|
||||
json!({"kind":"reorder","collection":c,"ids":p})
|
||||
} else if pick < 0.85 {
|
||||
json!({"kind":"setField","key":"name","value":format!("n{n}")})
|
||||
} else if pick < 0.92 {
|
||||
if d.field("extra").is_some() {
|
||||
json!({"kind":"setField","key":"extra"})
|
||||
} else {
|
||||
json!({"kind":"setField","key":"extra","value":{"v":n}})
|
||||
}
|
||||
} else {
|
||||
// Ganze Liste setzen (auch Liste mit Alt-Doppelungen → Feld-Sicherung als Inverse).
|
||||
let dup = r.next() < 0.3;
|
||||
json!({"kind":"setField","key":c,"value":[{"id":"s1"},{"id": if dup {"s1"} else {"s2"}}]})
|
||||
};
|
||||
out.push(Op::from_json(&op).unwrap());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tausend_zufallsaenderungen_undo_redo_exakt() {
|
||||
let text = include_str!("../tests/fixtures/sample_project.json");
|
||||
let mut d = Document::from_json(text).unwrap();
|
||||
d.history_mut().max_steps = 5000;
|
||||
let start = d.to_json();
|
||||
let mut r = Rng(7);
|
||||
let mut committed = 0;
|
||||
let mut rejected = 0;
|
||||
for n in 0..1000 {
|
||||
let ops = random_ops(&d, &mut r, n);
|
||||
let before = d.to_json();
|
||||
// Ohne Schlüssel: jede Änderung ein Schritt.
|
||||
match d.commit(&ops, None, n as f64 * 1000.0, true) {
|
||||
Ok(()) => committed += 1,
|
||||
Err(_) => {
|
||||
rejected += 1;
|
||||
assert_eq!(d.to_json(), before, "Rücknahme bei Verstoss");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(rejected > 0 && committed > 900, "{committed}/{rejected}");
|
||||
let end = d.to_json();
|
||||
assert_eq!(d.history().undo_depth(), committed);
|
||||
while d.undo().is_some() {}
|
||||
assert_eq!(d.to_json(), start);
|
||||
while d.redo().is_some() {}
|
||||
assert_eq!(d.to_json(), end);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coalesce_key_ein_schritt_und_verdichtet() {
|
||||
let mut d = doc();
|
||||
let start = d.to_json();
|
||||
for i in 0..500 {
|
||||
let o = ops(json!([{"kind":"replace","collection":"walls","entity":{"id":"a","x":i}}]));
|
||||
d.commit(&o, Some("drag"), i as f64, false).unwrap();
|
||||
}
|
||||
assert_eq!(d.history().undo_depth(), 1);
|
||||
// Der Schritt wächst nicht mit jeder Mausbewegung.
|
||||
assert!(d.history().bytes() < 1000, "{}", d.history().bytes());
|
||||
d.commit(&ops(json!([{"kind":"setField","key":"name","value":"Q"}])), Some("drag"), 499.0, false).unwrap();
|
||||
assert_eq!(d.history().undo_depth(), 1);
|
||||
d.undo().unwrap();
|
||||
assert_eq!(d.to_json(), start);
|
||||
// Nach Undo beginnt dieselbe Serie einen neuen Schritt.
|
||||
d.redo().unwrap();
|
||||
d.commit(&ops(json!([{"kind":"setField","key":"name","value":"R"}])), Some("drag"), 500.0, false).unwrap();
|
||||
assert_eq!(d.history().undo_depth(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nan_und_doppelte_ids_abgelehnt_ohne_schritt() {
|
||||
let mut d = doc();
|
||||
let before = d.to_json();
|
||||
let e = d.commit(&ops(json!([{"kind":"replace","collection":"walls","entity":{"id":"a","x":"\u{1}NaN"}}])), None, 0.0, true).unwrap_err();
|
||||
assert_eq!(e, vec!["„walls\" a: NaN ist nicht endlich.".to_string()]);
|
||||
let e = d.commit(&ops(json!([{"kind":"add","collection":"walls","items":[{"id":"b"}]}])), None, 0.0, false).unwrap_err();
|
||||
assert_eq!(e, vec!["Doppelte ids in „walls\".".to_string()]);
|
||||
assert_eq!(d.to_json(), before);
|
||||
assert_eq!(d.history().undo_depth(), 0);
|
||||
// Tiefe Marken werden angenommen und als null gespeichert.
|
||||
d.commit(&ops(json!([{"kind":"replace","collection":"walls","entity":{"id":"a","p":{"q":{"r":{"s":{"t":"\u{1}NaN"}}}}}}])), None, 0.0, true).unwrap();
|
||||
assert_eq!(d.field("walls").unwrap()[0]["p"]["q"]["r"]["s"]["t"], Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feld_reihenfolge_bleibt_beim_undo() {
|
||||
let mut d = doc();
|
||||
let start = d.to_json();
|
||||
d.commit(&ops(json!([{"kind":"setField","key":"walls"}])), None, 0.0, false).unwrap();
|
||||
d.commit(&ops(json!([{"kind":"setField","key":"walls","value":[]}])), None, 1.0, false).unwrap();
|
||||
d.undo().unwrap();
|
||||
d.undo().unwrap();
|
||||
assert_eq!(d.to_json(), start);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn speichergrenze_wirft_aelteste_schritte() {
|
||||
let mut d = doc();
|
||||
d.history_mut().max_bytes = 20_000;
|
||||
let big: Vec<Value> = (0..10).map(|i| json!({"id": format!("e{i}"), "pad": "x".repeat(100)})).collect();
|
||||
for i in 0..20 {
|
||||
d.commit(&ops(json!([{"kind":"setField","key":"blob","value":big.clone()}, {"kind":"setField","key":"i","value":i}])), None, i as f64 * 1000.0, false).unwrap();
|
||||
}
|
||||
assert!(d.history().bytes() <= 20_000 && d.history().undo_depth() < 20 && d.history().undo_depth() >= 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Messung: cargo test --release -- --ignored --nocapture"]
|
||||
fn messung_grosses_projekt() {
|
||||
use std::time::Instant;
|
||||
let walls: Vec<Value> = (0..5000)
|
||||
.map(|i| json!({"id": format!("w{i}"), "start": {"x": i, "y": 0}, "end": {"x": i + 1, "y": 0}, "thickness": 0.2, "height": 2.6, "layers": [{"m":"a","t":0.1},{"m":"b","t":0.1}]}))
|
||||
.collect();
|
||||
let mut d = Document::from_json(&json!({"id":"p","walls":walls}).to_string()).unwrap();
|
||||
d.history_mut().max_steps = 10_000;
|
||||
let t = Instant::now();
|
||||
let n = 5000;
|
||||
for i in 0..n {
|
||||
let o = ops(json!([{"kind":"replace","collection":"walls","entity":{"id": format!("w{}", (i * 7) % 5000), "height": i}}]));
|
||||
d.commit(&o, None, i as f64 * 1000.0, false).unwrap();
|
||||
}
|
||||
let commit = t.elapsed();
|
||||
let t = Instant::now();
|
||||
while d.undo().is_some() {}
|
||||
let undo = t.elapsed();
|
||||
let t = Instant::now();
|
||||
while d.redo().is_some() {}
|
||||
let redo = t.elapsed();
|
||||
eprintln!(
|
||||
"5000 Wände, {n} Schritte: commit {:.1} µs/Schritt, undo {:.1} µs, redo {:.1} µs, Verlauf ≈ {} KiB",
|
||||
commit.as_secs_f64() * 1e6 / n as f64,
|
||||
undo.as_secs_f64() * 1e6 / n as f64,
|
||||
redo.as_secs_f64() * 1e6 / n as f64,
|
||||
d.history().bytes() / 1024
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,7 @@ pub mod opening_geom;
|
||||
pub mod plan_openings;
|
||||
pub mod delaunay;
|
||||
pub mod document;
|
||||
pub mod ops;
|
||||
pub mod mesh_section;
|
||||
pub mod model;
|
||||
pub mod model3d;
|
||||
|
||||
@@ -0,0 +1,599 @@
|
||||
//! Ops, Validierung und Undo/Redo-Verlauf ([K4] S3, [7], [8]).
|
||||
//!
|
||||
//! Eine [`Op`] ist eine Änderung am Projekt (Spiegel von `CoreOp` in `src/core/ops.ts`). Das
|
||||
//! Dokument (`document.rs`) wendet Op-Folgen atomar an, prüft sie hier ([`validate`], gleiche
|
||||
//! Ablehnungen und Meldungen wie die frühere TS-Fassung `validateOps`) und hält den Verlauf
|
||||
//! ([`History`]): je Schritt die Vorwärts-Ops und die inversen Ops — keine Projekt-Schnappschüsse.
|
||||
//!
|
||||
//! Nicht endliche Zahlen: JSON kennt weder NaN noch ±Infinity. TS kodiert sie beim Senden als
|
||||
//! Marken-Text `"\u{1}NaN"`, `"\u{1}Infinity"`, `"\u{1}-Infinity"` (s. `opsToJson` in
|
||||
//! `core/document.ts`), damit die Prüfung sie sieht. Was trotzdem angenommen wird (tiefer als die
|
||||
//! Prüfung schaut), wird als `null` gespeichert — wie `JSON.stringify` es täte.
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
|
||||
/// Zeitfenster, in dem Änderungen mit gleichem `coalesceKey` zu einem Undo-Schritt verschmelzen (ms).
|
||||
pub const COALESCE_WINDOW_MS: f64 = 400.0;
|
||||
|
||||
/// Eine Änderung am Projekt.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Op {
|
||||
/// Fügt Elemente an `at` (Default: Ende) in die Liste `collection` ein.
|
||||
Add { collection: String, items: Vec<Value>, at: Option<usize> },
|
||||
/// Ersetzt das Element mit gleicher id (fehlt es, wird angehängt).
|
||||
Replace { collection: String, entity: Value },
|
||||
/// Entfernt Elemente per id.
|
||||
Remove { collection: String, ids: Vec<String> },
|
||||
/// Setzt die Reihenfolge (genannte ids zuerst, der Rest dahinter).
|
||||
Reorder { collection: String, ids: Vec<String> },
|
||||
/// Setzt ein Feld (`None` = entfernen). `at`: Position, falls das Feld neu eingefügt wird
|
||||
/// (Undo stellt so auch die Feld-Reihenfolge wieder her).
|
||||
SetField { key: String, value: Option<Value>, at: Option<usize> },
|
||||
}
|
||||
|
||||
pub(crate) fn id_of(v: &Value) -> Option<&str> {
|
||||
let o = v.as_object()?;
|
||||
// Schnellweg: `id` steht fast immer zuerst (spart das Hashen bei langen Listen).
|
||||
match o.iter().next() {
|
||||
Some((k, id)) if k == "id" => id.as_str(),
|
||||
_ => o.get("id").and_then(Value::as_str),
|
||||
}
|
||||
}
|
||||
|
||||
fn index_arg(v: Option<&Value>, what: &str) -> Result<Option<usize>, String> {
|
||||
match v {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
// Wie JS `slice`: Bruchteile abschneiden, negativ → 0.
|
||||
Some(a) => a.as_f64().filter(|x| x.is_finite()).map(|x| Some(x.max(0.0) as usize)).ok_or(format!("{what} ungültig")),
|
||||
}
|
||||
}
|
||||
|
||||
impl Op {
|
||||
pub fn from_json(v: &Value) -> Result<Op, String> {
|
||||
let kind = v.get("kind").and_then(Value::as_str).ok_or("Op ohne kind")?;
|
||||
let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_owned).ok_or(format!("Op {kind}: {k} fehlt"));
|
||||
let ids = |k: &str| -> Result<Vec<String>, String> {
|
||||
v.get(k)
|
||||
.and_then(Value::as_array)
|
||||
.ok_or(format!("Op {kind}: {k} fehlt"))?
|
||||
.iter()
|
||||
.map(|x| x.as_str().map(str::to_owned).ok_or(format!("Op {kind}: {k} enthält Nicht-Text")))
|
||||
.collect()
|
||||
};
|
||||
Ok(match kind {
|
||||
"add" => {
|
||||
let items = v.get("items").and_then(Value::as_array).ok_or("Op add: items fehlt")?.clone();
|
||||
if items.iter().any(|e| id_of(e).is_none()) {
|
||||
return Err("Op add: Element ohne id".into());
|
||||
}
|
||||
Op::Add { collection: s("collection")?, items, at: index_arg(v.get("at"), "Op add: at")? }
|
||||
}
|
||||
"replace" => {
|
||||
let entity = v.get("entity").cloned().ok_or("Op replace: entity fehlt")?;
|
||||
if id_of(&entity).is_none() {
|
||||
return Err("Op replace: Element ohne id".into());
|
||||
}
|
||||
Op::Replace { collection: s("collection")?, entity }
|
||||
}
|
||||
"remove" => Op::Remove { collection: s("collection")?, ids: ids("ids")? },
|
||||
"reorder" => Op::Reorder { collection: s("collection")?, ids: ids("ids")? },
|
||||
// `value: null` ist ein Wert (TS setzt das Feld auf null); fehlend = entfernen.
|
||||
"setField" => Op::SetField { key: s("key")?, value: v.get("value").cloned(), at: index_arg(v.get("at"), "Op setField: at")? },
|
||||
other => return Err(format!("Unbekannte Op: {other}")),
|
||||
})
|
||||
}
|
||||
|
||||
/// JSON-Form wie `CoreOp` in TS.
|
||||
pub fn to_json(&self) -> Value {
|
||||
let mut m = Map::new();
|
||||
let mut put = |k: &str, v: Value| {
|
||||
m.insert(k.to_owned(), v);
|
||||
};
|
||||
match self {
|
||||
Op::Add { collection, items, at } => {
|
||||
put("kind", "add".into());
|
||||
put("collection", collection.as_str().into());
|
||||
put("items", Value::Array(items.clone()));
|
||||
if let Some(a) = at {
|
||||
put("at", (*a as u64).into());
|
||||
}
|
||||
}
|
||||
Op::Replace { collection, entity } => {
|
||||
put("kind", "replace".into());
|
||||
put("collection", collection.as_str().into());
|
||||
put("entity", entity.clone());
|
||||
}
|
||||
Op::Remove { collection, ids } | Op::Reorder { collection, ids } => {
|
||||
put("kind", if matches!(self, Op::Remove { .. }) { "remove" } else { "reorder" }.into());
|
||||
put("collection", collection.as_str().into());
|
||||
put("ids", ids.iter().map(|s| Value::from(s.as_str())).collect());
|
||||
}
|
||||
Op::SetField { key, value, at } => {
|
||||
put("kind", "setField".into());
|
||||
put("key", key.as_str().into());
|
||||
if let Some(v) = value {
|
||||
put("value", v.clone());
|
||||
}
|
||||
if let Some(a) = at {
|
||||
put("at", (*a as u64).into());
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
/// Das Projekt-Feld, das die Op ändert.
|
||||
pub fn key(&self) -> &str {
|
||||
match self {
|
||||
Op::Add { collection, .. } | Op::Replace { collection, .. } | Op::Remove { collection, .. } | Op::Reorder { collection, .. } => collection,
|
||||
Op::SetField { key, .. } => key,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Op-Liste aus JSON (Array).
|
||||
pub fn ops_from_json(v: &Value) -> Result<Vec<Op>, String> {
|
||||
v.as_array().ok_or("Ops sind kein Array".to_string())?.iter().map(Op::from_json).collect()
|
||||
}
|
||||
|
||||
/// Op-Liste als JSON-Text.
|
||||
pub fn ops_to_json(ops: &[Op]) -> String {
|
||||
Value::Array(ops.iter().map(Op::to_json).collect()).to_string()
|
||||
}
|
||||
|
||||
// ── Listen-Hilfen ────────────────────────────────────────────────────────────
|
||||
|
||||
/// Liste mit lauter `id`-tragenden Elementen (leer zählt mit) — `isIdList` in TS.
|
||||
pub fn is_id_list(v: &Value) -> bool {
|
||||
v.as_array().is_some_and(|a| a.iter().all(|e| id_of(e).is_some()))
|
||||
}
|
||||
|
||||
/// Nicht leere Liste mit lauter ids — `isEntityList` in TS.
|
||||
fn is_entity_list(v: &Value) -> bool {
|
||||
v.as_array().is_some_and(|a| !a.is_empty()) && is_id_list(v)
|
||||
}
|
||||
|
||||
pub fn unique_ids(list: &[Value]) -> bool {
|
||||
let mut seen = HashSet::new();
|
||||
list.iter().all(|e| seen.insert(id_of(e).unwrap_or("")))
|
||||
}
|
||||
|
||||
/// Liste mit alten Doppelungen (Alt-Dateien bleiben änderbar: nur NEUE Doppelungen zählen).
|
||||
pub fn has_dup(v: Option<&Value>) -> bool {
|
||||
match v {
|
||||
Some(v) if is_id_list(v) => !unique_ids(v.as_array().unwrap()),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Nicht endliche Zahlen ────────────────────────────────────────────────────
|
||||
|
||||
/// Text einer Nicht-endlich-Marke (`"\u{1}NaN"` → `"NaN"`).
|
||||
pub fn non_finite_mark(v: &Value) -> Option<&str> {
|
||||
match v.as_str()?.strip_prefix('\u{1}')? {
|
||||
t @ ("NaN" | "Infinity" | "-Infinity") => Some(t),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `findNonFinite` aus TS: Suche bis Tiefe 3, grosse Zahlenfelder (> 5000) werden übersprungen.
|
||||
fn find_non_finite(v: &Value, depth: u32) -> Option<&str> {
|
||||
if let Some(t) = non_finite_mark(v) {
|
||||
return Some(t);
|
||||
}
|
||||
if depth > 3 {
|
||||
return None;
|
||||
}
|
||||
match v {
|
||||
Value::Array(a) if a.len() > 5000 => None,
|
||||
Value::Array(a) => a.iter().find_map(|x| find_non_finite(x, depth + 1)),
|
||||
Value::Object(o) => o.values().find_map(|x| find_non_finite(x, depth + 1)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Ersetzt Nicht-endlich-Marken durch `null` (Speicherform, wie `JSON.stringify`).
|
||||
pub fn sanitize_non_finite(v: &mut Value) {
|
||||
match v {
|
||||
Value::String(_) if non_finite_mark(v).is_some() => *v = Value::Null,
|
||||
Value::Array(a) => a.iter_mut().for_each(sanitize_non_finite),
|
||||
Value::Object(o) => o.values_mut().for_each(sanitize_non_finite),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn op_values_mut(op: &mut Op) -> Vec<&mut Value> {
|
||||
match op {
|
||||
Op::Add { items, .. } => items.iter_mut().collect(),
|
||||
Op::Replace { entity, .. } => vec![entity],
|
||||
Op::SetField { value: Some(v), .. } => vec![v],
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn sanitize_ops(ops: &mut [Op]) {
|
||||
for op in ops {
|
||||
op_values_mut(op).into_iter().for_each(sanitize_non_finite);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Validierung ([7]) ────────────────────────────────────────────────────────
|
||||
|
||||
/// Prüft eine angewendete Op-Folge (bitgleich zur früheren TS-Fassung `validateOps`): nicht
|
||||
/// endliche Zahlen in neuen/ersetzten Elementen und `setField`-Zahlen, neue doppelte ids in den
|
||||
/// Listen, in die eingefügt wurde. `after` = Projekt nach den Ops, `had_dup(key)` = die Liste hatte
|
||||
/// vorher schon Doppelungen.
|
||||
pub fn validate(after: &Map<String, Value>, ops: &[Op], had_dup: &dyn Fn(&str) -> bool) -> Vec<String> {
|
||||
let mut problems = Vec::new();
|
||||
let mut dup_checked: HashSet<&str> = HashSet::new();
|
||||
for op in ops {
|
||||
match op {
|
||||
Op::Add { collection, .. } | Op::Replace { collection, .. } => {
|
||||
let ents: &[Value] = match op {
|
||||
Op::Add { items, .. } => items,
|
||||
Op::Replace { entity, .. } => std::slice::from_ref(entity),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
for e in ents {
|
||||
if let Some(bad) = find_non_finite(e, 0) {
|
||||
problems.push(format!("„{collection}\" {}: {bad} ist nicht endlich.", id_of(e).unwrap_or("undefined")));
|
||||
}
|
||||
}
|
||||
if matches!(op, Op::Add { .. }) && dup_checked.insert(collection) {
|
||||
if let Some(list) = after.get(collection) {
|
||||
if is_id_list(list) && !unique_ids(list.as_array().unwrap()) && !had_dup(collection) {
|
||||
problems.push(format!("Doppelte ids in „{collection}\"."));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Op::SetField { key, value, .. } => {
|
||||
if let Some(bad) = value.as_ref().and_then(non_finite_mark) {
|
||||
problems.push(format!("Feld „{key}\": {bad} ist nicht endlich."));
|
||||
} else if let Some(v) = value {
|
||||
if is_entity_list(v) && !unique_ids(v.as_array().unwrap()) && !had_dup(key) {
|
||||
problems.push(format!("Doppelte ids in „{key}\"."));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
problems
|
||||
}
|
||||
|
||||
/// Wie [`validate`] mit dem Projekt vor den Ops (für die TS-Fassade `validateOps`).
|
||||
pub fn validate_ops(after: &Map<String, Value>, ops: &[Op], before: Option<&Map<String, Value>>) -> Vec<String> {
|
||||
validate(after, ops, &|k| before.is_some_and(|b| has_dup(b.get(k))))
|
||||
}
|
||||
|
||||
/// Prüft ein ganzes Projekt (`validateProject`): doppelte ids und nicht endliche Zahlen je Liste.
|
||||
pub fn validate_project(root: &Map<String, Value>) -> Vec<String> {
|
||||
let mut problems = Vec::new();
|
||||
for (key, v) in root {
|
||||
if !is_entity_list(v) {
|
||||
continue;
|
||||
}
|
||||
let list = v.as_array().unwrap();
|
||||
if !unique_ids(list) {
|
||||
problems.push(format!("Doppelte ids in „{key}\"."));
|
||||
}
|
||||
for e in list {
|
||||
if let Some(bad) = find_non_finite(e, 0) {
|
||||
problems.push(format!("„{key}\" {}: {bad} ist nicht endlich.", id_of(e).unwrap_or("undefined")));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
problems
|
||||
}
|
||||
|
||||
// ── Verlauf ([8]) ────────────────────────────────────────────────────────────
|
||||
|
||||
/// Ein Undo-Schritt: Vorwärts-Ops (Redo) und inverse Ops (Undo), beide in Anwendungsreihenfolge.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Step {
|
||||
pub forward: Vec<Op>,
|
||||
pub inverse: Vec<Op>,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
/// Geschätzter Speicherbedarf eines JSON-Werts (Bytes).
|
||||
fn approx_bytes(v: &Value) -> usize {
|
||||
match v {
|
||||
Value::String(s) => 24 + s.len(),
|
||||
Value::Array(a) => 24 + a.iter().map(approx_bytes).sum::<usize>(),
|
||||
Value::Object(o) => 64 + o.iter().map(|(k, v)| 24 + k.len() + approx_bytes(v)).sum::<usize>(),
|
||||
_ => 16,
|
||||
}
|
||||
}
|
||||
|
||||
fn ops_bytes(ops: &[Op]) -> usize {
|
||||
ops.iter()
|
||||
.map(|op| {
|
||||
48 + op.key().len()
|
||||
+ match op {
|
||||
Op::Add { items, .. } => items.iter().map(approx_bytes).sum(),
|
||||
Op::Replace { entity, .. } => approx_bytes(entity),
|
||||
Op::Remove { ids, .. } | Op::Reorder { ids, .. } => ids.iter().map(|s| 24 + s.len()).sum(),
|
||||
Op::SetField { value, .. } => value.as_ref().map_or(0, approx_bytes),
|
||||
}
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Streicht Ops, die eine spätere Op derselben Folge vollständig überschreibt (Drag/Regler-Serien
|
||||
/// wachsen so nicht mit jeder Mausbewegung): `replace` desselben Elements ohne Struktur-Op auf der
|
||||
/// Liste dazwischen, `setField` desselben Felds mit gleicher Einfüge-Position. Alle aufgezeichneten
|
||||
/// `replace` treffen ein vorhandenes Element (s. `Document::apply_recorded`), daher ist das exakt.
|
||||
pub fn compact(ops: Vec<Op>) -> Vec<Op> {
|
||||
let mut keep = vec![true; ops.len()];
|
||||
{
|
||||
let mut later_set: HashMap<&str, Option<usize>> = HashMap::new();
|
||||
let mut later_replaced: HashMap<&str, HashSet<&str>> = HashMap::new();
|
||||
for (i, op) in ops.iter().enumerate().rev() {
|
||||
let k = op.key();
|
||||
match op {
|
||||
Op::SetField { value: Some(_), at, .. } => {
|
||||
if later_set.get(k) == Some(at) {
|
||||
keep[i] = false;
|
||||
} else {
|
||||
later_set.insert(k, *at);
|
||||
later_replaced.remove(k);
|
||||
}
|
||||
}
|
||||
Op::Replace { entity, .. } => {
|
||||
later_set.remove(k);
|
||||
if !later_replaced.entry(k).or_default().insert(id_of(entity).unwrap_or("")) {
|
||||
keep[i] = false;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
later_set.remove(k);
|
||||
later_replaced.remove(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if keep.iter().all(|&k| k) {
|
||||
return ops;
|
||||
}
|
||||
ops.into_iter().zip(keep).filter_map(|(op, k)| k.then_some(op)).collect()
|
||||
}
|
||||
|
||||
/// Undo/Redo-Stapel. Gleicher `coalesceKey` innerhalb von [`COALESCE_WINDOW_MS`] = ein Schritt;
|
||||
/// Gruppen (`begin_group`/`end_group`) fassen beliebige Änderungen zu einem Schritt zusammen.
|
||||
/// Begrenzt auf `max_steps` Schritte und (ungefähr) `max_bytes` Speicher — die ältesten fallen weg.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct History {
|
||||
undo: VecDeque<Step>,
|
||||
redo: Vec<Step>,
|
||||
last_key: Option<String>,
|
||||
last_at: f64,
|
||||
group_depth: u32,
|
||||
/// In einer offenen Gruppe: der erste Schritt steht schon (weitere verschmelzen damit).
|
||||
group_started: bool,
|
||||
bytes: usize,
|
||||
pub max_steps: usize,
|
||||
pub max_bytes: usize,
|
||||
}
|
||||
|
||||
impl Default for History {
|
||||
fn default() -> Self {
|
||||
History {
|
||||
undo: VecDeque::new(),
|
||||
redo: Vec::new(),
|
||||
last_key: None,
|
||||
last_at: 0.0,
|
||||
group_depth: 0,
|
||||
group_started: false,
|
||||
bytes: 0,
|
||||
max_steps: 100,
|
||||
max_bytes: 256 << 20,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl History {
|
||||
pub fn undo_depth(&self) -> usize {
|
||||
self.undo.len()
|
||||
}
|
||||
pub fn redo_depth(&self) -> usize {
|
||||
self.redo.len()
|
||||
}
|
||||
/// Geschätzter Speicher aller Schritte (Bytes).
|
||||
pub fn bytes(&self) -> usize {
|
||||
self.bytes
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.undo.clear();
|
||||
self.redo.clear();
|
||||
self.bytes = 0;
|
||||
self.last_key = None;
|
||||
self.group_depth = 0;
|
||||
self.group_started = false;
|
||||
}
|
||||
|
||||
pub fn begin_group(&mut self) {
|
||||
if self.group_depth == 0 {
|
||||
self.group_started = false;
|
||||
}
|
||||
self.group_depth += 1;
|
||||
}
|
||||
|
||||
pub fn end_group(&mut self) {
|
||||
self.group_depth = self.group_depth.saturating_sub(1);
|
||||
if self.group_depth == 0 {
|
||||
// Die nächste Änderung beginnt einen eigenen Schritt, auch mit gleichem Schlüssel.
|
||||
self.last_key = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Zeichnet eine angewendete Änderung auf.
|
||||
pub fn record(&mut self, forward: Vec<Op>, inverse: Vec<Op>, key: Option<&str>, now: f64) {
|
||||
for s in self.redo.drain(..) {
|
||||
self.bytes -= s.bytes;
|
||||
}
|
||||
let coalesced = key.is_some() && key == self.last_key.as_deref() && now - self.last_at < COALESCE_WINDOW_MS;
|
||||
self.last_key = key.map(str::to_owned);
|
||||
self.last_at = now;
|
||||
let merge = if self.group_depth > 0 { std::mem::replace(&mut self.group_started, true) } else { coalesced };
|
||||
match self.undo.back_mut().filter(|_| merge) {
|
||||
Some(top) => {
|
||||
self.bytes -= top.bytes;
|
||||
let mut fwd = std::mem::take(&mut top.forward);
|
||||
fwd.extend(forward);
|
||||
top.forward = compact(fwd);
|
||||
let mut inv = inverse;
|
||||
inv.append(&mut top.inverse);
|
||||
top.inverse = compact(inv);
|
||||
top.bytes = ops_bytes(&top.forward) + ops_bytes(&top.inverse);
|
||||
self.bytes += top.bytes;
|
||||
}
|
||||
None => {
|
||||
let bytes = ops_bytes(&forward) + ops_bytes(&inverse);
|
||||
self.bytes += bytes;
|
||||
self.undo.push_back(Step { forward, inverse, bytes });
|
||||
}
|
||||
}
|
||||
while self.undo.len() > self.max_steps || (self.bytes > self.max_bytes && self.undo.len() > 1) {
|
||||
let s = self.undo.pop_front().expect("nicht leer");
|
||||
self.bytes -= s.bytes;
|
||||
}
|
||||
}
|
||||
|
||||
/// Nimmt den jüngsten Schritt vom Undo-Stapel (der Aufrufer wendet `inverse` an und legt ihn
|
||||
/// mit [`History::push_redo`] ab).
|
||||
pub fn pop_undo(&mut self) -> Option<Step> {
|
||||
self.group_depth = 0;
|
||||
self.last_key = None;
|
||||
let s = self.undo.pop_back()?;
|
||||
self.bytes -= s.bytes;
|
||||
Some(s)
|
||||
}
|
||||
pub fn push_redo(&mut self, s: Step) {
|
||||
self.bytes += s.bytes;
|
||||
self.redo.push(s);
|
||||
}
|
||||
pub fn pop_redo(&mut self) -> Option<Step> {
|
||||
self.group_depth = 0;
|
||||
self.last_key = None;
|
||||
let s = self.redo.pop()?;
|
||||
self.bytes -= s.bytes;
|
||||
Some(s)
|
||||
}
|
||||
pub fn push_undo(&mut self, s: Step) {
|
||||
self.bytes += s.bytes;
|
||||
self.undo.push_back(s);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn obj(v: Value) -> Map<String, Value> {
|
||||
v.as_object().unwrap().clone()
|
||||
}
|
||||
fn ops(v: Value) -> Vec<Op> {
|
||||
ops_from_json(&v).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_hin_und_zurueck() {
|
||||
let v = json!([
|
||||
{"kind":"add","collection":"walls","items":[{"id":"a"}],"at":2},
|
||||
{"kind":"replace","collection":"walls","entity":{"id":"a","x":1}},
|
||||
{"kind":"remove","collection":"walls","ids":["a"]},
|
||||
{"kind":"reorder","collection":"walls","ids":["b","a"]},
|
||||
{"kind":"setField","key":"name","value":"N"},
|
||||
{"kind":"setField","key":"name","value":null,"at":3},
|
||||
{"kind":"setField","key":"name"},
|
||||
]);
|
||||
assert_eq!(serde_json::from_str::<Value>(&ops_to_json(&ops(v.clone()))).unwrap(), v);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn meldungen_wie_ts() {
|
||||
let before = obj(json!({"walls":[{"id":"a"}],"old":[{"id":"x"},{"id":"x"}]}));
|
||||
let after = obj(json!({"walls":[{"id":"a"},{"id":"a","h":"\u{1}NaN"}],"old":[{"id":"x"},{"id":"x"},{"id":"y"}]}));
|
||||
let o = ops(json!([
|
||||
{"kind":"add","collection":"walls","items":[{"id":"a","h":"\u{1}NaN"}]},
|
||||
{"kind":"add","collection":"old","items":[{"id":"y"}]},
|
||||
{"kind":"replace","collection":"walls","entity":{"id":"a","p":{"q":[1,"\u{1}-Infinity"]}}},
|
||||
{"kind":"setField","key":"scale","value":"\u{1}Infinity"},
|
||||
{"kind":"setField","key":"levels","value":[{"id":"l"},{"id":"l"}]},
|
||||
]));
|
||||
assert_eq!(
|
||||
validate_ops(&after, &o, Some(&before)),
|
||||
vec![
|
||||
"„walls\" a: NaN ist nicht endlich.",
|
||||
"Doppelte ids in „walls\".",
|
||||
"„walls\" a: -Infinity ist nicht endlich.",
|
||||
"Feld „scale\": Infinity ist nicht endlich.",
|
||||
"Doppelte ids in „levels\".",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiefe_und_grosse_felder_wie_ts() {
|
||||
// Tiefe 4 wird noch geprüft (Zahl vor der Tiefenprüfung), Tiefe 5 nicht.
|
||||
let deep4 = json!({"id":"a","b":{"c":{"d":{"e":"\u{1}NaN"}}}});
|
||||
let deep5 = json!({"id":"a","b":{"c":{"d":{"e":{"f":"\u{1}NaN"}}}}});
|
||||
assert!(find_non_finite(&deep4, 0).is_some());
|
||||
assert!(find_non_finite(&deep5, 0).is_none());
|
||||
let mut big = vec![json!(0); 5001];
|
||||
big[3] = json!("\u{1}NaN");
|
||||
assert!(find_non_finite(&json!({"id":"a","m":big}), 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projekt_pruefung() {
|
||||
let p = obj(json!({"walls":[{"id":"a","h":"\u{1}NaN"},{"id":"a"}],"levels":[],"name":"x"}));
|
||||
assert_eq!(validate_project(&p), vec!["Doppelte ids in „walls\".", "„walls\" a: NaN ist nicht endlich."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verdichtung() {
|
||||
let o = ops(json!([
|
||||
{"kind":"replace","collection":"walls","entity":{"id":"a","x":1}},
|
||||
{"kind":"replace","collection":"walls","entity":{"id":"b","x":1}},
|
||||
{"kind":"replace","collection":"walls","entity":{"id":"a","x":2}},
|
||||
{"kind":"setField","key":"s","value":1},
|
||||
{"kind":"setField","key":"s","value":2},
|
||||
{"kind":"remove","collection":"walls","ids":["c"]},
|
||||
{"kind":"replace","collection":"walls","entity":{"id":"a","x":3}},
|
||||
]));
|
||||
let c = compact(o.clone());
|
||||
assert_eq!(c.len(), 5);
|
||||
assert_eq!(c[0], o[1]);
|
||||
assert_eq!(c[1], o[2]);
|
||||
assert_eq!(c[2], o[4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verlauf_koalesziert_und_begrenzt() {
|
||||
let mut h = History { max_steps: 3, ..Default::default() };
|
||||
let op = |n: i32| ops(json!([{"kind":"setField","key":"s","value":n}]));
|
||||
h.record(op(1), op(0), Some("k"), 0.0);
|
||||
h.record(op(2), op(1), Some("k"), 100.0);
|
||||
assert_eq!(h.undo_depth(), 1);
|
||||
h.record(op(3), op(2), Some("k"), 600.0);
|
||||
assert_eq!(h.undo_depth(), 2);
|
||||
h.record(op(4), op(3), None, 700.0);
|
||||
h.record(op(5), op(4), None, 800.0);
|
||||
assert_eq!(h.undo_depth(), 3);
|
||||
h.begin_group();
|
||||
h.record(op(6), op(5), None, 900.0);
|
||||
h.record(op(7), op(6), Some("x"), 901.0);
|
||||
h.end_group();
|
||||
assert_eq!(h.undo_depth(), 3);
|
||||
let s = h.pop_undo().unwrap();
|
||||
assert_eq!(s.inverse, op(5));
|
||||
assert_eq!(s.forward, op(7));
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
//! Projekt nicht bei jedem Aufruf neu übergeben muss.
|
||||
|
||||
use crate::document::{Document, Op};
|
||||
use crate::ops::{ops_from_json, ops_to_json};
|
||||
use serde_json::Value;
|
||||
use std::cell::RefCell;
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
@@ -39,23 +40,103 @@ pub fn doc_close(h: u32) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Wendet eine Op-Folge (JSON-Array) an. Leerer Text = ok, sonst JSON-Array der Meldungen.
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_apply(h: u32, ops_json: &str) -> String {
|
||||
let parsed: Result<Vec<Op>, String> = serde_json::from_str::<Value>(ops_json)
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|v| v.as_array().ok_or("Ops sind kein Array".to_string()).and_then(|a| a.iter().map(Op::from_json).collect()));
|
||||
let problems = match parsed {
|
||||
Err(e) => vec![e],
|
||||
Ok(ops) => match with_doc(h, |d| d.apply(&ops)) {
|
||||
None => vec!["Dokument nicht offen".to_string()],
|
||||
Some(Ok(())) => return String::new(),
|
||||
Some(Err(p)) => p,
|
||||
},
|
||||
fn parse_ops(ops_json: &str) -> Result<Vec<Op>, String> {
|
||||
serde_json::from_str::<Value>(ops_json).map_err(|e| e.to_string()).and_then(|v| ops_from_json(&v))
|
||||
}
|
||||
|
||||
/// Ob der Text Nicht-endlich-Marken enthalten kann (`"\u0001NaN"` …, s. `crate::ops`).
|
||||
fn may_have_marks(ops_json: &str) -> bool {
|
||||
ops_json.contains("\\u0001")
|
||||
}
|
||||
|
||||
fn problems_text(r: Option<Result<(), Vec<String>>>, parsed_err: Option<String>) -> String {
|
||||
let problems = match (parsed_err, r) {
|
||||
(Some(e), _) => vec![e],
|
||||
(None, None) => vec!["Dokument nicht offen".to_string()],
|
||||
(None, Some(Ok(()))) => return String::new(),
|
||||
(None, Some(Err(p))) => p,
|
||||
};
|
||||
Value::from(problems).to_string()
|
||||
}
|
||||
|
||||
/// Wendet eine Op-Folge (JSON-Array) an, ohne Verlauf (Abgleich). Leerer Text = ok, sonst
|
||||
/// JSON-Array der Meldungen (Dokument unverändert).
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_apply(h: u32, ops_json: &str) -> String {
|
||||
match parse_ops(ops_json) {
|
||||
Err(e) => problems_text(None, Some(e)),
|
||||
Ok(ops) => problems_text(with_doc(h, |d| d.apply_marked(&ops, may_have_marks(ops_json))), None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Eine Benutzer-Änderung: Ops anwenden, prüfen (NaN, neue doppelte ids) und als Undo-Schritt
|
||||
/// aufzeichnen. `key` = coalesceKey (leer = keiner), `now_ms` = Zeit für das Koaleszenz-Fenster.
|
||||
/// Leerer Text = angenommen, sonst JSON-Array der Meldungen (Dokument und Verlauf unverändert).
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_commit(h: u32, ops_json: &str, key: &str, now_ms: f64) -> String {
|
||||
match parse_ops(ops_json) {
|
||||
Err(e) => problems_text(None, Some(e)),
|
||||
Ok(ops) => {
|
||||
let key = (!key.is_empty()).then_some(key);
|
||||
let now = if now_ms.is_finite() { now_ms } else { 0.0 };
|
||||
problems_text(with_doc(h, |d| d.commit(&ops, key, now, may_have_marks(ops_json))), None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Einen Schritt zurück: die angewendeten Ops als JSON-Array (für die TS-Leseansicht), leer = nichts.
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_undo(h: u32) -> String {
|
||||
with_doc(h, |d| d.undo().map(|ops| ops_to_json(&ops))).flatten().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Einen Schritt vor: die angewendeten Ops als JSON-Array, leer = nichts.
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_redo(h: u32) -> String {
|
||||
with_doc(h, |d| d.redo().map(|ops| ops_to_json(&ops))).flatten().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Verlaufsstand `[Undo-Tiefe, Redo-Tiefe, geschätzte Bytes]` (leer, wenn nicht offen).
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_history_state(h: u32) -> Vec<f64> {
|
||||
with_doc(h, |d| {
|
||||
let hi = d.history();
|
||||
vec![hi.undo_depth() as f64, hi.redo_depth() as f64, hi.bytes() as f64]
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Verlauf leeren (z. B. nach einer Änderung am Projekt vorbei an den Ops).
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_history_clear(h: u32) {
|
||||
with_doc(h, |d| d.history_mut().clear());
|
||||
}
|
||||
|
||||
/// Grenzen des Verlaufs: höchstens `steps` Schritte und ungefähr `bytes` Speicher (≤ 0 = unverändert).
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_history_limits(h: u32, steps: f64, bytes: f64) {
|
||||
with_doc(h, |d| {
|
||||
let hi = d.history_mut();
|
||||
if steps.is_finite() && steps >= 1.0 {
|
||||
hi.max_steps = steps as usize;
|
||||
}
|
||||
if bytes.is_finite() && bytes >= 1.0 {
|
||||
hi.max_bytes = bytes as usize;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Gruppe öffnen: alle Änderungen bis `doc_group_end` werden ein Undo-Schritt (verschachtelbar).
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_group_begin(h: u32) {
|
||||
with_doc(h, |d| d.history_mut().begin_group());
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_group_end(h: u32) {
|
||||
with_doc(h, |d| d.history_mut().end_group());
|
||||
}
|
||||
|
||||
/// Das ganze Dokument als JSON (leer, wenn nicht offen).
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_json(h: u32) -> String {
|
||||
|
||||
@@ -23,6 +23,7 @@ mod gpu_compile;
|
||||
mod plan_openings;
|
||||
mod delaunay;
|
||||
mod document;
|
||||
mod ops;
|
||||
mod mesh_section;
|
||||
mod plan_elevation;
|
||||
mod plan_misc;
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
//! Bindungen der Op-Prüfung (`crate::ops`) für die TS-Fassaden `validateOps`/`validateProject`
|
||||
//! (`src/core/ops.ts`). Eingaben als JSON (Nicht-endlich-Marken s. `crate::ops`), Ausgabe ein
|
||||
//! JSON-Array der Meldungen. Kaputte Eingaben ergeben eine Meldung, nie einen Panic.
|
||||
|
||||
use crate::ops::{ops_from_json, validate_ops, validate_project};
|
||||
use serde_json::{Map, Value};
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
fn object(text: &str) -> Result<Map<String, Value>, String> {
|
||||
match serde_json::from_str::<Value>(text) {
|
||||
Ok(Value::Object(m)) => Ok(m),
|
||||
Ok(_) => Err("kein JSON-Objekt".into()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Prüft angewendete Ops: `after_json`/`before_json` = Projekt (oder die berührten Felder) nach
|
||||
/// bzw. vor den Ops; `before_json` leer = unbekannt.
|
||||
#[wasm_bindgen]
|
||||
pub fn ops_validate(ops_json: &str, after_json: &str, before_json: &str) -> String {
|
||||
let run = || -> Result<Vec<String>, String> {
|
||||
let ops = ops_from_json(&serde_json::from_str::<Value>(ops_json).map_err(|e| e.to_string())?)?;
|
||||
let after = object(after_json)?;
|
||||
let before = if before_json.is_empty() { None } else { Some(object(before_json)?) };
|
||||
Ok(validate_ops(&after, &ops, before.as_ref()))
|
||||
};
|
||||
Value::from(run().unwrap_or_else(|e| vec![e])).to_string()
|
||||
}
|
||||
|
||||
/// Prüft ein ganzes Projekt (doppelte ids, nicht endliche Zahlen).
|
||||
#[wasm_bindgen]
|
||||
pub fn project_validate(project_json: &str) -> String {
|
||||
let problems = object(project_json).map(|p| validate_project(&p)).unwrap_or_else(|e| vec![e]);
|
||||
Value::from(problems).to_string()
|
||||
}
|
||||
@@ -3656,6 +3656,7 @@ export default function App() {
|
||||
selectedId: baseHost.selectedViewSnapshotId,
|
||||
onApply: baseHost.onApplyViewSnapshot,
|
||||
onCaptureAuto: baseHost.onCaptureViewSnapshotAuto,
|
||||
autoName: baseHost.viewSnapshotAutoName,
|
||||
onDelete: baseHost.onDeleteViewSnapshot,
|
||||
}}
|
||||
onSelectLevel={setActiveLevelId}
|
||||
|
||||
+27
-13
@@ -7,9 +7,11 @@
|
||||
// „+" sichert den aktuellen Stand als neuen Tab; der Name wird automatisch
|
||||
// bestimmt (aktive Zeichnungskombination, falls ihre Sichtbarkeits-Map exakt
|
||||
// passt, sonst das aktive Blatt) — kein Tipp-Dialog, wie ein Browser-Tab.
|
||||
// „×" löscht einen Tab; mindestens einer bleibt immer erhalten (fehlt der
|
||||
// letzte, wird beim nächsten Mount automatisch einer aus dem aktuellen Stand
|
||||
// nachgezogen).
|
||||
// „×" löscht einen Tab; mindestens einer bleibt immer erhalten. Hat das Projekt
|
||||
// noch keinen Ausschnitt, zeigt die Leiste einen Tab für den aktuellen Stand, ohne
|
||||
// ihn ins Projekt zu schreiben (das früher automatische Anlegen war eine
|
||||
// Projektänderung: nach jedem Rückgängig bis zum Anfang landete sie neu im Verlauf
|
||||
// und verwarf den Redo-Stapel). Erst „+" legt einen echten Ausschnitt an.
|
||||
//
|
||||
// Ersetzt die frühere Ein-Tab-je-Geschoss-Leiste: ein Ausschnitt kann JEDE
|
||||
// Zeichnungsebenen-Art referenzieren (Geschoss, Schnitt, Ansicht, Zeichnung),
|
||||
@@ -18,7 +20,6 @@
|
||||
//
|
||||
// Bezeichner englisch, UI-Text/Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import { useEffect } from "react";
|
||||
import type { Project } from "./model/types";
|
||||
import { t } from "./i18n";
|
||||
|
||||
@@ -35,6 +36,8 @@ export interface ViewSnapshotTabsHandlers {
|
||||
onCaptureAuto: () => string;
|
||||
/** Löscht einen Ausschnitt. */
|
||||
onDelete: (id: string) => void;
|
||||
/** Name für den Tab des aktuellen Stands, solange das Projekt keinen Ausschnitt hat. */
|
||||
autoName: () => string;
|
||||
}
|
||||
|
||||
export function DrawingTabs({
|
||||
@@ -47,15 +50,26 @@ export function DrawingTabs({
|
||||
const snapshots = project.viewSnapshots ?? [];
|
||||
const { selectedId, onApply, onCaptureAuto, onDelete } = handlers;
|
||||
|
||||
// Es muss immer mindestens ein Tab existieren (Nutzer-Vorgabe): ein frisches
|
||||
// oder altes Projekt ohne einen einzigen Ausschnitt bekommt beim ersten
|
||||
// Mount automatisch einen aus dem aktuellen Stand.
|
||||
useEffect(() => {
|
||||
if (snapshots.length === 0) onCaptureAuto();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [snapshots.length]);
|
||||
|
||||
if (snapshots.length === 0) return null;
|
||||
// Es muss immer mindestens ein Tab sichtbar sein (Nutzer-Vorgabe): ohne gespeicherten
|
||||
// Ausschnitt einer für den aktuellen Stand (nur Anzeige, keine Projektänderung).
|
||||
if (snapshots.length === 0) {
|
||||
return (
|
||||
<div className="drawing-tabs" role="tablist" aria-label={t("tabs.drawings")}>
|
||||
<button type="button" role="tab" aria-selected className="drawing-tab active" title={handlers.autoName()}>
|
||||
<span className="drawing-tab-label">{handlers.autoName()}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="drawing-tab-add"
|
||||
aria-label={t("tabs.add")}
|
||||
title={t("tabs.add")}
|
||||
onClick={() => onCaptureAuto()}
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="drawing-tabs" role="tablist" aria-label={t("tabs.drawings")}>
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
// Undo/Redo im Kern ([K4] S3, [8]): Änderungen laufen über `ProjectDocument.commit` (Prüfung +
|
||||
// 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 type { CoreOp } from "./ops";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Project, Wall } from "../model/types";
|
||||
|
||||
const plain = (p: Project): unknown => JSON.parse(JSON.stringify(p));
|
||||
|
||||
/** Zufällige, deterministische Änderung (Wände, Felder, Reihenfolgen, Listen ersetzen). */
|
||||
function mutate(p: Project, seed: number): Project {
|
||||
let x = seed;
|
||||
const rnd = () => (x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296;
|
||||
let out = { ...p };
|
||||
const walls = [...out.walls];
|
||||
const r = rnd();
|
||||
if (r < 0.2 && walls.length) walls.splice(Math.floor(rnd() * walls.length), 1);
|
||||
else if (r < 0.55 && walls.length) {
|
||||
const i = Math.floor(rnd() * walls.length);
|
||||
walls[i] = { ...walls[i], height: Math.round(((walls[i].height ?? 2.6) + rnd()) * 1000) / 1000 };
|
||||
} else if (r < 0.75) {
|
||||
walls.splice(Math.floor(rnd() * (walls.length + 1)), 0, { ...sampleProject.walls[0], id: `n${seed}` });
|
||||
} else if (r < 0.82) walls.reverse();
|
||||
out = { ...out, walls };
|
||||
const f = rnd();
|
||||
if (f < 0.15) out = { ...out, name: `n${seed}` };
|
||||
else if (f < 0.25) out = { ...out, referenceElevationMasl: Math.round(rnd() * 500) };
|
||||
else if (f < 0.32) out = { ...out, referenceElevationMasl: undefined };
|
||||
else if (f < 0.38) out = { ...out, geoAnchor: out.geoAnchor ? undefined : sampleProject.geoAnchor };
|
||||
else if (f < 0.42) out = { ...out, drawings2d: out.drawings2d.length ? [] : sampleProject.drawings2d };
|
||||
return out;
|
||||
}
|
||||
|
||||
describe("Undo/Redo im Kern-Dokument", () => {
|
||||
it("1000 Zufallsänderungen: Undo bis zum Anfang = Ausgangsprojekt, Redo bis zum Ende = Endprojekt", () => {
|
||||
const d = new ProjectDocument(sampleProject);
|
||||
d.setHistoryLimits(5000, 1 << 30);
|
||||
let cur: Project = sampleProject;
|
||||
let steps = 0;
|
||||
for (let seed = 1; seed <= 1000; seed++) {
|
||||
const next = mutate(cur, seed);
|
||||
const ops = diffToOps(cur, next);
|
||||
if (!ops.length) continue;
|
||||
const r = d.commit(cur, ops, undefined, seed * 1000);
|
||||
expect("project" in r, `seed ${seed}`).toBe(true);
|
||||
if ("project" in r) cur = r.project;
|
||||
steps++;
|
||||
}
|
||||
const end = cur;
|
||||
expect(d.historyState().undo).toBe(steps);
|
||||
expect(JSON.parse(d.json())).toEqual(plain(end));
|
||||
for (;;) {
|
||||
const prev = d.undo(cur);
|
||||
if (!prev) break;
|
||||
cur = prev;
|
||||
}
|
||||
expect(cur).toEqual(sampleProject);
|
||||
// Exakt, auch die Feld-Reihenfolge, und Kern == Leseansicht.
|
||||
expect(JSON.stringify(cur)).toBe(JSON.stringify(sampleProject));
|
||||
expect(JSON.parse(d.json())).toEqual(plain(sampleProject));
|
||||
for (;;) {
|
||||
const next = d.redo(cur);
|
||||
if (!next) break;
|
||||
cur = next;
|
||||
}
|
||||
expect(JSON.stringify(cur)).toBe(JSON.stringify(end));
|
||||
expect(JSON.parse(d.json())).toEqual(plain(end));
|
||||
d.close();
|
||||
});
|
||||
|
||||
it("coalesceKey: Serie im Zeitfenster = ein Schritt, unveränderte Elemente bleiben identisch", () => {
|
||||
const d = new ProjectDocument(sampleProject);
|
||||
let cur: Project = sampleProject;
|
||||
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);
|
||||
if ("project" in r) cur = r.project;
|
||||
}
|
||||
expect(d.historyState().undo).toBe(1);
|
||||
const back = d.undo(cur)!;
|
||||
expect(back).toEqual(sampleProject);
|
||||
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);
|
||||
expect("project" in r).toBe(true);
|
||||
expect(d.historyState().undo).toBe(2);
|
||||
d.close();
|
||||
});
|
||||
|
||||
it("Gruppe: mehrere Änderungen = ein Schritt", () => {
|
||||
const d = new ProjectDocument(sampleProject);
|
||||
let cur: Project = sampleProject;
|
||||
d.beginGroup();
|
||||
for (const name of ["a", "b", "c"]) {
|
||||
const r = d.commit(cur, diffToOps(cur, { ...cur, name }), undefined, 0);
|
||||
if ("project" in r) cur = r.project;
|
||||
}
|
||||
d.endGroup();
|
||||
expect(d.historyState().undo).toBe(1);
|
||||
expect(d.undo(cur)!.name).toBe(sampleProject.name);
|
||||
d.close();
|
||||
});
|
||||
|
||||
it("NaN und doppelte ids: abgelehnt mit den Meldungen der TS-Fassung, kein Schritt", () => {
|
||||
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);
|
||||
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);
|
||||
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);
|
||||
expect(r3).toEqual({ problems: [`Feld „referenceElevationMasl": -Infinity ist nicht endlich.`] });
|
||||
expect(d.historyState().undo).toBe(0);
|
||||
expect(JSON.parse(d.json())).toEqual(plain(sampleProject));
|
||||
d.close();
|
||||
});
|
||||
|
||||
it("Fassaden validateOps/validateProject (Kern) melden wie bisher", () => {
|
||||
const w = sampleProject.walls[0];
|
||||
const ops: CoreOp[] = [
|
||||
{ kind: "add", collection: "walls", items: [{ ...w, start: { x: Infinity, y: 0 } }] as never },
|
||||
{ kind: "setField", key: "scale", value: NaN },
|
||||
];
|
||||
const after = { ...sampleProject, walls: [...sampleProject.walls, ops[0].kind === "add" ? (ops[0].items[0] as unknown as Wall) : w] };
|
||||
expect(validateOps(after, ops, sampleProject)).toEqual([
|
||||
`„walls" ${w.id}: Infinity ist nicht endlich.`,
|
||||
`Doppelte ids in „walls".`,
|
||||
`Feld „scale": NaN ist nicht endlich.`,
|
||||
]);
|
||||
// Alt-Doppelungen bleiben änderbar.
|
||||
expect(validateOps(after, [{ kind: "add", collection: "walls", items: [{ id: "neu" }] }], after)).toEqual([]);
|
||||
expect(validateProject(sampleProject)).toEqual([]);
|
||||
});
|
||||
|
||||
it("Messung: grosses Projekt, viele Undo-Schritte", () => {
|
||||
const base = sampleProject.walls;
|
||||
const walls: Wall[] = Array.from({ length: 3000 }, (_, i) => ({
|
||||
...base[i % base.length],
|
||||
id: `w${i}`,
|
||||
start: { x: i, y: 0 },
|
||||
end: { x: i + 1, y: 0 },
|
||||
}));
|
||||
const big: Project = { ...sampleProject, walls };
|
||||
const d = new ProjectDocument(big);
|
||||
d.setHistoryLimits(1000, 1 << 30);
|
||||
let cur = big;
|
||||
const n = 500;
|
||||
let t = performance.now();
|
||||
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);
|
||||
if ("project" in r) cur = r.project;
|
||||
}
|
||||
const commitMs = (performance.now() - t) / n;
|
||||
const end = cur;
|
||||
t = performance.now();
|
||||
for (let p = d.undo(cur); p; p = d.undo(cur)) cur = p;
|
||||
const undoMs = (performance.now() - t) / n;
|
||||
t = performance.now();
|
||||
for (let p = d.redo(cur); p; p = d.redo(cur)) cur = p;
|
||||
const redoMs = (performance.now() - t) / n;
|
||||
const kib = Math.round(d.historyState().bytes / 1024);
|
||||
process.stderr.write(
|
||||
`3000 Wände, ${n} Schritte: setProject-Weg ${commitMs.toFixed(2)} ms/Schritt (diff+commit+apply), Undo ${undoMs.toFixed(2)} ms, Redo ${redoMs.toFixed(2)} ms, Verlauf ≈ ${kib} KiB\n`,
|
||||
);
|
||||
expect(cur.walls.map((w) => w.height)).toEqual(end.walls.map((w) => w.height));
|
||||
// Grosszügige Grenze (Container unter Last); typische Werte s. TODO [K4].
|
||||
expect(commitMs + undoMs + redoMs).toBeLessThan(50);
|
||||
d.close();
|
||||
});
|
||||
});
|
||||
+107
-3
@@ -1,12 +1,14 @@
|
||||
// Projekt-Dokument im Rust-Kern ([K4], Stufe S1): spiegelt das TS-Projekt über Ops nach Rust
|
||||
// (`document.rs`). TS bleibt vorerst Quelle der Änderungen (`setProject` → `diffToOps`); Rust hält
|
||||
// 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.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import { diffToOps } from "./ops";
|
||||
import { applyOps, diffToOps, opsToJson } from "./ops";
|
||||
import type { CoreOp } from "./ops";
|
||||
|
||||
/** Abfragen des Kerns (`queries.rs`). */
|
||||
export type QueryName =
|
||||
@@ -36,6 +38,8 @@ export type QueryName =
|
||||
export class ProjectDocument {
|
||||
private handle = 0;
|
||||
private mirror: Project;
|
||||
/** Verlaufsgrenzen (Schritte, Bytes), beim Neuöffnen wieder gesetzt. */
|
||||
private limits: [number, number] | null = null;
|
||||
|
||||
constructor(project: Project) {
|
||||
this.mirror = project;
|
||||
@@ -51,6 +55,7 @@ export class ProjectDocument {
|
||||
if (this.handle) core().doc_close(this.handle);
|
||||
this.handle = core().doc_open(JSON.stringify(project));
|
||||
if (!this.handle) console.warn("Projekt-Dokument im Kern konnte nicht geöffnet werden.");
|
||||
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). */
|
||||
@@ -106,9 +111,107 @@ export class ProjectDocument {
|
||||
if (this.handle) core().doc_close(this.handle);
|
||||
this.handle = 0;
|
||||
}
|
||||
|
||||
// ── Änderungen mit Verlauf ([K4] S3, [7], [8]) ──────────────────────────────
|
||||
// Der Kern prüft, wendet an und zeichnet Undo-Schritte als inverse Ops auf; das TS-Projekt ist
|
||||
// die Leseansicht und wird mit genau den Ops nachgeführt, die der Kern angenommen bzw. für
|
||||
// Undo/Redo geliefert hat (`applyOps`, unveränderte Elemente behalten ihre Identität).
|
||||
|
||||
/** Stand des Spiegels (die zuletzt übernommene Leseansicht). */
|
||||
get current(): Project {
|
||||
return this.mirror;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Benutzer-Änderung: `ops` (auf `base`) im Kern prüfen, anwenden und als Undo-Schritt
|
||||
* aufzeichnen (`coalesceKey` + `now` in ms: Serien im Zeitfenster = ein Schritt).
|
||||
* Ergebnis: neues Projekt oder die Meldungen des Kerns (dann bleibt alles unverändert).
|
||||
*/
|
||||
commit(base: Project, ops: readonly CoreOp[], coalesceKey: string | undefined, now: number): { project: Project } | { problems: string[] } {
|
||||
this.ensure(base);
|
||||
if (!this.handle) return { problems: ["Projekt-Dokument im Kern nicht offen."] };
|
||||
const res = core().doc_commit(this.handle, opsToJson(ops), coalesceKey ?? "", now);
|
||||
if (res) {
|
||||
let problems: string[];
|
||||
try {
|
||||
problems = JSON.parse(res) as string[];
|
||||
} catch {
|
||||
problems = [res];
|
||||
}
|
||||
return { problems };
|
||||
}
|
||||
const project = applyOps(base, ops);
|
||||
this.mirror = project;
|
||||
return { project };
|
||||
}
|
||||
|
||||
/** Einen Schritt zurück auf `base` (= aktuelles Projekt); `null` = nichts rückgängig zu machen. */
|
||||
undo(base: Project): Project | null {
|
||||
return this.jump(base, "doc_undo");
|
||||
}
|
||||
|
||||
/** Einen Schritt vor; `null` = nichts wiederherzustellen. */
|
||||
redo(base: Project): Project | null {
|
||||
return this.jump(base, "doc_redo");
|
||||
}
|
||||
|
||||
private jump(base: Project, fn: "doc_undo" | "doc_redo"): Project | null {
|
||||
if (base !== this.mirror || !this.handle) {
|
||||
this.ensure(base);
|
||||
return null;
|
||||
}
|
||||
const json = core()[fn](this.handle);
|
||||
if (!json) return null;
|
||||
const project = applyOps(base, JSON.parse(json) as CoreOp[]);
|
||||
this.mirror = project;
|
||||
return project;
|
||||
}
|
||||
|
||||
/** Verlaufsstand: Undo-/Redo-Tiefe und geschätzter Speicher (Bytes). */
|
||||
historyState(): { undo: number; redo: number; bytes: number } {
|
||||
const s = this.handle ? core().doc_history_state(this.handle) : new Float64Array(0);
|
||||
return { undo: s[0] ?? 0, redo: s[1] ?? 0, bytes: s[2] ?? 0 };
|
||||
}
|
||||
|
||||
clearHistory(): void {
|
||||
if (this.handle) core().doc_history_clear(this.handle);
|
||||
}
|
||||
|
||||
/** Grenzen des Verlaufs (Schritte, ungefähre Bytes). */
|
||||
setHistoryLimits(steps: number, bytes: number): void {
|
||||
this.limits = [steps, bytes];
|
||||
if (this.handle) core().doc_history_limits(this.handle, steps, bytes);
|
||||
}
|
||||
|
||||
/** Gruppe: alle Änderungen bis {@link endGroup} werden ein Undo-Schritt (verschachtelbar). */
|
||||
beginGroup(): void {
|
||||
if (this.handle) core().doc_group_begin(this.handle);
|
||||
}
|
||||
|
||||
endGroup(): void {
|
||||
if (this.handle) core().doc_group_end(this.handle);
|
||||
}
|
||||
}
|
||||
|
||||
let shared: ProjectDocument | null = null;
|
||||
/** Dokument des Stores (mit Verlauf); Abfragen auf dessen aktuellem Projekt laufen direkt darüber. */
|
||||
let primary: ProjectDocument | null = null;
|
||||
|
||||
/** Meldet das Dokument des Stores an (s. {@link documentFor}). */
|
||||
export function setPrimaryDocument(doc: ProjectDocument | null): void {
|
||||
primary = doc;
|
||||
}
|
||||
|
||||
/**
|
||||
* Das gemeinsame Kern-Dokument, auf den Stand von `project` gebracht. Der Abgleich läuft über die
|
||||
@@ -116,6 +219,7 @@ let shared: ProjectDocument | null = null;
|
||||
* wechselt ein Aufrufer zwischen sehr verschiedenen Projekten, ist es nur langsamer, nie falsch.
|
||||
*/
|
||||
export function documentFor(project: Project): ProjectDocument {
|
||||
if (primary && primary.current === project && primary.id) return primary;
|
||||
if (!shared) shared = new ProjectDocument(project);
|
||||
else shared.sync(project);
|
||||
return shared;
|
||||
|
||||
+50
-69
@@ -7,6 +7,12 @@
|
||||
// an — das Projekt ändert sich ausschliesslich durch Ops. Ops sind JSON-serialisierbar
|
||||
// (Undo-Verlauf [84], Makros [85], MCP [9], später ein Rust-Kern).
|
||||
//
|
||||
// [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).
|
||||
//
|
||||
// Granularität (bewusst grob, aber stabil):
|
||||
// • Listen aus Elementen mit `id` (walls, ceilings, drawings2d, …): `add` / `replace` / `remove`
|
||||
// / `reorder` je Element — unveränderte Elemente behalten ihre Objekt-Identität
|
||||
@@ -14,6 +20,7 @@
|
||||
// • Alles andere (Skalare, Objekte, Listen ohne ids): `setField` mit dem ganzen Wert.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { core } from "../engine/coreWasm";
|
||||
|
||||
type Entity = { id: string } & Record<string, unknown>;
|
||||
|
||||
@@ -26,8 +33,9 @@ export type CoreOp =
|
||||
| { kind: "remove"; collection: string; ids: string[] }
|
||||
/** Setzt die Reihenfolge der Liste (`ids` ist eine Permutation der vorhandenen ids). */
|
||||
| { kind: "reorder"; collection: string; ids: string[] }
|
||||
/** Setzt ein Projekt-Feld auf `value` (`undefined`/fehlend ⇒ Feld entfernen). */
|
||||
| { kind: "setField"; key: string; value?: unknown };
|
||||
/** Setzt ein Projekt-Feld auf `value` (`undefined`/fehlend ⇒ Feld entfernen). `at`: Position, falls
|
||||
* 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");
|
||||
@@ -113,6 +121,12 @@ function listOf(cur: Record<string, unknown>, collection: string): Entity[] {
|
||||
function applyOne(cur: Record<string, unknown>, op: CoreOp): Record<string, unknown> {
|
||||
switch (op.kind) {
|
||||
case "setField": {
|
||||
if (op.value !== undefined && op.at !== undefined && !(op.key in cur)) {
|
||||
// Neues Feld an Position `at` (wie `shift_insert` im Kern).
|
||||
const entries = Object.entries(cur);
|
||||
entries.splice(Math.max(0, Math.min(entries.length, op.at)), 0, [op.key, op.value]);
|
||||
return Object.fromEntries(entries);
|
||||
}
|
||||
const next = { ...cur };
|
||||
if (op.value === undefined) delete next[op.key];
|
||||
else next[op.key] = op.value;
|
||||
@@ -145,7 +159,28 @@ function applyOne(cur: Record<string, unknown>, op: CoreOp): Record<string, unkn
|
||||
}
|
||||
}
|
||||
|
||||
// ── Validierung ([7]) ────────────────────────────────────────────────────────
|
||||
// ── Übergabe an den Kern ─────────────────────────────────────────────────────
|
||||
|
||||
/** Nicht endliche Zahlen als Marken-Text (JSON kennt sie nicht; der Kern prüft sie, s. `ops.rs`). */
|
||||
function markNonFinite(_key: string, v: unknown): unknown {
|
||||
return typeof v === "number" && !Number.isFinite(v) ? `\u0001${String(v)}` : v;
|
||||
}
|
||||
|
||||
/** Ops als JSON für den Kern (NaN/±Infinity als Marken). */
|
||||
export function opsToJson(ops: readonly CoreOp[]): string {
|
||||
return JSON.stringify(ops, markNonFinite);
|
||||
}
|
||||
|
||||
// ── Validierung ([7]) — im Kern (`ops.rs`) ───────────────────────────────────
|
||||
|
||||
function problemsOf(json: string): string[] {
|
||||
try {
|
||||
const v = JSON.parse(json) as unknown;
|
||||
return Array.isArray(v) ? (v as string[]) : [];
|
||||
} catch {
|
||||
return ["Prüfung im Kern fehlgeschlagen."];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft ein Projekt auf Verstösse, die nie gewollt sind: nicht endliche Zahlen in Geometrie
|
||||
@@ -153,76 +188,22 @@ function applyOne(cur: Record<string, unknown>, op: CoreOp): Record<string, unkn
|
||||
* konservativ — gesperrt wird nur, was sicher kaputt ist.
|
||||
*/
|
||||
export function validateProject(p: Project): string[] {
|
||||
const problems: string[] = [];
|
||||
const rec = p as unknown as Record<string, unknown>;
|
||||
for (const key of Object.keys(rec)) {
|
||||
const v = rec[key];
|
||||
if (!isIdList(v) || v.length === 0) continue;
|
||||
if (!uniqueIds(v)) problems.push(`Doppelte ids in „${key}".`);
|
||||
// Nicht endliche Zahlen in den Elementen (flache Suche bis Tiefe 3, ohne grosse Zahlenfelder).
|
||||
for (const e of v) {
|
||||
const bad = findNonFinite(e, 0);
|
||||
if (bad) {
|
||||
problems.push(`„${key}" ${e.id}: ${bad} ist nicht endlich.`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
return problemsOf(core().project_validate(JSON.stringify(p, markNonFinite)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Wie {@link validateProject}, aber nur für das, was `ops` anfassen (billig genug für jeden
|
||||
* Maus-Schritt eines Drags): nicht endliche Zahlen in neuen/ersetzten Elementen, doppelte ids
|
||||
* in den betroffenen Listen, nicht endliche `setField`-Zahlen.
|
||||
* Prüft angewendete Ops (nur was sie anfassen, billig genug für jeden Drag-Schritt): nicht
|
||||
* endliche Zahlen in neuen/ersetzten Elementen und `setField`-Zahlen, NEUE doppelte ids in den
|
||||
* betroffenen Listen. Im Store läuft die Prüfung direkt im Kern-Dokument (`ProjectDocument.commit`).
|
||||
*/
|
||||
export function validateOps(after: Project, ops: readonly CoreOp[], before?: Project): string[] {
|
||||
const beforeRec = before as unknown as Record<string, unknown> | undefined;
|
||||
/** Alt-Dateien mit doppelten ids sollen weiter änderbar bleiben: nur NEUE Doppelungen melden. */
|
||||
const hadDup = (key: string) => {
|
||||
const l = beforeRec?.[key];
|
||||
return isIdList(l) && !uniqueIds(l);
|
||||
const keys = new Set(ops.map((op) => (op.kind === "setField" ? op.key : op.collection)));
|
||||
const pick = (p: Project | undefined): string => {
|
||||
if (!p) return "";
|
||||
const rec = p as unknown as Record<string, unknown>;
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const k of keys) if (k in rec) out[k] = rec[k];
|
||||
return JSON.stringify(out);
|
||||
};
|
||||
const problems: string[] = [];
|
||||
const rec = after as unknown as Record<string, unknown>;
|
||||
const dupChecked = new Set<string>();
|
||||
for (const op of ops) {
|
||||
if (op.kind === "add" || op.kind === "replace") {
|
||||
const ents = op.kind === "add" ? op.items : [op.entity];
|
||||
for (const e of ents) {
|
||||
const bad = findNonFinite(e, 0);
|
||||
if (bad) problems.push(`„${op.collection}" ${e.id}: ${bad} ist nicht endlich.`);
|
||||
}
|
||||
if (op.kind === "add" && !dupChecked.has(op.collection)) {
|
||||
dupChecked.add(op.collection);
|
||||
const list = rec[op.collection];
|
||||
if (isIdList(list) && !uniqueIds(list) && !hadDup(op.collection)) problems.push(`Doppelte ids in „${op.collection}".`);
|
||||
}
|
||||
} else if (op.kind === "setField") {
|
||||
if (typeof op.value === "number" && !Number.isFinite(op.value)) {
|
||||
problems.push(`Feld „${op.key}": ${String(op.value)} ist nicht endlich.`);
|
||||
} else if (isEntityList(op.value) && !uniqueIds(op.value) && !hadDup(op.key)) {
|
||||
problems.push(`Doppelte ids in „${op.key}".`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
function findNonFinite(v: unknown, depth: number): string | null {
|
||||
if (typeof v === "number") return Number.isFinite(v) ? null : String(v);
|
||||
if (depth > 3 || v === null || typeof v !== "object") return null;
|
||||
if (Array.isArray(v)) {
|
||||
if (v.length > 5000) return null; // Mesh-Arrays: nicht durchlaufen
|
||||
for (const x of v) {
|
||||
const r = findNonFinite(x, depth + 1);
|
||||
if (r) return r;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
for (const x of Object.values(v as Record<string, unknown>)) {
|
||||
const r = findNonFinite(x, depth + 1);
|
||||
if (r) return r;
|
||||
}
|
||||
return null;
|
||||
return problemsOf(core().ops_validate(opsToJson(ops), pick(after), pick(before)));
|
||||
}
|
||||
@@ -628,6 +628,8 @@ export interface PanelHostValue {
|
||||
* Ausschnitt sofort an.
|
||||
*/
|
||||
onCaptureViewSnapshotAuto: () => string;
|
||||
/** Name, den ein automatisch angelegter Ausschnitt jetzt bekäme (aktive Kombination bzw. Blatt). */
|
||||
viewSnapshotAutoName: () => string;
|
||||
/** Stellt alle Felder eines Ausschnitts wieder her (Geschoss/Sichtbarkeit/Overrides/Ansicht). */
|
||||
onApplyViewSnapshot: (id: string) => void;
|
||||
/** Benennt einen Ausschnitt um. */
|
||||
|
||||
@@ -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