From c36eb750f5418a89c66171a53f10f6af64c9a605 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 22:01:38 +0000 Subject: [PATCH 1/5] =?UTF-8?q?[K4][8]=20Kern-Verlauf:=20Positions-Index?= =?UTF-8?q?=20f=C3=BCr=20replace-Serien,=20commit=20=C3=BCbernimmt=20die?= =?UTF-8?q?=20Ops,=20Gruppen=20mit=20Schl=C3=BCssel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - document.rs: `PosCache` (id-Hash → Position je Liste, erst ab der zweiten Suche gebaut, Treffer nachgeprüft) für commit/undo/redo/Rücknahme; 300 `replace` auf 5000 Wände nativ 11,2 ms → 1,5 ms je Schritt. - `Document::commit` nimmt die Ops als Vec (gehen in den Verlauf über): jedes Element wird nur noch einmal kopiert. - `History::begin_group_keyed` / `doc_group_begin_keyed`: aufeinanderfolgende Gruppen mit gleichem Schlüssel im Zeitfenster = ein Undo-Schritt (Griff-Zug mit mitgeführten Ecken). - Tests: Serien = Einzel-Ops (200 Zufallsrunden, Undo/Redo exakt), Gruppen mit Schlüssel. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src-tauri/core/src/document.rs | 243 ++++++++++++++++++++++++----- src-tauri/core/src/ops.rs | 40 ++++- src-tauri/core/src/web/document.rs | 11 +- 3 files changed, 254 insertions(+), 40 deletions(-) diff --git a/src-tauri/core/src/document.rs b/src-tauri/core/src/document.rs index b7735ffa..c93ef569 100644 --- a/src-tauri/core/src/document.rs +++ b/src-tauri/core/src/document.rs @@ -24,6 +24,67 @@ pub struct Document { history: History, } +/// id → Position je Liste für die Dauer einer Op-Folge. Nur `replace` sucht darüber; jede andere Op +/// auf der Liste verwirft den Eintrag. Erst die zweite Suche in derselben Liste baut den Index — +/// ein einzelner Drag-Schritt bleibt bei der linearen Suche, Serien (Auswahl verschieben: hunderte +/// `replace`) kosten so O(Liste + Ops) statt O(Liste · Ops). Gleiche Semantik wie `position` +/// (erstes Vorkommen). Schlüssel ist ein Hash der id (keine Text-Kopien); jeder Treffer wird an der +/// Liste nachgeprüft, bei einer Kollision sucht `find` linear. +#[derive(Default)] +struct PosCache(HashMap); + +enum PosEntry { + /// Einmal linear gesucht. + Once, + Built(HashMap), +} + +/// FNV-1a über die id. +fn id_hash(id: &str) -> u64 { + id.bytes().fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ b as u64).wrapping_mul(0x0000_0100_0000_01b3)) +} + +impl PosCache { + fn find(&mut self, collection: &str, list: &[Value], id: Option<&str>) -> Option { + let linear = |id: Option<&str>| list.iter().position(|e| id_of(e) == id); + let Some(id) = id else { + return linear(None); + }; + match self.0.get(collection) { + Some(PosEntry::Built(m)) => match m.get(&id_hash(id)) { + Some(&i) if list.get(i).and_then(id_of) == Some(id) => Some(i), + Some(_) => linear(Some(id)), + None => None, + }, + Some(PosEntry::Once) => { + let mut m: HashMap = HashMap::with_capacity(list.len()); + for (i, e) in list.iter().enumerate() { + if let Some(x) = id_of(e) { + m.entry(id_hash(x)).or_insert(i); + } + } + self.0.insert(collection.to_owned(), PosEntry::Built(m)); + self.find(collection, list, Some(id)) + } + None => { + self.0.insert(collection.to_owned(), PosEntry::Once); + linear(Some(id)) + } + } + } + + /// Element `id` wurde an Position `at` angehängt (`replace` ohne Treffer). + fn pushed(&mut self, collection: &str, id: Option<&str>, at: usize) { + if let (Some(PosEntry::Built(m)), Some(id)) = (self.0.get_mut(collection), id) { + m.entry(id_hash(id)).or_insert(at); + } + } + + fn forget(&mut self, collection: &str) { + self.0.remove(collection); + } +} + impl Document { pub fn from_json(text: &str) -> Result { match serde_json::from_str::(text) { @@ -87,7 +148,10 @@ impl Document { /// Wendet eine Op ohne Aufzeichnung an (Semantik wie `applyOps` in TS). - fn apply_raw(&mut self, op: &Op) { + fn apply_raw(&mut self, op: &Op, pos: &mut PosCache) { + if !matches!(op, Op::Replace { .. }) { + pos.forget(op.key()); + } match op { Op::SetField { key, value, at } => match value { Some(v) => match at { @@ -111,9 +175,12 @@ impl Document { Op::Replace { collection, entity } => { let list = self.list_mut(collection); let id = id_of(entity); - match list.iter().position(|e| id_of(e) == id) { + match pos.find(collection, list, id) { Some(i) => list[i] = entity.clone(), - None => list.push(entity.clone()), + None => { + list.push(entity.clone()); + pos.pushed(collection, id, list.len() - 1); + } } } Op::Remove { collection, ids } => { @@ -137,13 +204,13 @@ impl Document { } } - /// Wendet eine Op an und liefert (inverse Ops in Anwendungsreihenfolge, normalisierte - /// Vorwärts-Op). Listen bekommen feine Inverse (`replace` ↔ altes Element, `add` ↔ `remove`, + /// Wendet eine Op an und liefert (inverse Ops in Anwendungsreihenfolge, ob die Vorwärts-Op als + /// `add` aufzuzeichnen ist — `replace` ohne Treffer). 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) { + fn apply_recorded(&mut self, op: &Op, pos: &mut PosCache) -> (Vec, bool) { let key = op.key(); let old = self.root.get(key); let snapshot = || { @@ -155,7 +222,7 @@ impl Document { 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 mut as_add = false; let inverse = match (op, clean) { (_, None) => vec![snapshot()], (Op::Add { collection, items, .. }, Some(list)) => { @@ -168,16 +235,16 @@ impl Document { vec![snapshot()] } } - (Op::Replace { collection, entity }, Some(list)) => match list.iter().position(|e| id_of(e) == id_of(entity)) { + (Op::Replace { collection, entity }, Some(list)) => match pos.find(collection, list, 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); + return (vec![Op::Replace { collection: collection.clone(), entity: prev }], false); } None => { // Aufgezeichnet als `add` (so trifft jedes aufgezeichnete `replace` ein vorhandenes Element). - forward = Op::Add { collection: collection.clone(), items: vec![entity.clone()], at: None }; + as_add = true; vec![Op::Remove { collection: collection.clone(), ids: vec![id_of(entity).unwrap_or("").to_owned()] }] } }, @@ -202,14 +269,14 @@ impl Document { } (Op::SetField { .. }, Some(_)) => unreachable!("setField hat keine Liste"), }; - self.apply_raw(op); - (inverse, forward) + self.apply_raw(op, pos); + (inverse, as_add) } /// 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 + /// Dokument unverändert. Ok → (je Op: als `add` aufzuzeichnen, 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, Vec), Vec> { + fn apply_checked(&mut self, ops: &[Op], sanitize: bool) -> Result<(Vec, Vec), Vec> { // Alt-Doppelungen der Listen merken, in die eingefügt oder die gesetzt wird. let mut had_dup: HashSet = HashSet::new(); for op in ops { @@ -218,17 +285,19 @@ impl Document { } } let mut inverses: Vec> = Vec::with_capacity(ops.len()); - let mut forward: Vec = Vec::with_capacity(ops.len()); + let mut as_add: Vec = Vec::with_capacity(ops.len()); + let mut pos = PosCache::default(); for op in ops { - let (inv, fwd) = self.apply_recorded(op); + let (inv, add) = self.apply_recorded(op, &mut pos); inverses.push(inv); - forward.push(fwd); + as_add.push(add); } let problems = crate::ops::validate(&self.root, ops, &|k| had_dup.contains(k)); if !problems.is_empty() { + let mut pos = PosCache::default(); for inv in inverses.iter().rev() { for op in inv { - self.apply_raw(op); + self.apply_raw(op, &mut pos); } } return Err(problems); @@ -241,12 +310,11 @@ impl Document { crate::ops::sanitize_non_finite(v); } } - crate::ops::sanitize_ops(&mut forward); } for op in ops { self.dirty.insert(op.key().to_owned()); } - Ok((forward, inverses.into_iter().rev().flatten().collect())) + Ok((as_add, inverses.into_iter().rev().flatten().collect())) } /// Wendet `ops` atomar an, ohne Verlauf (Abgleich des Spiegels). Verstösse (NaN, neue @@ -261,16 +329,32 @@ impl Document { } /// 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> { - let (forward, inverse) = self.apply_checked(ops, sanitize)?; + /// `coalesceKey`, `now` = Zeit in ms für das Koaleszenz-Fenster). Die Ops gehen in den Verlauf + /// über (Redo) — das Dokument hält eigene Kopien, so wird jedes Element nur einmal kopiert. + pub fn commit(&mut self, ops: Vec, key: Option<&str>, now: f64, sanitize: bool) -> Result<(), Vec> { + let (as_add, inverse) = self.apply_checked(&ops, sanitize)?; + // Normalisiert: `replace` ohne Treffer wird als `add` aufgezeichnet (so trifft jedes + // aufgezeichnete `replace` ein vorhandenes Element, s. `ops::compact`). + let mut forward: Vec = ops + .into_iter() + .zip(as_add) + .map(|(op, add)| match op { + Op::Replace { collection, entity } if add => Op::Add { collection, items: vec![entity], at: None }, + op => op, + }) + .collect(); + if sanitize { + // Angenommene Nicht-endlich-Marken auch im Verlauf als null. + crate::ops::sanitize_ops(&mut forward); + } self.history.record(forward, inverse, key, now); Ok(()) } fn apply_unchecked(&mut self, ops: &[Op]) { + let mut pos = PosCache::default(); for op in ops { - self.apply_raw(op); + self.apply_raw(op, &mut pos); self.dirty.insert(op.key().to_owned()); } } @@ -443,7 +527,7 @@ mod tests { 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) { + match d.commit(ops, None, n as f64 * 1000.0, true) { Ok(()) => committed += 1, Err(_) => { rejected += 1; @@ -460,24 +544,102 @@ mod tests { assert_eq!(d.to_json(), end); } + #[test] + fn replace_serien_wie_einzeln() { + // Serien in einem Aufruf (Positions-Index) = dieselben Ops einzeln (lineare Suche), auch mit + // fehlenden ids, Alt-Doppelungen und Struktur-Ops dazwischen; Undo stellt exakt zurück. + let start = r#"{"walls":[{"id":"a"},{"id":"b"},{"id":"a","alt":1},{"id":"c"}],"rooms":[{"id":"r"}]}"#; + let mut r = Rng(3); + for round in 0..200 { + let mut list = Vec::new(); + for k in 0..(2 + r.below(30)) { + let id = ["a", "b", "c", "d", "e"][r.below(5)]; + let c = if r.next() < 0.8 { "walls" } else { "rooms" }; + let p = r.next(); + list.push(if p < 0.7 { + json!({"kind":"replace","collection":c,"entity":{"id":id,"v":k}}) + } else if p < 0.8 { + json!({"kind":"remove","collection":c,"ids":[id]}) + } else if p < 0.9 { + json!({"kind":"add","collection":c,"items":[{"id":format!("n{round}-{k}")}],"at":r.below(4)}) + } else { + json!({"kind":"reorder","collection":c,"ids":[id]}) + }); + } + let o = ops(Value::Array(list)); + let mut batch = Document::from_json(start).unwrap(); + batch.commit(o.clone(), None, 0.0, false).unwrap(); + let mut single = Document::from_json(start).unwrap(); + for op in &o { + single.apply(std::slice::from_ref(op)).unwrap(); + } + assert_eq!(batch.to_json(), single.to_json(), "Runde {round}"); + batch.undo().unwrap(); + assert_eq!(batch.to_json(), Document::from_json(start).unwrap().to_json()); + batch.redo().unwrap(); + assert_eq!(batch.to_json(), single.to_json()); + } + } + #[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(); + d.commit(o.clone(), 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(); + 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(); + 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 gruppen_mit_schluessel_verschmelzen() { + let mut d = doc(); + let start = d.to_json(); + // Griff-Zug: je Mausschritt eine Gruppe (Element + mitgeführter Nachbar), gleicher Schlüssel. + for i in 0..20 { + d.history_mut().begin_group_keyed(Some("zug"), i as f64 * 20.0); + d.commit(ops(json!([{"kind":"replace","collection":"walls","entity":{"id":"a","x":i}}])), Some("grip:a"), i as f64 * 20.0, false).unwrap(); + d.commit(ops(json!([{"kind":"replace","collection":"walls","entity":{"id":"b","x":i}}])), Some("grip:b"), i as f64 * 20.0, false).unwrap(); + d.history_mut().end_group(); + } + assert_eq!(d.history().undo_depth(), 1); + // Andere Gruppe bzw. Pause über das Zeitfenster: neuer Schritt. + d.history_mut().begin_group_keyed(Some("zug"), 5000.0); + d.commit(ops(json!([{"kind":"setField","key":"name","value":"Z"}])), None, 5000.0, false).unwrap(); + d.history_mut().end_group(); + assert_eq!(d.history().undo_depth(), 2); + // Leere Gruppe ändert nichts am Anschluss. + d.history_mut().begin_group_keyed(Some("anders"), 5010.0); + d.history_mut().end_group(); + d.history_mut().begin_group_keyed(Some("zug"), 5020.0); + d.commit(ops(json!([{"kind":"setField","key":"name","value":"Y"}])), None, 5020.0, false).unwrap(); + d.history_mut().end_group(); + assert_eq!(d.history().undo_depth(), 2); + // Ohne Schlüssel: jede Gruppe ein Schritt. + for i in 0..3 { + d.history_mut().begin_group(); + d.commit(ops(json!([{"kind":"setField","key":"name","value":format!("g{i}")}])), Some("k"), 6000.0, false).unwrap(); + d.history_mut().end_group(); + } + assert_eq!(d.history().undo_depth(), 5); + while d.undo().is_some() {} + assert_eq!(d.to_json(), start); + // Nach Undo verschmilzt eine gleichnamige Gruppe nicht mit dem Redo-Rest. + d.redo().unwrap(); + d.history_mut().begin_group_keyed(Some("zug"), 6001.0); + d.commit(ops(json!([{"kind":"setField","key":"name","value":"W"}])), None, 6001.0, false).unwrap(); + d.history_mut().end_group(); assert_eq!(d.history().undo_depth(), 2); } @@ -485,14 +647,14 @@ mod tests { 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(); + 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(); + 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(); + 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); } @@ -500,8 +662,8 @@ mod tests { 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.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); @@ -513,7 +675,7 @@ mod tests { d.history_mut().max_bytes = 20_000; let big: Vec = (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(); + 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); } @@ -531,9 +693,20 @@ mod tests { 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(); + d.commit(o.clone(), None, i as f64 * 1000.0, false).unwrap(); } let commit = t.elapsed(); + // Auswahl verschieben: 300 `replace` in einer Op-Folge. + let sel: Vec = (0..300).map(|k| json!({"kind":"replace","collection":"walls","entity":{"id": format!("w{}", k * 16), "height": 1}})).collect(); + let sel = ops(Value::Array(sel)); + let t = Instant::now(); + for i in 0..20 { + d.commit(sel.clone(), None, (n + i) as f64 * 1000.0, false).unwrap(); + } + eprintln!("Auswahl 300 Wände verschieben: commit {:.1} µs/Schritt", t.elapsed().as_secs_f64() * 1e6 / 20.0); + for _ in 0..20 { + d.undo().unwrap(); + } let t = Instant::now(); while d.undo().is_some() {} let undo = t.elapsed(); diff --git a/src-tauri/core/src/ops.rs b/src-tauri/core/src/ops.rs index 67fa4071..e7fa692e 100644 --- a/src-tauri/core/src/ops.rs +++ b/src-tauri/core/src/ops.rs @@ -374,6 +374,12 @@ pub struct History { group_depth: u32, /// In einer offenen Gruppe: der erste Schritt steht schon (weitere verschmelzen damit). group_started: bool, + /// Schlüssel und Zeit der offenen Gruppe (`begin_group_keyed`): aufeinanderfolgende Gruppen + /// mit gleichem Schlüssel im Zeitfenster verschmelzen wie einzelne Änderungen. + group_key: Option, + group_at: f64, + /// Die offene Gruppe hat etwas aufgezeichnet. + group_recorded: bool, bytes: usize, pub max_steps: usize, pub max_bytes: usize, @@ -388,6 +394,9 @@ impl Default for History { last_at: 0.0, group_depth: 0, group_started: false, + group_key: None, + group_at: 0.0, + group_recorded: false, bytes: 0, max_steps: 100, max_bytes: 256 << 20, @@ -417,17 +426,37 @@ impl History { } pub fn begin_group(&mut self) { + self.begin_group_keyed(None, 0.0); + } + + /// Wie [`History::begin_group`]; mit `key` verschmilzt die Gruppe mit dem vorigen Schritt, wenn + /// dieser von einer Gruppe (oder Änderung) mit gleichem Schlüssel innerhalb des Zeitfensters + /// stammt — z. B. ein Griff-Zug, der je Mausschritt mehrere Elemente mitführt. + pub fn begin_group_keyed(&mut self, key: Option<&str>, now: f64) { if self.group_depth == 0 { - self.group_started = false; + let coalesced = key.is_some() && key == self.last_key.as_deref() && now - self.last_at < COALESCE_WINDOW_MS; + self.group_started = coalesced && !self.undo.is_empty(); + self.group_key = key.map(str::to_owned); + self.group_at = now; + self.group_recorded = 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; + return; + } + self.group_depth -= 1; + if self.group_depth == 0 { + if self.group_recorded || self.group_key.is_none() { + // Ohne Schlüssel beginnt die nächste Änderung einen eigenen Schritt (auch mit gleichem + // Schlüssel); mit Schlüssel kann die nächste gleichnamige Gruppe anschliessen. + self.last_key = self.group_key.take(); + self.last_at = self.group_at; + } else { + self.group_key = None; + } } } @@ -439,6 +468,9 @@ impl History { 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; + if self.group_depth > 0 { + self.group_recorded = true; + } 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) => { diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index 49f5a268..744ed688 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -79,7 +79,7 @@ pub fn doc_commit(h: u32, ops_json: &str, key: &str, now_ms: f64) -> String { 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) + problems_text(with_doc(h, |d| d.commit(ops, key, now, may_have_marks(ops_json))), None) } } } @@ -132,6 +132,15 @@ pub fn doc_group_begin(h: u32) { with_doc(h, |d| d.history_mut().begin_group()); } +/// Wie `doc_group_begin`, mit Schlüssel und Zeit (ms): aufeinanderfolgende Gruppen mit gleichem +/// Schlüssel im Zeitfenster werden ein Undo-Schritt (Griff-Zug mit mitgeführten Elementen). +#[wasm_bindgen] +pub fn doc_group_begin_keyed(h: u32, key: &str, now_ms: f64) { + let key = (!key.is_empty()).then_some(key); + let now = if now_ms.is_finite() { now_ms } else { 0.0 }; + with_doc(h, |d| d.history_mut().begin_group_keyed(key, now)); +} + #[wasm_bindgen] pub fn doc_group_end(h: u32) { with_doc(h, |d| d.history_mut().end_group()); From b9483db52923c438a8fe5cad566bc7adfd729da7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 22:01:39 +0000 Subject: [PATCH 2/5] =?UTF-8?q?[K4]=20applyOps:=20Listen=20je=20Aufruf=20e?= =?UTF-8?q?inmal=20kopiert,=20id-Index=20f=C3=BCr=20replace-Serien?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Leseansicht wird mit Op-Serien (Auswahl verschieben: hunderte `replace`) in O(Liste + Ops) statt O(Liste · Ops) nachgeführt; unberührte Listen/Elemente behalten ihre Identität. Test: 2000 zufällige Op-Folgen (auch Unsinn) = einfache Referenzfassung, JSON und Feld-Reihenfolge gleich. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src/core/ops.apply.test.ts | 130 +++++++++++++++++++++++++++++++++++++ src/core/ops.ts | 92 ++++++++++++++++++++------ 2 files changed, 203 insertions(+), 19 deletions(-) create mode 100644 src/core/ops.apply.test.ts diff --git a/src/core/ops.apply.test.ts b/src/core/ops.apply.test.ts new file mode 100644 index 00000000..194d9a4f --- /dev/null +++ b/src/core/ops.apply.test.ts @@ -0,0 +1,130 @@ +// [K4] S3: `applyOps` führt die Leseansicht mit Op-Serien nach (z. B. 300 `replace` beim Verschieben +// einer Auswahl). Die schnelle Fassung (Listen innerhalb eines Aufrufs nur einmal kopiert, id-Index +// je Liste) muss genau das Ergebnis der einfachen Fassung liefern — hier als Referenz festgehalten. +import { describe, expect, it } from "vitest"; +import { applyOps } from "./ops"; +import type { CoreOp } from "./ops"; +import { sampleProject } from "../model/sampleProject"; +import type { Project } from "../model/types"; + +type Entity = { id: string } & Record; + +/** Referenz: die einfache Fassung (je Op eine neue Liste, lineare Suche). */ +function referenceApplyOps(project: Project, ops: readonly CoreOp[]): Project { + let cur = project as unknown as Record; + const listOf = (c: string): Entity[] => (Array.isArray(cur[c]) ? (cur[c] as Entity[]) : []); + for (const op of ops) { + switch (op.kind) { + case "setField": { + if (op.value !== undefined && op.at !== undefined && !(op.key in cur)) { + const entries = Object.entries(cur); + entries.splice(Math.max(0, Math.min(entries.length, op.at)), 0, [op.key, op.value]); + cur = Object.fromEntries(entries); + break; + } + const next = { ...cur }; + if (op.value === undefined) delete next[op.key]; + else next[op.key] = op.value; + cur = next; + break; + } + case "add": { + const list = listOf(op.collection); + const at = op.at === undefined ? list.length : Math.max(0, Math.min(list.length, op.at)); + cur = { ...cur, [op.collection]: [...list.slice(0, at), ...op.items, ...list.slice(at)] }; + break; + } + case "replace": { + const list = listOf(op.collection); + const idx = list.findIndex((e) => e.id === op.entity.id); + if (idx < 0) cur = { ...cur, [op.collection]: [...list, op.entity] }; + else { + const out = list.slice(); + out[idx] = op.entity; + cur = { ...cur, [op.collection]: out }; + } + break; + } + case "remove": { + const drop = new Set(op.ids); + cur = { ...cur, [op.collection]: listOf(op.collection).filter((e) => !drop.has(e.id)) }; + break; + } + case "reorder": { + const list = listOf(op.collection); + const byId = new Map(list.map((e) => [e.id, e])); + const ordered = op.ids.map((id) => byId.get(id)).filter((e): e is Entity => e !== undefined); + const inOps = new Set(op.ids); + cur = { ...cur, [op.collection]: [...ordered, ...list.filter((e) => !inOps.has(e.id))] }; + break; + } + } + } + return cur as unknown as Project; +} + +function rng(seed: number): () => number { + let x = seed >>> 0; + return () => ((x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296); +} + +/** Zufällige Op-Folge, auch Unsinn (fehlende ids, Doppelungen, Felder ohne Liste). */ +function randomOps(p: Project, seed: number): CoreOp[] { + const r = rng(seed); + const pick = (a: readonly T[]): T => a[Math.floor(r() * a.length)]; + const colls = ["walls", "drawings2d", "rooms", "nope", "name"]; + const ids = [...p.walls.map((w) => w.id), ...p.drawings2d.map((d) => d.id), "x1", "x2", "x3"]; + const ops: CoreOp[] = []; + const n = 1 + Math.floor(r() * 25); + for (let i = 0; i < n; i++) { + const c = pick(colls); + const k = r(); + if (k < 0.45) ops.push({ kind: "replace", collection: c, entity: { id: pick(ids), v: Math.floor(r() * 100) } }); + else if (k < 0.6) { + const items = Array.from({ length: Math.floor(r() * 3) }, () => ({ id: pick(ids), a: r() })); + ops.push(r() < 0.5 ? { kind: "add", collection: c, items } : { kind: "add", collection: c, items, at: Math.floor(r() * 20) - 3 }); + } else if (k < 0.72) ops.push({ kind: "remove", collection: c, ids: [pick(ids), pick(ids)] }); + else if (k < 0.82) ops.push({ kind: "reorder", collection: c, ids: [pick(ids), pick(ids), pick(ids)] }); + else if (k < 0.9) ops.push({ kind: "setField", key: pick(colls), value: r() < 0.5 ? [{ id: pick(ids) }] : r() }); + else if (k < 0.95) ops.push({ kind: "setField", key: pick(colls) }); + else ops.push({ kind: "setField", key: `neu${Math.floor(r() * 3)}`, value: r(), at: Math.floor(r() * 5) }); + } + return ops; +} + +describe("applyOps (schnelle Fassung) = Referenz", () => { + it("2000 zufällige Op-Folgen: gleiches JSON, gleiche Feld-Reihenfolge, Original unberührt", () => { + const snap = JSON.stringify(sampleProject); + for (let seed = 1; seed <= 2000; seed++) { + const ops = randomOps(sampleProject, seed); + const a = applyOps(sampleProject, ops); + const b = referenceApplyOps(sampleProject, ops); + expect(JSON.stringify(a)).toBe(JSON.stringify(b)); + } + expect(JSON.stringify(sampleProject)).toBe(snap); + }); + + it("unberührte Listen und Elemente behalten ihre Identität", () => { + const w = sampleProject.walls; + const out = applyOps(sampleProject, [ + { kind: "replace", collection: "walls", entity: { ...w[0], height: 7 } }, + { kind: "replace", collection: "walls", entity: { ...w[1], height: 8 } }, + ]); + expect(out.drawings2d).toBe(sampleProject.drawings2d); + expect(out.walls[2]).toBe(w[2]); + expect(out.walls[0].height).toBe(7); + expect(sampleProject.walls[0]).toBe(w[0]); + expect(applyOps(sampleProject, [])).toBe(sampleProject); + }); + + it("vom Aufrufer übergebene Werte werden nicht verändert", () => { + const list = [{ id: "a" }, { id: "b" }]; + const out = applyOps(sampleProject, [ + { kind: "setField", key: "walls", value: list }, + { kind: "replace", collection: "walls", entity: { id: "a", z: 1 } }, + { kind: "add", collection: "walls", items: [{ id: "c" }] }, + ]); + expect(list).toEqual([{ id: "a" }, { id: "b" }]); + expect(out.walls).toEqual([{ id: "a", z: 1 }, { id: "b" }, { id: "c" }]); + }); +}); diff --git a/src/core/ops.ts b/src/core/ops.ts index ac00b046..b835c33b 100644 --- a/src/core/ops.ts +++ b/src/core/ops.ts @@ -106,11 +106,27 @@ function diffList(collection: string, va: Entity[], vb: Entity[], ops: CoreOp[]) } } -/** Wendet eine Op-Folge rein an (kein Zugriff auf Store/UI). */ +/** + * Wendet eine Op-Folge rein an (kein Zugriff auf Store/UI). Unberührte Listen und Elemente behalten + * ihre Identität. Innerhalb eines Aufrufs wird jede Liste höchstens einmal kopiert und für + * `replace`-Serien (Auswahl verschieben: hunderte Elemente) über einen id-Index angesprochen — + * Ergebnis gleich der einfachen Fassung (Test `ops.apply.test.ts`). + */ export function applyOps(project: Project, ops: readonly CoreOp[]): Project { - let cur = project as unknown as Record; - for (const op of ops) cur = applyOne(cur, op); - return cur as unknown as Project; + if (ops.length === 0) return project; + const st: ApplyState = { cur: { ...(project as unknown as Record) }, owned: new Set(), index: new Map() }; + for (const op of ops) applyOne(st, op); + return st.cur as unknown as Project; +} + +/** Zustand eines `applyOps`-Aufrufs: `cur` ist eine eigene Kopie der obersten Ebene; Listen in + * `owned` wurden in diesem Aufruf neu angelegt (dürfen verändert werden), `index` = id → Position + * (erstes Vorkommen) solcher Listen. */ +interface ApplyState { + cur: Record; + owned: Set; + /** `null` = einmal linear gesucht, der Index wird bei der nächsten Suche gebaut. */ + index: Map | null>; } function listOf(cur: Record, collection: string): Entity[] { @@ -118,43 +134,81 @@ function listOf(cur: Record, collection: string): Entity[] { return Array.isArray(v) ? (v as Entity[]) : []; } -function applyOne(cur: Record, op: CoreOp): Record { +/** Setzt `collection` auf eine neue (eigene) Liste; ein vorhandener Index verfällt. */ +function putList(st: ApplyState, collection: string, list: Entity[]): void { + st.cur[collection] = list; + st.owned.add(collection); + st.index.delete(collection); +} + +function applyOne(st: ApplyState, op: CoreOp): void { + const cur = st.cur; switch (op.kind) { case "setField": { + // Der Wert gehört dem Aufrufer: nie verändern. + st.owned.delete(op.key); + st.index.delete(op.key); if (op.value !== undefined && op.at !== undefined && !(op.key in cur)) { // Neues Feld an Position `at` (wie `shift_insert` im Kern). const entries = Object.entries(cur); entries.splice(Math.max(0, Math.min(entries.length, op.at)), 0, [op.key, op.value]); - return Object.fromEntries(entries); + st.cur = Object.fromEntries(entries); + return; } - const next = { ...cur }; - if (op.value === undefined) delete next[op.key]; - else next[op.key] = op.value; - return next; + if (op.value === undefined) delete cur[op.key]; + else cur[op.key] = op.value; + return; } case "add": { const list = listOf(cur, op.collection); const at = op.at === undefined ? list.length : Math.max(0, Math.min(list.length, op.at)); - return { ...cur, [op.collection]: [...list.slice(0, at), ...op.items, ...list.slice(at)] }; + putList(st, op.collection, [...list.slice(0, at), ...op.items, ...list.slice(at)]); + return; } case "replace": { - const list = listOf(cur, op.collection); - const idx = list.findIndex((e) => e.id === op.entity.id); - if (idx < 0) return { ...cur, [op.collection]: [...list, op.entity] }; - const out = list.slice(); - out[idx] = op.entity; - return { ...cur, [op.collection]: out }; + const c = op.collection; + let list: Entity[]; + if (st.owned.has(c)) list = cur[c] as Entity[]; + else { + list = listOf(cur, c).slice(); + putList(st, c, list); + } + // Erste Suche in dieser Liste linear (ein Drag-Schritt), ab der zweiten über den Index. + let idx = st.index.get(c); + let at: number | undefined; + if (idx === undefined) { + st.index.set(c, null); + const i = list.findIndex((e) => e?.id === op.entity.id); + at = i < 0 ? undefined : i; + } else { + if (idx === null) { + idx = new Map(); + for (let i = 0; i < list.length; i++) { + const id = list[i]?.id; + if (!idx.has(id)) idx.set(id, i); + } + st.index.set(c, idx); + } + at = idx.get(op.entity.id); + } + if (at === undefined) { + idx?.set(op.entity.id, list.length); + list.push(op.entity); + } else list[at] = op.entity; + return; } case "remove": { const drop = new Set(op.ids); - return { ...cur, [op.collection]: listOf(cur, op.collection).filter((e) => !drop.has(e.id)) }; + putList(st, op.collection, listOf(cur, op.collection).filter((e) => !drop.has(e.id))); + return; } case "reorder": { const list = listOf(cur, op.collection); const byId = new Map(list.map((e) => [e.id, e])); const ordered = op.ids.map((id) => byId.get(id)).filter((e): e is Entity => e !== undefined); const inOps = new Set(op.ids); - return { ...cur, [op.collection]: [...ordered, ...list.filter((e) => !inOps.has(e.id))] }; + putList(st, op.collection, [...ordered, ...list.filter((e) => !inOps.has(e.id))]); + return; } } } From b33f336bf0118b35e9655dd3d8afb091b148fdd1 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 22:02:25 +0000 Subject: [PATCH 3/5] =?UTF-8?q?[K4][8]=20Op-Bauhelfer=20(core/opsBuild.ts)?= =?UTF-8?q?,=20Gruppen=20mit=20Schl=C3=BCssel=20im=20Store?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `patchItem`/`patchItems`/`addItems`/`removeItems`/`replaceItem`/`setField`/`fieldOps` (Differenz nur über ein kleines Feld) und `opsMutation`: Projekt → Projekt-Funktion, die ihre Ops mitträgt (für `CommandResult.commit`, Hüllen-Aufrufer von `setProject`). - `ProjectDocument.beginKeyedGroup`, Store `groupChanges(fn, coalesceKey?)`. - Tests: Helfer = bisheriges map/filter/Anhängen über `diffToOps` (Zufall), fieldOps = volle Differenz. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src/core/document.ts | 9 +++ src/core/extra.ts | 2 + src/core/opsBuild.test.ts | 115 ++++++++++++++++++++++++++++ src/core/opsBuild.ts | 155 ++++++++++++++++++++++++++++++++++++++ src/state/historySlice.ts | 12 ++- 5 files changed, 289 insertions(+), 4 deletions(-) create mode 100644 src/core/opsBuild.test.ts create mode 100644 src/core/opsBuild.ts diff --git a/src/core/document.ts b/src/core/document.ts index 5348a77e..375174c8 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -199,6 +199,15 @@ export class ProjectDocument { if (this.handle) core().doc_group_begin(this.handle); } + /** + * Wie {@link beginGroup}, mit `coalesceKey` (+ `now` in ms): aufeinanderfolgende Gruppen mit + * gleichem Schlüssel im Zeitfenster schliessen an denselben Undo-Schritt an (Griff-Zug, der je + * Mausschritt mehrere Elemente bewegt), [K4] S3. + */ + beginKeyedGroup(coalesceKey: string, now: number): void { + if (this.handle) core().doc_group_begin_keyed(this.handle, coalesceKey, now); + } + endGroup(): void { if (this.handle) core().doc_group_end(this.handle); } diff --git a/src/core/extra.ts b/src/core/extra.ts index 79eec142..10d83eb9 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -43,3 +43,5 @@ export { readPdfVectorPage, pdfPageToImport, pdfPageInfo, pdfMetersPerPt, isPdfF export type { PdfVectorPage, PdfVectorPath, PdfVectorText } from "../io/pdfVector"; export { readMesh, meshObjectsToImportedMeshes, formatMeshReport, isMeshFile, MESH_UNITS, MESH_UNIT_SCALE } from "../io/meshImport"; export type { MeshObject, MeshImportReport, MeshUnit, MeshUp, MeshPlacement } from "../io/meshImport"; +export { addItems, fieldOps, findItem, isOpsMutation, itemsOf, opsMutation, patchItem, patchItems, removeItems, replaceItem, setField, setFieldIfChanged } from "./opsBuild"; +export type { EntityCollection, EntityOf, ProjectMutation } from "./opsBuild"; diff --git a/src/core/opsBuild.test.ts b/src/core/opsBuild.test.ts new file mode 100644 index 00000000..083aa8c3 --- /dev/null +++ b/src/core/opsBuild.test.ts @@ -0,0 +1,115 @@ +// Op-Bauhelfer ([K4] S3): Ergebnis = das bisherige Projekt → Projekt-Muster (`map`/`filter`/Anhängen) +// über `diffToOps`, auf Zufallsprojekten; unveränderte Elemente bleiben identisch. +import { describe, expect, it } from "vitest"; +import { applyOps, diffToOps } from "./ops"; +import { + addItems, + fieldOps, + findItem, + isOpsMutation, + opsMutation, + patchItem, + patchItems, + removeItems, + setField, + setFieldIfChanged, +} from "./opsBuild"; +import { sampleProject } from "../model/sampleProject"; +import type { Project, Wall } from "../model/types"; + +function rng(seed: number): () => number { + let x = seed >>> 0; + return () => ((x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296); +} + +function project(seed: number): Project { + const r = rng(seed); + const n = 1 + Math.floor(r() * 40); + const base = sampleProject.walls; + const walls: Wall[] = Array.from({ length: n }, (_, i) => ({ ...base[i % base.length], id: `w${i}`, height: r() * 3 })); + return { ...sampleProject, walls }; +} + +/** Alter Weg: Projekt → Projekt, dann über die Differenz. */ +const viaDiff = (p: Project, next: Project): Project => applyOps(p, diffToOps(p, next)); + +describe("Op-Bauhelfer", () => { + it("patchItem = map über die Liste (Teilobjekt und Funktion), Zufall", () => { + for (let seed = 1; seed <= 300; seed++) { + const p = project(seed); + const r = rng(seed + 1000); + const id = `w${Math.floor(r() * (p.walls.length + 3))}`; // auch fehlende ids + const h = r(); + const a = applyOps(p, patchItem(p, "walls", id, { height: h })); + const b = viaDiff(p, { ...p, walls: p.walls.map((w) => (w.id === id ? { ...w, height: h } : w)) }); + expect(a).toEqual(b); + const f = (w: Wall): Wall => ({ ...w, start: { x: w.start.x + h, y: w.start.y } }); + expect(applyOps(p, patchItem(p, "walls", id, f))).toEqual(viaDiff(p, { ...p, walls: p.walls.map((w) => (w.id === id ? f(w) : w)) })); + // Unveränderte Elemente identisch. + const out = applyOps(p, patchItem(p, "walls", "w0", { height: 9 })); + if (p.walls.length > 1) expect(out.walls[1]).toBe(p.walls[1]); + } + }); + + it("patchItem: fehlendes Element oder gleiches Objekt → keine Op", () => { + expect(patchItem(sampleProject, "walls", "gibt-es-nicht", { height: 1 })).toEqual([]); + expect(patchItem(sampleProject, "walls", sampleProject.walls[0].id, (w) => w)).toEqual([]); + }); + + it("patchItems / removeItems / addItems = map / filter / Anhängen, Zufall", () => { + for (let seed = 1; seed <= 300; seed++) { + const p = project(seed); + const r = rng(seed + 7); + const ids = p.walls.filter(() => r() < 0.3).map((w) => w.id); + const set = new Set(ids); + const mv = (w: Wall): Wall => ({ ...w, start: { x: w.start.x, y: w.start.y + 1 }, end: { x: w.end.x, y: w.end.y + 1 } }); + expect(applyOps(p, patchItems(p, "walls", ids, mv))).toEqual(viaDiff(p, { ...p, walls: p.walls.map((w) => (set.has(w.id) ? mv(w) : w)) })); + expect(applyOps(p, removeItems(p, "walls", set))).toEqual(viaDiff(p, { ...p, walls: p.walls.filter((w) => !set.has(w.id)) })); + const extra: Wall[] = [{ ...p.walls[0], id: `neu${seed}` }]; + expect(applyOps(p, addItems("walls", extra))).toEqual(viaDiff(p, { ...p, walls: [...p.walls, ...extra] })); + const at = Math.floor(r() * p.walls.length); + expect(applyOps(p, addItems("walls", extra, at))).toEqual( + viaDiff(p, { ...p, walls: [...p.walls.slice(0, at), ...extra, ...p.walls.slice(at)] }), + ); + } + }); + + it("leere Änderungen ergeben keine Ops; Prädikat statt ids", () => { + expect(removeItems(sampleProject, "walls", [])).toEqual([]); + expect(addItems("walls", [])).toEqual([]); + expect(patchItems(sampleProject, "walls", () => false, (w) => ({ ...w }))).toEqual([]); + const first = sampleProject.walls[0].id; + expect(removeItems(sampleProject, "walls", (w) => w.id === first)).toEqual([{ kind: "remove", collection: "walls", ids: [first] }]); + expect(findItem(sampleProject, "walls", first)).toBe(sampleProject.walls[0]); + }); + + it("setField / setFieldIfChanged", () => { + expect(setField("name", "X")).toEqual({ kind: "setField", key: "name", value: "X" }); + expect(setField("geoAnchor", undefined)).toEqual({ kind: "setField", key: "geoAnchor" }); + expect(setFieldIfChanged(sampleProject, "name", sampleProject.name)).toEqual([]); + expect(applyOps(sampleProject, setFieldIfChanged(sampleProject, "name", "Y")).name).toBe("Y"); + }); + + it("fieldOps: Differenz nur über ein Feld = volle Differenz, Zufall", () => { + for (let seed = 1; seed <= 200; seed++) { + const p = project(seed); + const r = rng(seed + 99); + const levels = p.drawingLevels.filter(() => r() < 0.8).map((z) => (r() < 0.3 ? { ...z, visible: !z.visible } : z)); + if (r() < 0.3) levels.reverse(); + const next = { ...p, drawingLevels: levels }; + expect(fieldOps(p, "drawingLevels", levels)).toEqual(diffToOps(p, next)); + expect(applyOps(p, fieldOps(p, "drawingLevels", levels))).toEqual(next); + } + expect(fieldOps(sampleProject, "layers", sampleProject.layers)).toEqual([]); + expect(fieldOps(sampleProject, "geoAnchor", undefined)).toEqual(diffToOps(sampleProject, { ...sampleProject, geoAnchor: undefined })); + }); + + it("opsMutation: wirkt wie eine Projekt → Projekt-Funktion und trägt die Ops mit", () => { + const id = sampleProject.walls[0].id; + const m = opsMutation((p) => patchItem(p, "walls", id, { height: 4.2 })); + expect(isOpsMutation(m)).toBe(true); + expect(isOpsMutation((p: Project) => p)).toBe(false); + expect(m(sampleProject).walls[0].height).toBe(4.2); + expect(m.toOps(sampleProject)).toHaveLength(1); + }); +}); diff --git a/src/core/opsBuild.ts b/src/core/opsBuild.ts new file mode 100644 index 00000000..81005b91 --- /dev/null +++ b/src/core/opsBuild.ts @@ -0,0 +1,155 @@ +// Op-Bauhelfer ([K4] S3, zweite Etappe): Aktionen beschreiben ihre Änderung direkt als +// {@link CoreOp}s statt als Projekt → Projekt-Funktion, die `setProject` erst per `diffToOps` über +// alle Listen zurückübersetzen muss (bei 3000 Wänden ≈ 2,4 ms je Mausschritt). Die Helfer lesen +// nur das betroffene Element; unveränderte Elemente bleiben unberührt (Identität in der +// TS-Leseansicht, `applyOps`). +// +// Store: `applyChange(ops | (p) => ops, coalesceKey?)`. Wo eine Schnittstelle weiter eine +// Projekt → Projekt-Funktion erwartet (Befehle: `CommandResult.commit`), trägt +// {@link opsMutation} die Ops mit — `setProject` nimmt dann die Ops ohne Differenz. + +import type { Project } from "../model/types"; +import { applyOps, diffToOps } from "./ops"; +import type { CoreOp } from "./ops"; + +/** Projekt-Felder, die Listen von Elementen mit `id` sind (walls, drawings2d, rooms, …). */ +export type EntityCollection = { + [K in keyof Project]-?: NonNullable extends readonly (infer E)[] + ? E extends { id: string } + ? K + : never + : never; +}[keyof Project]; + +/** Elementtyp einer Liste. */ +export type EntityOf = NonNullable extends readonly (infer E)[] ? E : never; + +type AnyEntity = { id: string } & Record; + +/** Die Liste `collection` (fehlend = leer). */ +export function itemsOf(p: Project, collection: K): readonly EntityOf[] { + const v = (p as unknown as Record)[collection]; + return Array.isArray(v) ? (v as EntityOf[]) : []; +} + +/** Element `id` aus `collection` (erstes Vorkommen). */ +export function findItem(p: Project, collection: K, id: string): EntityOf | undefined { + return itemsOf(p, collection).find((e) => (e as { id: string }).id === id); +} + +/** Ersetzt ein Element (gleiche id, Position bleibt). */ +export function replaceItem(collection: K, entity: EntityOf): CoreOp { + return { kind: "replace", collection, entity: entity as unknown as AnyEntity }; +} + +/** + * Ändert Element `id` in `collection`: `patch` als Teilobjekt (`{ ...e, ...patch }`) oder Funktion. + * Leer, wenn das Element fehlt oder die Funktion dasselbe Objekt zurückgibt (keine Änderung). + */ +export function patchItem( + p: Project, + collection: K, + id: string, + patch: Partial> | ((e: EntityOf) => EntityOf), +): CoreOp[] { + const old = findItem(p, collection, id); + if (old === undefined) return []; + const next = typeof patch === "function" ? patch(old) : ({ ...old, ...patch } as EntityOf); + return next === old ? [] : [replaceItem(collection, next)]; +} + +/** + * Ändert alle Elemente, deren id in `ids` liegt (bzw. für die `ids(e)` wahr ist), mit `fn`; eine + * `replace`-Op je tatsächlich geändertem Element, in Listen-Reihenfolge. + */ +export function patchItems( + p: Project, + collection: K, + ids: ReadonlySet | readonly string[] | ((e: EntityOf) => boolean), + fn: (e: EntityOf) => EntityOf, +): CoreOp[] { + const hit = idTest(ids); + const ops: CoreOp[] = []; + for (const e of itemsOf(p, collection)) { + if (!hit(e)) continue; + const next = fn(e); + if (next !== e) ops.push(replaceItem(collection, next)); + } + return ops; +} + +/** Fügt Elemente an `at` (Default: Ende) ein; leer ohne Elemente. */ +export function addItems(collection: K, items: readonly EntityOf[], at?: number): CoreOp[] { + if (items.length === 0) return []; + const op: CoreOp = { kind: "add", collection, items: items as unknown as AnyEntity[] }; + if (at !== undefined) op.at = at; + return [op]; +} + +/** Entfernt die Elemente aus `ids` (bzw. für die `ids(e)` wahr ist), die es gibt; leer, wenn keines trifft. */ +export function removeItems( + p: Project, + collection: K, + ids: ReadonlySet | readonly string[] | ((e: EntityOf) => boolean), +): CoreOp[] { + const hit = idTest(ids); + const drop: string[] = []; + const seen = new Set(); + for (const e of itemsOf(p, collection)) { + const id = (e as { id: string }).id; + if (hit(e) && !seen.has(id)) { + seen.add(id); + drop.push(id); + } + } + return drop.length ? [{ kind: "remove", collection, ids: drop }] : []; +} + +/** Setzt ein Projekt-Feld (`undefined` ⇒ Feld entfernen). */ +export function setField(key: K, value: Project[K] | undefined): CoreOp { + return value === undefined ? { kind: "setField", key } : { kind: "setField", key, value }; +} + +/** Setzt ein Projekt-Feld nur, wenn sich der Wert (per Referenz) ändert. */ +export function setFieldIfChanged(p: Project, key: K, value: Project[K] | undefined): CoreOp[] { + return p[key] === value ? [] : [setField(key, value)]; +} + +function idTest(ids: ReadonlySet | readonly string[] | ((e: E) => boolean)): (e: E) => boolean { + if (typeof ids === "function") return ids; + const set = ids instanceof Set ? ids : new Set(ids as readonly string[]); + return (e) => set.has((e as unknown as { id: string }).id); +} + +// ── Projekt → Projekt mit mitgeführten Ops ───────────────────────────────── + +/** Projekt → Projekt-Funktion, die ihre Ops mitträgt (s. {@link opsMutation}). */ +export type ProjectMutation = ((p: Project) => Project) & { readonly toOps: (p: Project) => CoreOp[] }; + +/** + * Verpackt einen Op-Bauer als Projekt → Projekt-Funktion (für Schnittstellen wie + * `CommandResult.commit`). Aufgerufen liefert sie `applyOps(p, build(p))`; `setProject` erkennt + * sie an `toOps` und übergibt die Ops ohne `diffToOps` an den Kern. + */ +export function opsMutation(build: (p: Project) => CoreOp[]): ProjectMutation { + const fn = (p: Project): Project => applyOps(p, build(p)); + return Object.assign(fn, { toOps: build }); +} + +/** Ob `fn` ihre Ops mitträgt. */ +export function isOpsMutation(fn: unknown): fn is ProjectMutation { + return typeof fn === "function" && typeof (fn as Partial).toOps === "function"; +} + +/** + * Ops, die das Feld `key` auf `value` bringen — für KLEINE Listen, die eine Hilfsfunktion als Ganzes + * neu liefert (Ebenen nach `recomputeFloorElevations`, Kategorien-Baum …): Differenz nur über + * dieses eine Feld (Elemente mit id einzeln, sonst `setField`). Grosse Listen (Wände, 2D) gehören + * über {@link patchItem}/{@link patchItems}/{@link addItems}/{@link removeItems}. + */ +export function fieldOps(p: Project, key: K, value: Project[K] | undefined): CoreOp[] { + if (p[key] === value) return []; + const before = { [key]: p[key] } as unknown as Project; + const after = (value === undefined ? {} : { [key]: value }) as unknown as Project; + return diffToOps(before, after); +} diff --git a/src/state/historySlice.ts b/src/state/historySlice.ts index 00117599..910d80c1 100644 --- a/src/state/historySlice.ts +++ b/src/state/historySlice.ts @@ -34,8 +34,11 @@ export interface HistorySlice { redo: () => void; /** Verlauf leeren. */ clearHistory: () => void; - /** Alle Projekt-Änderungen in `fn` werden EIN Undo-Schritt. */ - groupChanges: (fn: () => void) => void; + /** + * Alle Projekt-Änderungen in `fn` werden EIN Undo-Schritt. Mit `coalesceKey` schliessen + * aufeinanderfolgende Gruppen mit gleichem Schlüssel (im Zeitfenster) an denselben Schritt an. + */ + groupChanges: (fn: () => void, coalesceKey?: string) => void; } let doc: ProjectDocument | null = null; @@ -82,9 +85,10 @@ export function createHistorySlice(api: StoreApi { + groupChanges: (fn, coalesceKey) => { const d = storeDocument(get().project); - d.beginGroup(); + if (coalesceKey) d.beginKeyedGroup(coalesceKey, Date.now()); + else d.beginGroup(); try { fn(); } finally { From a24cfbb3d792eaa84df57a41d0960fbcaca8f24b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 22:02:40 +0000 Subject: [PATCH 4/5] =?UTF-8?q?[K4][6][8]=20Aktionen=20erzeugen=20Ops=20di?= =?UTF-8?q?rekt=20statt=20Projekt=20=E2=86=92=20Projekt=20+=20diffToOps?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Store `applyChange(ops | (p) => ops, coalesceKey?)` geht ohne Differenz an den Kern; `setProject` erkennt `opsMutation`-Funktionen und nimmt deren Ops. - Umgestellt: Griffe (moveGripOf/moveElementByOf/moveEdgeOf, Decke/Dach/Treppe/Raum), Objekt-Info (updateWall/-Ceiling/-Opening/-Roof/-Stair/-Room/-Drawing2D, Farbe, Füllung, Vorder-/Hintergrund, Resize, Wand-/Deckendicke, Polylinien-Punkte), Auswahl verschieben/ kopieren/drehen (`transformOps`), Löschen der Auswahl (+ Schnittlinien, eine Gruppe), Ebenen/Sichtbarkeit/Kategorien, Text-Tippen, Panel-Zeichnungs-Eigenschaften und die Zeichenbefehle (Wand, Decke, Raum, Treppe, Öffnung, Dach, Stütze, Extrusion, alle 2D-Zeichenbefehle, move/copy/mirror/rotate/scale/array). Gruppen-Zuordnung beim Zeichnen in einer Gruppe über `activeGroupOps`. - Griff-Zug mit mitgeführten Ecken: je Mausschritt eine Gruppe mit Schlüssel → ein Undo-Schritt für den ganzen Zug; aufgeschobene Commits beim Loslassen als Gruppe. - Tests: Store-Zufallsfolgen (Leseansicht = Kern, Aktion = applyOps(vorher, ihre Ops), Undo bis Anfang/Redo bis Ende exakt), activeGroupOps = addNewElementsToActiveGroup; beim Umbau zusätzlich 2400 Zufallsschritte gegen die alte setProject-Fassung und 400 Transformationen gegen das alte commitTransform geprüft (gleiches Projekt bis auf erzeugte ids und fehlend/leere Listen). - Messung (vitest, 3000 Wände): Griff ziehen 3,3 → 0,2–0,3 ms/Schritt, Auswahl (300 Wände) verschieben 30 → 6–7 ms, Eigenschaft tippen 3 → 0,03 ms. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src/App.tsx | 81 ++-- src/commands/cmds/arc.ts | 19 +- src/commands/cmds/array.ts | 4 +- src/commands/cmds/bezier.ts | 11 +- src/commands/cmds/block.ts | 13 +- src/commands/cmds/ceiling.ts | 16 +- src/commands/cmds/circle.ts | 16 +- src/commands/cmds/column.ts | 13 +- src/commands/cmds/copy.ts | 6 +- src/commands/cmds/detailref.ts | 9 +- src/commands/cmds/dimension.ts | 17 +- src/commands/cmds/ellipse.ts | 17 +- src/commands/cmds/extrude.ts | 12 +- src/commands/cmds/kote.ts | 9 +- src/commands/cmds/leader.ts | 13 +- src/commands/cmds/line.ts | 8 +- src/commands/cmds/mirror.ts | 6 +- src/commands/cmds/move.ts | 6 +- src/commands/cmds/multiline.ts | 13 +- src/commands/cmds/offset.ts | 12 +- src/commands/cmds/opening.ts | 12 +- src/commands/cmds/pointmarker.ts | 9 +- src/commands/cmds/polygon.ts | 19 +- src/commands/cmds/polyline.ts | 17 +- src/commands/cmds/ray.ts | 9 +- src/commands/cmds/rect.ts | 35 +- src/commands/cmds/revcloud.ts | 15 +- src/commands/cmds/roof.ts | 12 +- src/commands/cmds/room.ts | 18 +- src/commands/cmds/rotate.ts | 9 +- src/commands/cmds/scale.ts | 6 +- src/commands/cmds/scalebar.ts | 9 +- src/commands/cmds/spline.ts | 13 +- src/commands/cmds/stair.ts | 12 +- src/commands/cmds/text.ts | 10 +- src/commands/cmds/textbox.ts | 9 +- src/commands/cmds/textpath.ts | 9 +- src/commands/cmds/wall.ts | 22 +- src/commands/cmds/wipeout.ts | 11 +- src/commands/cmds/xline.ts | 9 +- src/state/applyChange.perf.test.ts | 57 +++ src/state/applyChange.test.ts | 177 ++++++++ src/state/groupActions.test.ts | 29 ++ src/state/groupActions.ts | 54 +++ src/state/projectSlice.ts | 577 ++++++++++--------------- src/state/useGripEditing.ts | 27 +- src/state/useMouseSelectionHandlers.ts | 29 +- src/state/usePanelHostBase.ts | 127 +++--- src/tools/transform.ts | 108 +++-- 49 files changed, 1001 insertions(+), 750 deletions(-) create mode 100644 src/state/applyChange.perf.test.ts create mode 100644 src/state/applyChange.test.ts diff --git a/src/App.tsx b/src/App.tsx index 509d9717..64619482 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -156,7 +156,8 @@ import { useGripEditing } from "./state/useGripEditing"; import { usePanelHostBase } from "./state/usePanelHostBase"; import { useDockDragState } from "./state/useDockDragState"; import { useMouseSelectionHandlers } from "./state/useMouseSelectionHandlers"; -import { addNewElementsToActiveGroup, containingGroupId, EMPTY_MEMBERSHIP } from "./state/groupActions"; +import { activeGroupOps, addNewElementsToActiveGroup, containingGroupId, EMPTY_MEMBERSHIP } from "./state/groupActions"; +import { isOpsMutation, opsMutation, removeItems } from "./core"; import type { GroupMembership, MemberKind } from "./state/groupActions"; import { isLocked, setLockedForMembers } from "./state/objectLock"; import { useProjectFileActions } from "./state/useProjectFileActions"; @@ -352,6 +353,7 @@ export default function App() { // Endlosschleife). Actions leben ebenfalls im Zustand und sind referenzstabil. const project = useStore((s) => s.project); const setProject = useStore((s) => s.setProject); + const groupChanges = useStore((s) => s.groupChanges); const notify = useStore((s) => s.notify); const undo = useStore((s) => s.undo); const redo = useStore((s) => s.redo); @@ -937,10 +939,21 @@ export default function App() { // „wenn man etwas neu zeichnet ... zeichnet man in der Gruppe") — s. // state/groupActions.ts::addNewElementsToActiveGroup (Diff vor/nach // Commit über alle Elementarten, additiv zur eigentlichen Mutation). - commit: (mutate) => - cmdLatest.current.setProject((p) => - addNewElementsToActiveGroup(p, mutate(p), cmdLatest.current.groupPath), - ), + // [K4] S3: Befehle mit mitgeführten Ops (`opsMutation`) gehen ohne Projekt-Differenz an den + // Kern; die Gruppen-Zuordnung kommt dann als weitere Ops dazu (`activeGroupOps`). + commit: (mutate) => { + const groupPath = cmdLatest.current.groupPath; + if (isOpsMutation(mutate)) { + cmdLatest.current.setProject( + opsMutation((p) => { + const ops = mutate.toOps(p); + return [...ops, ...activeGroupOps(p, ops, groupPath)]; + }), + ); + } else { + cmdLatest.current.setProject((p) => addNewElementsToActiveGroup(p, mutate(p), groupPath)); + } + }, isFloor: () => cmdLatest.current.activeLevel.kind === "floor", // Frisch über `text`/`textbox` erzeugtes Element sofort inline editieren // (kein Lookup nötig — der Commit hat es bereits angehängt, s. engine.ts @@ -1223,6 +1236,21 @@ export default function App() { // Löscht die AKTUELLE Auswahl (alle Kanäle) — geteilte Logik zwischen dem // Entf-Tastatur-Handler und dem Menüpunkt „Bearbeiten > Löschen". const deleteSelection = () => { + // Ein Undo-Schritt für alles (Schnittlinien + Elemente), [K4] S3. + groupChanges(() => deleteSelectionChanges()); + setSelectedDrawingIds([]); + setSelectedWallIds([]); + setSelectedCeilingIds([]); + setSelectedOpeningIds([]); + setSelectedStairIds([]); + setSelectedRoomIds([]); + setSelectedExtrudedSolidIds([]); + setSelectedColumnIds([]); + setSelectedRoofIds([]); + setSelectedContextObjectIds([]); + setSelectedSectionLineIds([]); + }; + const deleteSelectionChanges = () => { // Schnittlinie(n): Entf löscht NUR ihre Linie (linePoints), die Ebene // bleibt — ADDITIV zu den übrigen Kanälen unten (nicht mehr exklusiv: // seit Cmd/Ctrl+A Schnittlinien zusammen mit Wänden/etc. mitselektiert, @@ -1246,33 +1274,21 @@ export default function App() { const colids = new Set(notLocked("columnIds", selectedColumnIds)); const rfids = new Set(notLocked("roofIds", selectedRoofIds)); const ctxids = new Set(selectedContextObjectIds); - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.filter((d) => !dids.has(d.id)), - walls: p.walls.filter((w) => !wids.has(w.id)), - ceilings: (p.ceilings ?? []).filter((c) => !cids.has(c.id)), - roofs: (p.roofs ?? []).filter((r) => !rfids.has(r.id)), - stairs: (p.stairs ?? []).filter((s) => !stids.has(s.id)), - rooms: (p.rooms ?? []).filter((r) => !rmids.has(r.id)), - extrudedSolids: (p.extrudedSolids ?? []).filter((s) => !exids.has(s.id)), - columns: (p.columns ?? []).filter((c) => !colids.has(c.id)), - // Öffnungen: eigene Auswahl löschen UND alle, deren Host-Wand entfällt. - openings: (p.openings ?? []).filter( - (o) => !oids.has(o.id) && !wids.has(o.hostWallId), - ), - context: (p.context ?? []).filter((o) => !ctxids.has(o.id)), - })); - setSelectedDrawingIds([]); - setSelectedWallIds([]); - setSelectedCeilingIds([]); - setSelectedOpeningIds([]); - setSelectedStairIds([]); - setSelectedRoomIds([]); - setSelectedExtrudedSolidIds([]); - setSelectedColumnIds([]); - setSelectedRoofIds([]); - setSelectedContextObjectIds([]); - setSelectedSectionLineIds([]); + setProject( + opsMutation((p) => [ + ...removeItems(p, "drawings2d", dids), + ...removeItems(p, "walls", wids), + ...removeItems(p, "ceilings", cids), + ...removeItems(p, "roofs", rfids), + ...removeItems(p, "stairs", stids), + ...removeItems(p, "rooms", rmids), + ...removeItems(p, "extrudedSolids", exids), + ...removeItems(p, "columns", colids), + // Öffnungen: eigene Auswahl löschen UND alle, deren Host-Wand entfällt. + ...removeItems(p, "openings", (o) => oids.has(o.id) || wids.has(o.hostWallId)), + ...removeItems(p, "context", ctxids), + ]), + ); }; // Tastatur im Auswahl-Werkzeug: Ctrl/Cmd+A = alles wählen, Entf/Backspace = @@ -1823,6 +1839,7 @@ export default function App() { moveRoomBy, moveCeilingBy, moveElementByOf, + groupChanges, }); // Nummern-Shortcuts für Zeichenwerkzeuge (Vectorworks-Stil): 1 Text, 2 Linie, diff --git a/src/commands/cmds/arc.ts b/src/commands/cmds/arc.ts index e0df69d3..3be38e40 100644 --- a/src/commands/cmds/arc.ts +++ b/src/commands/cmds/arc.ts @@ -42,11 +42,12 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; @@ -202,8 +203,8 @@ function lineDraft(a: Vec2, b: Vec2): ToolDraft { return { preview: [{ kind: "line", a, b }], vertices: [a] }; } -function appendArc(p: Project, center: Vec2, r: number, a0: number, a1: number, ctx: CommandContext): Project { - if (r < EPS) return p; +function appendArc(center: Vec2, r: number, a0: number, a1: number, ctx: CommandContext): CoreOp[] { + if (r < EPS) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -211,7 +212,7 @@ function appendArc(p: Project, center: Vec2, r: number, a0: number, a1: number, categoryCode: ctx.defaultCategoryCode, geom: { shape: "arc", center, r, a0, a1 }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (method: ArcMethod): [CommandState, CommandResult] => [ @@ -268,7 +269,7 @@ export const arcCommand: Command = { if (!arc) return [s, { draft: null }]; return [ idle("ser")[0], - { draft: null, done: true, commit: (p) => appendArc(p, arc.center, arc.r, arc.a0, arc.a1, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendArc(arc.center, arc.r, arc.a0, arc.a1, ctx)) }, ]; } if (input.kind !== "point") return [s, { draft: null }]; @@ -291,7 +292,7 @@ export const arcCommand: Command = { const { center, r, a0 } = s; return [ idle("center")[0], - { draft: null, done: true, commit: (p) => appendArc(p, center, r, a0, a1, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendArc(center, r, a0, a1, ctx)) }, ]; } @@ -311,7 +312,7 @@ export const arcCommand: Command = { if (!arc) return [s, { draft: lineDraft(s.a, pt) }]; // kollinear — Punkt ignorieren, weiter warten return [ idle("three")[0], - { draft: null, done: true, commit: (p) => appendArc(p, arc.center, arc.r, arc.a0, arc.a1, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendArc(arc.center, arc.r, arc.a0, arc.a1, ctx)) }, ]; } @@ -331,7 +332,7 @@ export const arcCommand: Command = { if (!arc) return [s, { draft: lineDraft(s.a, s.b) }]; // Radius zu klein — weiter warten return [ idle("ser")[0], - { draft: null, done: true, commit: (p) => appendArc(p, arc.center, arc.r, arc.a0, arc.a1, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendArc(arc.center, arc.r, arc.a0, arc.a1, ctx)) }, ]; } @@ -350,7 +351,7 @@ export const arcCommand: Command = { if (!sedArc) return [s, { draft: lineDraft(s.a, s.b) }]; // entartete Richtung — weiter warten return [ idle("sed")[0], - { draft: null, done: true, commit: (p) => appendArc(p, sedArc.center, sedArc.r, sedArc.a0, sedArc.a1, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendArc(sedArc.center, sedArc.r, sedArc.a0, sedArc.a1, ctx)) }, ]; }, diff --git a/src/commands/cmds/array.ts b/src/commands/cmds/array.ts index e112cba9..167e1b59 100644 --- a/src/commands/cmds/array.ts +++ b/src/commands/cmds/array.ts @@ -23,7 +23,7 @@ // wie move/copy). Leere Auswahl → No-op. import { - commitTransform, + transformMutation, hasTransformSelection, toTransformSel, transformPreview, @@ -200,7 +200,7 @@ export const arrayCommand: Command = { const pts = kind === "polar" ? polarPts(base, segAngleDeg(base, target)) : [base, target]; return [ idle(kind)[0], - { draft: null, done: true, commit: (p) => commitTransform(p, toTransformSel(sel), op, pts, "array", lastCount) }, + { draft: null, done: true, commit: transformMutation(toTransformSel(sel), op, pts, "array", lastCount) }, ]; }, diff --git a/src/commands/cmds/bezier.ts b/src/commands/cmds/bezier.ts index 8d7c7db3..cceb3a8a 100644 --- a/src/commands/cmds/bezier.ts +++ b/src/commands/cmds/bezier.ts @@ -17,10 +17,11 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; interface BezierStart extends CommandState { phase: "start"; @@ -58,8 +59,8 @@ function bezierDraft(pts: Vec2[], rubber: Vec2[]): ToolDraft { return { preview, vertices: pts.length > 0 ? [pts[0]] : [] }; } -function appendBezier(p: Project, pts: Vec2[], ctx: CommandContext): Project { - if (pts.length < 4) return p; +function appendBezier(pts: Vec2[], ctx: CommandContext): CoreOp[] { + if (pts.length < 4) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -67,7 +68,7 @@ function appendBezier(p: Project, pts: Vec2[], ctx: CommandContext): Project { categoryCode: ctx.defaultCategoryCode, geom: { shape: "bezier", pts }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -76,7 +77,7 @@ const idle = (): [CommandState, CommandResult] => [ ]; const finish = (pts: Vec2[], ctx: CommandContext): [CommandState, CommandResult] => [ { phase: "start", lastPoint: null } as BezierStart, - { draft: null, done: true, commit: (p) => appendBezier(p, pts, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendBezier(pts, ctx)) }, ]; export const bezierCommand: Command = { diff --git a/src/commands/cmds/block.ts b/src/commands/cmds/block.ts index 4b5e2da6..6619e424 100644 --- a/src/commands/cmds/block.ts +++ b/src/commands/cmds/block.ts @@ -22,9 +22,10 @@ import type { CommandContext, CommandResult, CommandState, - Project, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; @@ -51,14 +52,12 @@ function readDefs(ctx: CommandContext): { ids: string[]; names: string[] } { return { ids: defs.map((d) => d.id), names: defs.map((d) => d.name) }; } -function appendInstance( - p: Project, - blockDefId: string, +function appendInstance(blockDefId: string, at: Vec2, rotation: number, scale: number, ctx: CommandContext, -): Project { +): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -66,7 +65,7 @@ function appendInstance( categoryCode: ctx.defaultCategoryCode, geom: { shape: "block", blockDefId, at, rotation, scale }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } /** Drehwinkel + Skalierungsfaktor aus DEMSELBEN Punkt: Klick auf `at` = (0, 1). */ @@ -117,7 +116,7 @@ export const blockCommand: Command = { const { rotation, scale } = rotationAndScaleFrom(at, pt); return [ idle()[0], - { draft: null, done: true, commit: (p) => appendInstance(p, blockDefId, at, rotation, scale, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendInstance(blockDefId, at, rotation, scale, ctx)) }, ]; }, diff --git a/src/commands/cmds/ceiling.ts b/src/commands/cmds/ceiling.ts index 2ace28b9..d9ea59c4 100644 --- a/src/commands/cmds/ceiling.ts +++ b/src/commands/cmds/ceiling.ts @@ -26,10 +26,11 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -115,9 +116,9 @@ function ceilingDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { } /** Hängt eine Decke ans Projekt (immutabel). Entartete Umrisse werden verworfen. */ -function appendCeiling(p: Project, pts: Vec2[], ctx: CommandContext): Project { +function appendCeiling(pts: Vec2[], ctx: CommandContext): CoreOp[] { const outline = normalizeOutline(pts); - if (!outline || ceilingArea(outline) < 1e-4) return p; + if (!outline || ceilingArea(outline) < 1e-4) return []; const ceiling: Ceiling = { id: uniqueId("C"), type: "ceiling", @@ -126,8 +127,7 @@ function appendCeiling(p: Project, pts: Vec2[], ctx: CommandContext): Project { outline, wallTypeId: activeTypeId(ctx), }; - const ceilings = p.ceilings ? [...p.ceilings, ceiling] : [ceiling]; - return { ...p, ceilings }; + return addItems("ceilings", [ceiling]); } const idle = (): [CommandState, CommandResult] => [ @@ -175,7 +175,7 @@ export const ceilingCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null } as CeilIdle, - { draft: null, done: true, commit: (p) => appendCeiling(p, pts, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendCeiling(pts, ctx)) }, ]; } return [s, { draft: ceilingDraft(s.points, s.cursor) }]; @@ -197,7 +197,7 @@ export const ceilingCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null } as CeilIdle, - { draft: null, done: true, commit: (p) => appendCeiling(p, pts, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendCeiling(pts, ctx)) }, ]; } // Null-Strecke (Klick auf denselben Punkt) ignorieren. @@ -224,7 +224,7 @@ export const ceilingCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null } as CeilIdle, - { draft: null, done: true, commit: (p) => appendCeiling(p, pts, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendCeiling(pts, ctx)) }, ]; } return idle(); diff --git a/src/commands/cmds/circle.ts b/src/commands/cmds/circle.ts index 94bc2869..7e49a7bb 100644 --- a/src/commands/cmds/circle.ts +++ b/src/commands/cmds/circle.ts @@ -52,6 +52,8 @@ import type { Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; @@ -265,8 +267,8 @@ function lineDraft(a: Vec2, b: Vec2): ToolDraft { return { preview: [{ kind: "line", a, b }], vertices: [a] }; } -function appendCircle(p: Project, center: Vec2, r: number, ctx: CommandContext): Project { - if (r < EPS) return p; +function appendCircle(center: Vec2, r: number, ctx: CommandContext): CoreOp[] { + if (r < EPS) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -274,7 +276,7 @@ function appendCircle(p: Project, center: Vec2, r: number, ctx: CommandContext): categoryCode: ctx.defaultCategoryCode, geom: { shape: "circle", center, r }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (method: CircleMethod): [CommandState, CommandResult] => [ @@ -335,7 +337,7 @@ export const circleCommand: Command = { if (input.kind === "number") r = input.value; else r = dist(s.center, input.point); const center = s.center; - return [idle("center")[0], { draft: null, done: true, commit: (p) => appendCircle(p, center, r, ctx) }]; + return [idle("center")[0], { draft: null, done: true, commit: opsMutation(() => appendCircle(center, r, ctx)) }]; } if (s.method === "ttr") { @@ -346,7 +348,7 @@ export const circleCommand: Command = { const center = r > EPS ? nearestCandidate(tangentCircleCenters(s.t1, s.t2, r), s.near1, s.near2) : null; // Kein Kandidat (z. B. Radius geometrisch unpassend) — ignorieren, weiter warten. if (!center) return [s, { draft: null }]; - return [idle("ttr")[0], { draft: null, done: true, commit: (p) => appendCircle(p, center, r, ctx) }]; + return [idle("ttr")[0], { draft: null, done: true, commit: opsMutation(() => appendCircle(center, r, ctx)) }]; } if (input.kind !== "point") return [s, { draft: null }]; const pick = pickTangentTarget(ctx.project, ctx.level.id, input.point); @@ -387,7 +389,7 @@ export const circleCommand: Command = { } const center = mid(s.a, pt); const r = dist(s.a, pt) / 2; - return [idle("twoPoint")[0], { draft: null, done: true, commit: (p) => appendCircle(p, center, r, ctx) }]; + return [idle("twoPoint")[0], { draft: null, done: true, commit: opsMutation(() => appendCircle(center, r, ctx)) }]; } // threePoint @@ -405,7 +407,7 @@ export const circleCommand: Command = { if (!circ) return [s, { draft: lineDraft(s.a, pt) }]; // kollinear — ignorieren, weiter warten return [ idle("threePoint")[0], - { draft: null, done: true, commit: (p) => appendCircle(p, circ.center, circ.r, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendCircle(circ.center, circ.r, ctx)) }, ]; }, diff --git a/src/commands/cmds/column.ts b/src/commands/cmds/column.ts index 7d6cf22f..a84fa172 100644 --- a/src/commands/cmds/column.ts +++ b/src/commands/cmds/column.ts @@ -22,9 +22,10 @@ import type { CommandResult, CommandState, CmdOption, - Project, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; /** Default-Ebene (Kategorie) für Stützen: „50" Tragwerk (Fallback: aktive). */ const COLUMN_CATEGORY = "50"; @@ -48,11 +49,9 @@ function currentProfile(): ColumnProfile { } /** Fügt die Stütze immutabel an `project.columns` an. */ -function appendColumn( - p: Project, - position: Vec2, +function appendColumn(position: Vec2, ctx: CommandContext, -): Project { +): CoreOp[] { const height = ctx.level.floorHeight != null && ctx.level.floorHeight > 0 ? ctx.level.floorHeight @@ -67,7 +66,7 @@ function appendColumn( rotation: 0, height, }; - return { ...p, columns: [...(p.columns ?? []), column] }; + return addItems("columns", [column]); } interface ColState extends CommandState { @@ -135,7 +134,7 @@ export const columnCommand: Command = { if (input.kind === "point") { return [ { phase: "done", lastPoint: null } as ColState, - { draft: null, done: true, commit: (p) => appendColumn(p, input.point, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendColumn(input.point, ctx)) }, ]; } return [s, { draft: null }]; diff --git a/src/commands/cmds/copy.ts b/src/commands/cmds/copy.ts index e49e66be..daf0d109 100644 --- a/src/commands/cmds/copy.ts +++ b/src/commands/cmds/copy.ts @@ -5,11 +5,11 @@ // → weitere Zielpunkte = weitere Kopien (Basispunkt bleibt), bis Esc/Enter. // // Die Auswahl kommt vorab über ctx.selection. Leere Auswahl → No-op + Hinweis. -// Der Commit nutzt `commitTransform` (op:"move", mode:"copy") — eine Kopie der +// Der Commit nutzt `transformMutation` (op:"move", mode:"copy") — eine Kopie der // Auswahl an die Endlage, Original unverändert; neue IDs via uniqueId (dort). import { - commitTransform, + transformMutation, hasTransformSelection, toTransformSel, transformPreview, @@ -136,7 +136,7 @@ export const copyCommand: Command = { next, { draft: copyDraft(ctx.project, sel, base, pt), - commit: (p) => commitTransform(p, toTransformSel(sel), "move", [base, pt], "copy", 1), + commit: transformMutation(toTransformSel(sel), "move", [base, pt], "copy", 1), }, ]; }, diff --git a/src/commands/cmds/detailref.ts b/src/commands/cmds/detailref.ts index 55b96f57..2754a667 100644 --- a/src/commands/cmds/detailref.ts +++ b/src/commands/cmds/detailref.ts @@ -14,10 +14,11 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const PREVIEW_RADIUS = 0.3; // Modell-Meter, deckt sich mit DETAILREF_RADIUS_M (drawing2d.ts) const DEFAULT_LABEL = "A"; @@ -39,7 +40,7 @@ function pointDraft(at: Vec2): ToolDraft { return { preview, vertices: [at] }; } -function appendDetailRef(p: Project, at: Vec2, ctx: CommandContext): Project { +function appendDetailRef(at: Vec2, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -47,7 +48,7 @@ function appendDetailRef(p: Project, at: Vec2, ctx: CommandContext): Project { categoryCode: ctx.defaultCategoryCode, geom: { shape: "detailref", at, label: DEFAULT_LABEL }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -68,7 +69,7 @@ export const detailrefCommand: Command = { if (input.kind !== "point") return [s, { draft: null }]; return [ { phase: "point", lastPoint: null } as DetailRefIdle, - { draft: null, done: true, commit: (p) => appendDetailRef(p, input.point, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendDetailRef(input.point, ctx)) }, ]; }, diff --git a/src/commands/cmds/dimension.ts b/src/commands/cmds/dimension.ts index a31f1191..e53c34d3 100644 --- a/src/commands/cmds/dimension.ts +++ b/src/commands/cmds/dimension.ts @@ -36,6 +36,8 @@ import type { ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation, patchItem } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); @@ -151,16 +153,11 @@ function offsetDraft(pts: Vec2[], offset: number, at: Vec2 | null): ToolDraft { } /** Committet eine Kette: neu anhängen (editId null) ODER dasselbe Element ersetzen. */ -function commitChain(p: Project, pts: Vec2[], offset: number, editId: string | null, ctx: CommandContext): Project { +function commitChain(p: Project, pts: Vec2[], offset: number, editId: string | null, ctx: CommandContext): CoreOp[] { const cleaned = pts.filter((pt, i) => i === 0 || dist(pts[i - 1], pt) >= EPS); - if (cleaned.length < 2) return p; // zu wenig gültige Punkte → nichts committen/ändern + if (cleaned.length < 2) return []; // zu wenig gültige Punkte → nichts committen/ändern if (editId) { - return { - ...p, - drawings2d: p.drawings2d.map((d) => - d.id === editId ? { ...d, geom: { shape: "dimension", pts: cleaned, offset } } : d, - ), - }; + return patchItem(p, "drawings2d", editId, (d): Drawing2D => ({ ...d, geom: { shape: "dimension", pts: cleaned, offset } })); } const d: Drawing2D = { id: uniqueId("dr2d"), @@ -169,7 +166,7 @@ function commitChain(p: Project, pts: Vec2[], offset: number, editId: string | n categoryCode: ctx.defaultCategoryCode, geom: { shape: "dimension", pts: cleaned, offset }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -237,7 +234,7 @@ export const dimensionCommand: Command = { const editId = s.editId; return [ { phase: "start", lastPoint: null }, - { draft: null, done: true, commit: (p) => commitChain(p, pts, offset, editId, ctx) }, + { draft: null, done: true, commit: opsMutation((p) => commitChain(p, pts, offset, editId, ctx)) }, ]; }, diff --git a/src/commands/cmds/ellipse.ts b/src/commands/cmds/ellipse.ts index 6e79a1cf..2c72920c 100644 --- a/src/commands/cmds/ellipse.ts +++ b/src/commands/cmds/ellipse.ts @@ -30,11 +30,12 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; @@ -138,15 +139,13 @@ function axisMinorDraft(center: Vec2, major: Vec2, cursor: Vec2 | null): ToolDra // ── Commit ─────────────────────────────────────────────────────────────────── -function appendEllipse( - p: Project, - center: Vec2, +function appendEllipse(center: Vec2, rx: number, ry: number, rotation: number, ctx: CommandContext, -): Project { - if (rx < EPS || ry < EPS) return p; +): CoreOp[] { + if (rx < EPS || ry < EPS) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -154,7 +153,7 @@ function appendEllipse( categoryCode: ctx.defaultCategoryCode, geom: { shape: "ellipse", center, rx, ry, rotation }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (method: EllipseMethod): [CommandState, CommandResult] => [ @@ -201,7 +200,7 @@ export const ellipseCommand: Command = { return [ns, { draft: boxDraft(pt, pt) }]; } const { center, rx, ry } = ellipseFromCorners(s.p0, pt); - return [idle("box")[0], { draft: null, done: true, commit: (p) => appendEllipse(p, center, rx, ry, 0, ctx) }]; + return [idle("box")[0], { draft: null, done: true, commit: opsMutation(() => appendEllipse(center, rx, ry, 0, ctx)) }]; } // axis @@ -221,7 +220,7 @@ export const ellipseCommand: Command = { const rotation = angleOf(center, major); return [ idle("axis")[0], - { draft: null, done: true, commit: (p) => appendEllipse(p, center, rx, ry, rotation, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendEllipse(center, rx, ry, rotation, ctx)) }, ]; }, diff --git a/src/commands/cmds/extrude.ts b/src/commands/cmds/extrude.ts index 58a5ec0b..f2645452 100644 --- a/src/commands/cmds/extrude.ts +++ b/src/commands/cmds/extrude.ts @@ -25,6 +25,8 @@ import type { Project, Vec2, } from "../types"; +import { addItems, opsMutation, removeItems } from "../../core"; +import type { CoreOp } from "../../core"; const HIT_TOL = 0.25; // Modell-Meter: Pick-Toleranz für die Profil-Wahl @@ -113,7 +115,7 @@ function appendExtrudedSolid( taper: number, sourceId: string, ctx: CommandContext, -): Project { +): CoreOp[] { const solid: ExtrudedSolid = { id: uniqueId("extrude"), type: "extrudedSolid", @@ -123,11 +125,7 @@ function appendExtrudedSolid( circle: profile.circle, ...(taper > 0 ? { taper } : {}), }; - return { - ...p, - drawings2d: p.drawings2d.filter((d) => d.id !== sourceId), - extrudedSolids: [...(p.extrudedSolids ?? []), solid], - }; + return [...removeItems(p, "drawings2d", [sourceId]), ...addItems("extrudedSolids", [solid])]; } // ── Zustand ─────────────────────────────────────────────────────────────────── @@ -177,7 +175,7 @@ const commitTaper = ( ctx: CommandContext, ): [CommandState, CommandResult] => [ { phase: "done", lastPoint: null } as ExDone, - { draft: null, done: true, commit: (p) => appendExtrudedSolid(p, profile, height, taper, sourceId, ctx) }, + { draft: null, done: true, commit: opsMutation((p) => appendExtrudedSolid(p, profile, height, taper, sourceId, ctx)) }, ]; export const extrudeCommand: Command = { diff --git a/src/commands/cmds/kote.ts b/src/commands/cmds/kote.ts index 80b14f13..284b8d80 100644 --- a/src/commands/cmds/kote.ts +++ b/src/commands/cmds/kote.ts @@ -14,11 +14,12 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; type KoteKind = "okFertig" | "ukFertig" | "okRoh" | "ukRoh"; const KIND_ORDER: KoteKind[] = ["okFertig", "ukFertig", "okRoh", "ukRoh"]; @@ -62,7 +63,7 @@ function valueDraft(at: Vec2, kind: KoteKind): ToolDraft { return { preview, vertices: [at] }; } -function appendKote(p: Project, at: Vec2, value: number, kind: KoteKind, ctx: CommandContext): Project { +function appendKote(at: Vec2, value: number, kind: KoteKind, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -70,7 +71,7 @@ function appendKote(p: Project, at: Vec2, value: number, kind: KoteKind, ctx: Co categoryCode: ctx.defaultCategoryCode, geom: { shape: "kote", at, value, kind, rotation: 0 }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -101,7 +102,7 @@ export const koteCommand: Command = { const { at, kind } = s; return [ { phase: "point", lastPoint: null }, - { draft: null, done: true, commit: (p) => appendKote(p, at, input.value, kind, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendKote(at, input.value, kind, ctx)) }, ]; }, diff --git a/src/commands/cmds/leader.ts b/src/commands/cmds/leader.ts index 635fdb61..4c5f9a2a 100644 --- a/src/commands/cmds/leader.ts +++ b/src/commands/cmds/leader.ts @@ -22,11 +22,12 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const DEFAULT_TEXT_HEIGHT_M = 0.25; const MAX_BENDS = 4; @@ -53,14 +54,12 @@ interface LeaderAnchor extends CommandState { } type LeaderState = LeaderTarget | LeaderBend | LeaderAnchor; -function appendLeaderText( - p: Project, - id: string, +function appendLeaderText(id: string, at: Vec2, target: Vec2, bends: Vec2[], ctx: CommandContext, -): Project { +): CoreOp[] { const d: Drawing2D = { id, type: "drawing2d", @@ -76,7 +75,7 @@ function appendLeaderText( ...(bends.length > 0 ? { leaderBendPoints: bends } : {}), }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -143,7 +142,7 @@ export const leaderCommand: Command = { { draft: null, done: true, - commit: (p) => appendLeaderText(p, id, pt, target, bends, ctx), + commit: opsMutation(() => appendLeaderText(id, pt, target, bends, ctx)), focusDrawingId: id, }, ]; diff --git a/src/commands/cmds/line.ts b/src/commands/cmds/line.ts index ffd22127..71d602e1 100644 --- a/src/commands/cmds/line.ts +++ b/src/commands/cmds/line.ts @@ -36,6 +36,8 @@ import type { ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -81,7 +83,7 @@ function lineDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { } /** Hängt eine 2D-Linie ans Projekt (immutabel). Farbe/Strich erbt die Kategorie. */ -function appendLine(p: import("../types").Project, a: Vec2, b: Vec2, ctx: CommandContext) { +function appendLine(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -89,7 +91,7 @@ function appendLine(p: import("../types").Project, a: Vec2, b: Vec2, ctx: Comman categoryCode: ctx.defaultCategoryCode, geom: { shape: "line", a, b }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } export const lineCommand: Command = { @@ -117,7 +119,7 @@ export const lineCommand: Command = { } const a = s.a; const next: LineDrawing = { phase: "end", a: pt, cursor: pt, lastPoint: pt }; - return [next, { draft: lineDraft(pt, pt), commit: (p) => appendLine(p, a, pt, ctx) }]; + return [next, { draft: lineDraft(pt, pt), commit: opsMutation(() => appendLine(a, pt, ctx)) }]; }, onMove: (state, point): [CommandState, CommandResult] => { diff --git a/src/commands/cmds/mirror.ts b/src/commands/cmds/mirror.ts index 73b0c51a..ae438eec 100644 --- a/src/commands/cmds/mirror.ts +++ b/src/commands/cmds/mirror.ts @@ -7,12 +7,12 @@ // wie Move/Copy). Ist sie leer, ist nichts zu spiegeln: kurzer No-op mit Hinweis // („Nichts gewählt") und Beenden. // -// Der Commit nutzt den bestehenden, getesteten `commitTransform` (op:"mirror", +// Der Commit nutzt den bestehenden, getesteten `transformMutation` (op:"mirror", // mode:"copy") — er spiegelt Wände UND alle 2D-Formen immutabel an der Achse und // hängt das Spiegelbild als KOPIE an (das Original bleibt stehen). Das ist das // klassische Mirror „Kopie spiegeln" (Rhino/Vectorworks-Default). -import { commitTransform, hasTransformSelection, toTransformSel } from "../../tools/transform"; +import { transformMutation, hasTransformSelection, toTransformSel } from "../../tools/transform"; import { transformPreview } from "../../tools/transform"; import type { Command, @@ -132,7 +132,7 @@ export const mirrorCommand: Command = { { draft: null, done: true, - commit: (p) => commitTransform(p, toTransformSel(sel), "mirror", [a, pt], "copy", 1), + commit: transformMutation(toTransformSel(sel), "mirror", [a, pt], "copy", 1), }, ]; }, diff --git a/src/commands/cmds/move.ts b/src/commands/cmds/move.ts index 3b82d416..0de4a794 100644 --- a/src/commands/cmds/move.ts +++ b/src/commands/cmds/move.ts @@ -9,11 +9,11 @@ // einen zweiten, divergierenden Pick-Pfad für die Objektwahl aufzumachen; die // Selektion läuft schon sauber über die Plan-Ansicht/Store). // -// Der Commit nutzt den bestehenden, getesteten `commitTransform` (op:"move", +// Der Commit nutzt den bestehenden, getesteten `transformMutation` (op:"move", // mode:"move") statt eine zweite Verschiebe-Logik zu duplizieren — er bewegt // Wände UND alle 2D-Formen immutabel an die Endlage. -import { commitTransform, hasTransformSelection, toTransformSel } from "../../tools/transform"; +import { transformMutation, hasTransformSelection, toTransformSel } from "../../tools/transform"; import { transformPreview } from "../../tools/transform"; import type { Command, @@ -145,7 +145,7 @@ export const moveCommand: Command = { { draft: null, done: true, - commit: (p) => commitTransform(p, toTransformSel(sel), "move", [base, pt], "move", 1), + commit: transformMutation(toTransformSel(sel), "move", [base, pt], "move", 1), }, ]; }, diff --git a/src/commands/cmds/multiline.ts b/src/commands/cmds/multiline.ts index ed97ae3e..9de29102 100644 --- a/src/commands/cmds/multiline.ts +++ b/src/commands/cmds/multiline.ts @@ -27,10 +27,11 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -76,8 +77,8 @@ function multilinePairs(a: Vec2, b: Vec2, spacing: number, sign: number, count: return out; } -function appendMultiline(p: Project, a: Vec2, b: Vec2, spacing: number, sign: number, count: number, ctx: CommandContext): Project { - if (segLen(a, b) < EPS) return p; +function appendMultiline(a: Vec2, b: Vec2, spacing: number, sign: number, count: number, ctx: CommandContext): CoreOp[] { + if (segLen(a, b) < EPS) return []; const pairs = multilinePairs(a, b, spacing, sign, count); const copies: Drawing2D[] = pairs.map(([pa, pb]) => ({ id: uniqueId("dr2d"), @@ -86,7 +87,7 @@ function appendMultiline(p: Project, a: Vec2, b: Vec2, spacing: number, sign: nu categoryCode: ctx.defaultCategoryCode, geom: { shape: "line", a: pa, b: pb }, })); - return { ...p, drawings2d: [...p.drawings2d, ...copies] }; + return addItems("drawings2d", copies); } const COUNT_OPTION: CmdOption = { id: "count", labelKey: "cmd.multiline.count" }; @@ -169,7 +170,7 @@ export const multilineCommand: Command = { const { a, b } = s; return [ idle()[0], - { draft: null, done: true, commit: (p) => appendMultiline(p, a, b, lastSpacing, lastSign, lastCount, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendMultiline(a, b, lastSpacing, lastSign, lastCount, ctx)) }, ]; } if (input.kind === "point") { @@ -177,7 +178,7 @@ export const multilineCommand: Command = { const { a, b } = s; return [ idle()[0], - { draft: null, done: true, commit: (p) => appendMultiline(p, a, b, lastSpacing, lastSign, lastCount, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendMultiline(a, b, lastSpacing, lastSign, lastCount, ctx)) }, ]; } return [s, { draft: null }]; diff --git a/src/commands/cmds/offset.ts b/src/commands/cmds/offset.ts index 9ab6a2ea..71643afa 100644 --- a/src/commands/cmds/offset.ts +++ b/src/commands/cmds/offset.ts @@ -29,6 +29,8 @@ import type { Project, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const HIT_TOL = 0.25; // Modell-Meter: Pick-Toleranz für die Kurvenwahl @@ -183,11 +185,11 @@ function offsetDraftShapes(curve: Curve, d: number): DraftShape[] { return [{ kind: "poly", pts: tess, closed: curve.closed }]; } -function appendOffset(p: Project, src: Drawing2D, d: number): Project { +function appendOffset(src: Drawing2D, d: number): CoreOp[] { const geom = offsetGeom(src, d); - if (!geom) return p; + if (!geom) return []; const copy: Drawing2D = { ...src, id: uniqueId("dr2d"), geom }; - return { ...p, drawings2d: [...p.drawings2d, copy] }; + return addItems("drawings2d", [copy]); } // ── Zustand ─────────────────────────────────────────────────────────────────── @@ -316,7 +318,7 @@ function offsetSideInput( const d = sign * mag; return [ { phase: "done", lastPoint: null } as OffDone, - { draft: null, done: true, commit: (p) => appendOffset(p, src, d) }, + { draft: null, done: true, commit: opsMutation(() => appendOffset(src, d)) }, ]; } @@ -327,7 +329,7 @@ function offsetSideInput( const d = sign * lastDistance; return [ { phase: "done", lastPoint: null } as OffDone, - { draft: null, done: true, commit: (p) => appendOffset(p, src, d) }, + { draft: null, done: true, commit: opsMutation(() => appendOffset(src, d)) }, ]; } diff --git a/src/commands/cmds/opening.ts b/src/commands/cmds/opening.ts index 58edd854..6e9992c0 100644 --- a/src/commands/cmds/opening.ts +++ b/src/commands/cmds/opening.ts @@ -22,10 +22,11 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; /** Default-Ebene (Kategorie) für Öffnungen: „21" Türen/Fenster (Fallback: aktive). */ const OPENING_CATEGORY = "21"; @@ -183,7 +184,7 @@ function posDraft(s: OpPos): ToolDraft { } /** Hängt eine Öffnung ans Projekt (immutabel). */ -function appendOpening(p: Project, s: OpPos, ctx: CommandContext): Project { +function appendOpening(s: OpPos, ctx: CommandContext): CoreOp[] { const len = Math.hypot(s.end.x - s.start.x, s.end.y - s.start.y); const width = Math.max(0.1, Math.min(s.width, len)); const position = Math.max(0, Math.min(s.posAlong, Math.max(0, len - width))); @@ -208,8 +209,7 @@ function appendOpening(p: Project, s: OpPos, ctx: CommandContext): Project { ? { hinge: s.hinge, swing: s.side, openingDir: s.dir, swingAngle: s.swingAngle } : {}), }; - const openings = p.openings ? [...p.openings, opening] : [opening]; - return { ...p, openings }; + return addItems("openings", [opening]); } const idle = (from?: OpState): [CommandState, CommandResult] => [ @@ -307,7 +307,7 @@ export const openingCommand: Command = { const ns: OpPos = { ...s, posAlong: proj.t, cursor: pt }; return [ idle(s)[0], - { draft: null, done: true, commit: (p) => appendOpening(p, ns, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendOpening(ns, ctx)) }, ]; }, @@ -325,7 +325,7 @@ export const openingCommand: Command = { const ns = s; return [ idle(s)[0], - { draft: null, done: true, commit: (p) => appendOpening(p, ns, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendOpening(ns, ctx)) }, ]; } return idle(s); diff --git a/src/commands/cmds/pointmarker.ts b/src/commands/cmds/pointmarker.ts index 963d73e4..9c9fa15b 100644 --- a/src/commands/cmds/pointmarker.ts +++ b/src/commands/cmds/pointmarker.ts @@ -11,10 +11,11 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const PREVIEW_RADIUS = 0.08; // Modell-Meter, deckt sich mit POINTMARKER_RADIUS_M (drawing2d.ts) const PREVIEW_CROSS = 0.12; @@ -39,7 +40,7 @@ function pointDraft(at: Vec2): ToolDraft { return { preview, vertices: [at] }; } -function appendPointMarker(p: Project, at: Vec2, ctx: CommandContext): Project { +function appendPointMarker(at: Vec2, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -47,7 +48,7 @@ function appendPointMarker(p: Project, at: Vec2, ctx: CommandContext): Project { categoryCode: ctx.defaultCategoryCode, geom: { shape: "pointmarker", at }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -68,7 +69,7 @@ export const pointmarkerCommand: Command = { if (input.kind !== "point") return [s, { draft: null }]; return [ { phase: "point", lastPoint: null } as PointMarkerIdle, - { draft: null, done: true, commit: (p) => appendPointMarker(p, input.point, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendPointMarker(input.point, ctx)) }, ]; }, diff --git a/src/commands/cmds/polygon.ts b/src/commands/cmds/polygon.ts index e9011b71..0bc17917 100644 --- a/src/commands/cmds/polygon.ts +++ b/src/commands/cmds/polygon.ts @@ -35,11 +35,12 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const MIN_SIDES = 3; @@ -148,8 +149,8 @@ function edgeDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { return { preview: [{ kind: "poly", pts, closed: true }], vertices: [a], hud: segmentHud(a, cursor) }; } -function appendPolygon(p: Project, center: Vec2, r: number, dir: Vec2 | null, ctx: CommandContext): Project { - if (r < EPS) return p; +function appendPolygon(center: Vec2, r: number, dir: Vec2 | null, ctx: CommandContext): CoreOp[] { + if (r < EPS) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -157,11 +158,11 @@ function appendPolygon(p: Project, center: Vec2, r: number, dir: Vec2 | null, ct categoryCode: ctx.defaultCategoryCode, geom: { shape: "polyline", pts: polygonPts(center, r, lastSides, lastMode, dir), closed: true }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } -function appendPolygonFromEdge(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project { - if (dist(a, b) < EPS) return p; +function appendPolygonFromEdge(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] { + if (dist(a, b) < EPS) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -169,7 +170,7 @@ function appendPolygonFromEdge(p: Project, a: Vec2, b: Vec2, ctx: CommandContext categoryCode: ctx.defaultCategoryCode, geom: { shape: "polyline", pts: polygonFromEdge(a, b, lastSides), closed: true }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -247,7 +248,7 @@ export const polygonCommand: Command = { } const a = s.a; const b = input.point; - return [idle()[0], { draft: null, done: true, commit: (p) => appendPolygonFromEdge(p, a, b, ctx) }]; + return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendPolygonFromEdge(a, b, ctx)) }]; } // phase "radius" @@ -266,7 +267,7 @@ export const polygonCommand: Command = { const center = s.center; return [ idle()[0], - { draft: null, done: true, commit: (p) => appendPolygon(p, center, r, dir, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendPolygon(center, r, dir, ctx)) }, ]; }, diff --git a/src/commands/cmds/polyline.ts b/src/commands/cmds/polyline.ts index df330b1b..53e01cfc 100644 --- a/src/commands/cmds/polyline.ts +++ b/src/commands/cmds/polyline.ts @@ -29,10 +29,11 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -200,13 +201,11 @@ function polyDraft( } /** Hängt eine 2D-Polylinie ans Projekt (immutabel). Farbe/Strich erbt die Kategorie. */ -function appendPolyline( - p: Project, - pts: Vec2[], +function appendPolyline(pts: Vec2[], bulges: number[], closed: boolean, ctx: CommandContext, -): Project { +): CoreOp[] { // `bulge` nur mitschreiben, wenn wirklich ein Bogen dabei ist — ein reiner // Geradenzug bleibt damit bitgleich zu vorher (additives Feld). const hasArc = bulges.some((b) => Math.abs(b) > EPS); @@ -219,7 +218,7 @@ function appendPolyline( ? { shape: "polyline", pts, closed, bulge: bulges.slice(0, closed ? pts.length : pts.length - 1) } : { shape: "polyline", pts, closed }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } /** Ruhezustand; behält den zuletzt gewählten Schließ-Modus bei. */ @@ -312,7 +311,7 @@ export const polylineCommand: Command = { const bl = [...s.bulges, closingBulge(s)]; return [ { phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle, - { draft: null, done: true, commit: (p) => appendPolyline(p, pts, bl, true, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, bl, true, ctx)) }, ]; } return [ @@ -371,7 +370,7 @@ export const polylineCommand: Command = { const bl = [...s.bulges, newBulge]; return [ { phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle, - { draft: null, done: true, commit: (p) => appendPolyline(p, pts, bl, true, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, bl, true, ctx)) }, ]; } const points = [...s.points, pt]; @@ -411,7 +410,7 @@ export const polylineCommand: Command = { const bl = close ? [...s.bulges, closingBulge(s)] : s.bulges; return [ { phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle, - { draft: null, done: true, commit: (p) => appendPolyline(p, pts, bl, close, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, bl, close, ctx)) }, ]; } return idle(s.closed, s.arc, s.tangent); diff --git a/src/commands/cmds/ray.ts b/src/commands/cmds/ray.ts index dff99793..dc4e66ed 100644 --- a/src/commands/cmds/ray.ts +++ b/src/commands/cmds/ray.ts @@ -14,10 +14,11 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -67,7 +68,7 @@ function rayDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { return draft; } -function appendRay(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project { +function appendRay(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -75,7 +76,7 @@ function appendRay(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project { categoryCode: ctx.defaultCategoryCode, geom: { shape: "ray", a, b }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } export const rayCommand: Command = { @@ -100,7 +101,7 @@ export const rayCommand: Command = { const a = s.a; return [ { phase: "start", lastPoint: null }, - { draft: null, done: true, commit: (p) => appendRay(p, a, pt, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendRay(a, pt, ctx)) }, ]; }, diff --git a/src/commands/cmds/rect.ts b/src/commands/cmds/rect.ts index a0f11504..8eec65bd 100644 --- a/src/commands/cmds/rect.ts +++ b/src/commands/cmds/rect.ts @@ -41,11 +41,12 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; @@ -310,8 +311,8 @@ function riseDraft(a: Vec2, b: Vec2, cursor: Vec2 | null): ToolDraft { // ── Commit ─────────────────────────────────────────────────────────────────── /** Achsparalleles Rechteck als `shape:"rect"` (geschlossen behandelt). */ -function appendRect(p: Project, min: Vec2, max: Vec2, ctx: CommandContext): Project { - if (max.x - min.x < EPS || max.y - min.y < EPS) return p; // Null-Rechteck +function appendRect(min: Vec2, max: Vec2, ctx: CommandContext): CoreOp[] { + if (max.x - min.x < EPS || max.y - min.y < EPS) return []; // Null-Rechteck const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -319,7 +320,7 @@ function appendRect(p: Project, min: Vec2, max: Vec2, ctx: CommandContext): Proj categoryCode: ctx.defaultCategoryCode, geom: { shape: "rect", min, max }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } /** @@ -327,11 +328,11 @@ function appendRect(p: Project, min: Vec2, max: Vec2, ctx: CommandContext): Proj * — `shape:"rect"` kann nur achsparallel, deshalb hier ein Ring aus vier Ecken. * Downstream (Füllung/Offset) behandelt einen geschlossenen Polygonzug als Ring. */ -function appendRotated(p: Project, pts: Vec2[], ctx: CommandContext): Project { +function appendRotated(pts: Vec2[], ctx: CommandContext): CoreOp[] { // Fläche prüfen: entartete Rechtecke verwerfen. const w = segLen(pts[0], pts[1]); const h = segLen(pts[1], pts[2]); - if (w < EPS || h < EPS) return p; + if (w < EPS || h < EPS) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -339,7 +340,7 @@ function appendRotated(p: Project, pts: Vec2[], ctx: CommandContext): Project { categoryCode: ctx.defaultCategoryCode, geom: { shape: "polyline", pts, closed: true }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } /** @@ -350,9 +351,9 @@ function appendRotated(p: Project, pts: Vec2[], ctx: CommandContext): Project { * passt (`roundedRectPts` liefert dann `null`, z. B. bei einem entarteten * Rechteck). */ -function appendRectRounded(p: Project, corners: Vec2[], ctx: CommandContext): Project { +function appendRectRounded(corners: Vec2[], ctx: CommandContext): CoreOp[] { const rr = roundedRectPts(corners, lastRadius); - if (!rr) return p; + if (!rr) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -360,7 +361,7 @@ function appendRectRounded(p: Project, corners: Vec2[], ctx: CommandContext): Pr categoryCode: ctx.defaultCategoryCode, geom: { shape: "polyline", pts: rr.pts, closed: true, bulge: rr.bulge }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (method: RectMethod): [CommandState, CommandResult] => [ @@ -436,14 +437,14 @@ export const rectCommand: Command = { { draft: null, done: true, - commit: (p) => { + commit: opsMutation(() => { const g = method === "center" ? centerGeom(a, pt) : rectGeom(a, pt); if (lastRadius >= EPS) { const corners = [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }]; - return appendRectRounded(p, corners, ctx); + return appendRectRounded(corners, ctx); } - return appendRect(p, g.min, g.max, ctx); - }, + return appendRect(g.min, g.max, ctx); + }), }, ]; } @@ -456,10 +457,10 @@ export const rectCommand: Command = { { draft: null, done: true, - commit: (p) => { + commit: opsMutation(() => { const corners = rotatedCorners(a, b, pt); - return lastRadius >= EPS ? appendRectRounded(p, corners, ctx) : appendRotated(p, corners, ctx); - }, + return lastRadius >= EPS ? appendRectRounded(corners, ctx) : appendRotated(corners, ctx); + }), }, ]; }, diff --git a/src/commands/cmds/revcloud.ts b/src/commands/cmds/revcloud.ts index f193e50d..bc65d3d1 100644 --- a/src/commands/cmds/revcloud.ts +++ b/src/commands/cmds/revcloud.ts @@ -19,10 +19,11 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const CLOSE_HIT = 0.15; // Modell-Meter: Klick nahe Startpunkt schliesst den Zug @@ -62,9 +63,9 @@ function revcloudDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { return draft; } -function appendRevcloud(p: Project, points: Vec2[], closed: boolean, ctx: CommandContext): Project { +function appendRevcloud(points: Vec2[], closed: boolean, ctx: CommandContext): CoreOp[] { const expanded = revisionCloudPts(points, closed, lastArcSize); - if (!expanded) return p; + if (!expanded) return []; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -72,7 +73,7 @@ function appendRevcloud(p: Project, points: Vec2[], closed: boolean, ctx: Comman categoryCode: ctx.defaultCategoryCode, geom: { shape: "polyline", pts: expanded.pts, closed, bulge: expanded.bulge }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -105,7 +106,7 @@ export const revcloudCommand: Command = { } if (input.id === "close" && s.phase === "next" && s.points.length >= 3) { const pts = s.points; - return [idle()[0], { draft: null, done: true, commit: (p) => appendRevcloud(p, pts, true, ctx) }]; + return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendRevcloud(pts, true, ctx)) }]; } return [s, { draft: null }]; } @@ -123,7 +124,7 @@ export const revcloudCommand: Command = { // Klick nahe Startpunkt (≥3 Punkte) → schliessen (committet als Ring). if (s.points.length >= 3 && segLen(s.points[0], pt) < CLOSE_HIT) { const pts = s.points; - return [idle()[0], { draft: null, done: true, commit: (p) => appendRevcloud(p, pts, true, ctx) }]; + return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendRevcloud(pts, true, ctx)) }]; } const points = [...s.points, pt]; const ns: RevcloudDrawing = { phase: "next", points, cursor: pt, lastPoint: pt }; @@ -142,7 +143,7 @@ export const revcloudCommand: Command = { const s = state as RevcloudState; if (s.phase === "next" && s.points.length >= 2) { const pts = s.points; - return [idle()[0], { draft: null, done: true, commit: (p) => appendRevcloud(p, pts, false, ctx) }]; + return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendRevcloud(pts, false, ctx)) }]; } return idle(); }, diff --git a/src/commands/cmds/roof.ts b/src/commands/cmds/roof.ts index b2666a8d..beda8d4a 100644 --- a/src/commands/cmds/roof.ts +++ b/src/commands/cmds/roof.ts @@ -20,10 +20,11 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; /** Default-Ebene (Kategorie) für Dächer („31 Dächer"). */ const ROOF_CATEGORY = "31"; @@ -93,10 +94,10 @@ function roofDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { } /** Hängt ein Dach ans Projekt (immutabel). Entartete Rechtecke werden verworfen. */ -function appendRoof(p: Project, a: Vec2, b: Vec2, shape: RoofShape, ctx: CommandContext): Project { +function appendRoof(a: Vec2, b: Vec2, shape: RoofShape, ctx: CommandContext): CoreOp[] { const w = Math.abs(b.x - a.x); const d = Math.abs(b.y - a.y); - if (w < 0.1 || d < 0.1) return p; + if (w < 0.1 || d < 0.1) return []; const roof: Roof = { id: uniqueId("RF"), type: "roof", @@ -111,8 +112,7 @@ function appendRoof(p: Project, a: Vec2, b: Vec2, shape: RoofShape, ctx: Command ridgeAxis: w >= d ? "x" : "y", thickness: 0.2, }; - const roofs = p.roofs ? [...p.roofs, roof] : [roof]; - return { ...p, roofs }; + return addItems("roofs", [roof]); } const idle = (shape: RoofShape = "sattel"): [CommandState, CommandResult] => [ @@ -157,7 +157,7 @@ export const roofCommand: Command = { const shape = s.shape; return [ { phase: "start", shape, lastPoint: null } as RoofIdle, - { draft: null, done: true, commit: (p) => appendRoof(p, a, b, shape, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendRoof(a, b, shape, ctx)) }, ]; }, diff --git a/src/commands/cmds/room.ts b/src/commands/cmds/room.ts index 222cbf5f..a76ec33b 100644 --- a/src/commands/cmds/room.ts +++ b/src/commands/cmds/room.ts @@ -31,10 +31,11 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -134,11 +135,10 @@ function defaultRoomName(ctx: CommandContext): string { } /** Hängt einen Raum ans Projekt (immutabel); entartete Umrisse werden verworfen. */ -function appendRoom(p: Project, boundary: Vec2[], ctx: CommandContext): Project { - if (boundary.length < 3 || polygonArea(boundary) < 1e-4) return p; +function appendRoom(boundary: Vec2[], ctx: CommandContext): CoreOp[] { + if (boundary.length < 3 || polygonArea(boundary) < 1e-4) return []; const room = buildRoom(ctx, boundary); - const rooms = p.rooms ? [...p.rooms, room] : [room]; - return { ...p, rooms }; + return addItems("rooms", [room]); } // ── Zustand ────────────────────────────────────────────────────────────────── @@ -254,7 +254,7 @@ export const roomCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null, mode: s.mode } as RoomIdle, - { draft: null, done: true, commit: (p) => appendRoom(p, pts, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendRoom(pts, ctx)) }, ]; } return [s, { draft: s.phase === "draw" ? manualDraft(s.points, s.cursor) : null }]; @@ -275,7 +275,7 @@ export const roomCommand: Command = { if (boundary && boundary.length >= 3) { return [ { phase: "start", lastPoint: null, mode: "inside" } as RoomIdle, - { draft: null, done: true, commit: (p) => appendRoom(p, boundary, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendRoom(boundary, ctx)) }, ]; } // Kein umschlossener Bereich getroffen → im Werkzeug bleiben (kein Commit). @@ -298,7 +298,7 @@ export const roomCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null, mode: s.mode } as RoomIdle, - { draft: null, done: true, commit: (p) => appendRoom(p, pts, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendRoom(pts, ctx)) }, ]; } const last = s.points[s.points.length - 1]; @@ -329,7 +329,7 @@ export const roomCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null, mode: s.mode } as RoomIdle, - { draft: null, done: true, commit: (p) => appendRoom(p, pts, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendRoom(pts, ctx)) }, ]; } return idle(s.mode); diff --git a/src/commands/cmds/rotate.ts b/src/commands/cmds/rotate.ts index 6b5b2e31..c63df93b 100644 --- a/src/commands/cmds/rotate.ts +++ b/src/commands/cmds/rotate.ts @@ -11,11 +11,11 @@ // // Die Auswahl kommt vorab über `ctx.selection` (erst selektieren, dann Befehl — // wie Move/Copy/Mirror). Gedreht wird über den bestehenden, getesteten -// `commitTransform` (op:"rotate", mode:"move") — er bewegt das ORIGINAL, es +// `transformMutation` (op:"rotate", mode:"move") — er bewegt das ORIGINAL, es // entsteht keine Kopie. import { - commitTransform, + transformMutation, hasTransformSelection, toTransformSel, transformPreview, @@ -125,7 +125,7 @@ export const rotateCommand: Command = { { draft: null, done: true, - commit: (p) => commitTransform(p, toTransformSel(sel), "rotate", pts, "move", 1), + commit: transformMutation(toTransformSel(sel), "rotate", pts, "move", 1), }, ]; } @@ -166,8 +166,7 @@ export const rotateCommand: Command = { { draft: null, done: true, - commit: (p) => - commitTransform(p, toTransformSel(sel), "rotate", [center, ref, pt], "move", 1), + commit: transformMutation(toTransformSel(sel), "rotate", [center, ref, pt], "move", 1), }, ]; }, diff --git a/src/commands/cmds/scale.ts b/src/commands/cmds/scale.ts index 44d6be48..31317253 100644 --- a/src/commands/cmds/scale.ts +++ b/src/commands/cmds/scale.ts @@ -15,7 +15,7 @@ // desselben Typs verändert — bewusste Grenze, s. PENDENZEN.md. import { - commitTransform, + transformMutation, hasTransformSelection, toTransformSel, transformPreview, @@ -110,7 +110,7 @@ export const scaleCommand: Command = { { draft: null, done: true, - commit: (p) => commitTransform(p, toTransformSel(sel), "scale", pts, "move", 1), + commit: transformMutation(toTransformSel(sel), "scale", pts, "move", 1), }, ]; } @@ -145,7 +145,7 @@ export const scaleCommand: Command = { { draft: null, done: true, - commit: (p) => commitTransform(p, toTransformSel(sel), "scale", [base, ref, pt], "move", 1), + commit: transformMutation(toTransformSel(sel), "scale", [base, ref, pt], "move", 1), }, ]; }, diff --git a/src/commands/cmds/scalebar.ts b/src/commands/cmds/scalebar.ts index 3790ea3a..569de532 100644 --- a/src/commands/cmds/scalebar.ts +++ b/src/commands/cmds/scalebar.ts @@ -13,10 +13,11 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const LENGTH_PRESETS = [0.5, 1, 2, 5, 10, 20, 50]; let lastLength = 1; @@ -59,7 +60,7 @@ function pointDraft(at: Vec2): ToolDraft { }; } -function appendScalebar(p: Project, at: Vec2, ctx: CommandContext): Project { +function appendScalebar(at: Vec2, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -67,7 +68,7 @@ function appendScalebar(p: Project, at: Vec2, ctx: CommandContext): Project { categoryCode: ctx.defaultCategoryCode, geom: { shape: "scalebar", at, segmentLength: lastLength, segments: lastSegments }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -96,7 +97,7 @@ export const scalebarCommand: Command = { return [s, { draft: null }]; } if (input.kind !== "point") return [s, { draft: null }]; - return [idle()[0], { draft: null, done: true, commit: (p) => appendScalebar(p, input.point, ctx) }]; + return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendScalebar(input.point, ctx)) }]; }, onMove: (state, point): [CommandState, CommandResult] => [state, { draft: pointDraft(point) }], diff --git a/src/commands/cmds/spline.ts b/src/commands/cmds/spline.ts index 0e9d1cfc..3b957061 100644 --- a/src/commands/cmds/spline.ts +++ b/src/commands/cmds/spline.ts @@ -25,10 +25,11 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const CLOSE_HIT = 0.08; // Modell-Meter: Klick nahe Startpunkt schließt den Zug @@ -80,7 +81,7 @@ function splineDraft(points: Vec2[], cursor: Vec2 | null, closed: boolean, mode: return draft; } -function appendSpline(p: Project, pts: Vec2[], closed: boolean, mode: CurveMode, ctx: CommandContext): Project { +function appendSpline(pts: Vec2[], closed: boolean, mode: CurveMode, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -88,7 +89,7 @@ function appendSpline(p: Project, pts: Vec2[], closed: boolean, mode: CurveMode, categoryCode: ctx.defaultCategoryCode, geom: { shape: "spline", pts, closed, mode }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (closed = false, curveMode: CurveMode = "fit"): [CommandState, CommandResult] => [ @@ -143,7 +144,7 @@ export const splineCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle, - { draft: null, done: true, commit: (p) => appendSpline(p, pts, true, s.curveMode, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendSpline(pts, true, s.curveMode, ctx)) }, ]; } return [s, { draft: splineDraft(s.points, s.cursor, s.closed, s.curveMode) }]; @@ -168,7 +169,7 @@ export const splineCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle, - { draft: null, done: true, commit: (p) => appendSpline(p, pts, true, s.curveMode, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendSpline(pts, true, s.curveMode, ctx)) }, ]; } const points = [...s.points, pt]; @@ -197,7 +198,7 @@ export const splineCommand: Command = { const close = s.closed && pts.length >= 3; return [ { phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle, - { draft: null, done: true, commit: (p) => appendSpline(p, pts, close, s.curveMode, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendSpline(pts, close, s.curveMode, ctx)) }, ]; } return idle(s.closed, s.curveMode); diff --git a/src/commands/cmds/stair.ts b/src/commands/cmds/stair.ts index 32a0a1a6..8c55f336 100644 --- a/src/commands/cmds/stair.ts +++ b/src/commands/cmds/stair.ts @@ -30,10 +30,11 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; /** Default-Ebene (Kategorie) für Treppen: „40" Treppen (Fallback: aktive). */ const STAIR_CATEGORY = "40"; @@ -241,7 +242,7 @@ function runDraft(s: StairRun, ctx: CommandContext): ToolDraft { } /** Hängt eine Treppe ans Projekt (immutabel) und aktualisiert die Defaults. */ -function appendStair(p: Project, s: StairRun, ctx: CommandContext): Project { +function appendStair(s: StairRun, ctx: CommandContext): CoreOp[] { const stair = buildStair(s, ctx); // Zuletzt genutzte Einstellungen für die nächste Treppe merken. stairDefaults.shape = s.shape; @@ -252,8 +253,7 @@ function appendStair(p: Project, s: StairRun, ctx: CommandContext): Project { stairDefaults.auftritt = s.auftritt; stairDefaults.steps = s.steps; stairDefaults.rise = s.rise; - const stairs = p.stairs ? [...p.stairs, stair] : [stair]; - return { ...p, stairs }; + return addItems("stairs", [stair]); } const idle = (from?: StairCmdState): [CommandState, CommandResult] => [ @@ -348,7 +348,7 @@ export const stairCommand: Command = { const ns: StairRun = { ...s, cursor: pt }; return [ idle(s)[0], - { draft: null, done: true, commit: (p) => appendStair(p, ns, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendStair(ns, ctx)) }, ]; }, @@ -365,7 +365,7 @@ export const stairCommand: Command = { const ns = s; return [ idle(s)[0], - { draft: null, done: true, commit: (p) => appendStair(p, ns, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendStair(ns, ctx)) }, ]; } return idle(s); diff --git a/src/commands/cmds/text.ts b/src/commands/cmds/text.ts index 65027aff..ec306206 100644 --- a/src/commands/cmds/text.ts +++ b/src/commands/cmds/text.ts @@ -10,7 +10,9 @@ import type { Drawing2D } from "../../model/types"; import { uniqueId } from "../../tools/types"; -import type { Command, CommandContext, CommandResult, CommandState, Project, Vec2 } from "../types"; +import type { Command, CommandContext, CommandResult, CommandState, Vec2 } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; /** Default-Schrifthöhe eines frei platzierten Texts in Modell-Metern. */ const DEFAULT_TEXT_HEIGHT_M = 0.25; @@ -20,7 +22,7 @@ interface TextIdle extends CommandState { } type TextState = TextIdle; -function appendEmptyText(p: Project, id: string, at: Vec2, ctx: CommandContext): Project { +function appendEmptyText(id: string, at: Vec2, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id, type: "drawing2d", @@ -28,7 +30,7 @@ function appendEmptyText(p: Project, id: string, at: Vec2, ctx: CommandContext): categoryCode: ctx.defaultCategoryCode, geom: { shape: "text", at, text: "", height: DEFAULT_TEXT_HEIGHT_M, angle: 0 }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -54,7 +56,7 @@ export const textCommand: Command = { { draft: null, done: true, - commit: (p) => appendEmptyText(p, id, at, ctx), + commit: opsMutation(() => appendEmptyText(id, at, ctx)), focusDrawingId: id, }, ]; diff --git a/src/commands/cmds/textbox.ts b/src/commands/cmds/textbox.ts index 804b87bd..38cc66e3 100644 --- a/src/commands/cmds/textbox.ts +++ b/src/commands/cmds/textbox.ts @@ -27,9 +27,10 @@ import type { CommandResult, CommandState, DraftShape, - Project, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; /** Default-Schrifthöhe einer Textspalte in Modell-Metern (= Baseline-Versatz vom Rahmen-Top). */ const DEFAULT_TEXT_HEIGHT_M = 0.25; @@ -84,7 +85,7 @@ function frameDraft(a: Vec2, cursor: Vec2): { preview: DraftShape[]; vertices: V }; } -function appendEmptyTextbox(p: Project, id: string, at: Vec2, width: number, ctx: CommandContext): Project { +function appendEmptyTextbox(id: string, at: Vec2, width: number, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id, type: "drawing2d", @@ -92,7 +93,7 @@ function appendEmptyTextbox(p: Project, id: string, at: Vec2, width: number, ctx categoryCode: ctx.defaultCategoryCode, geom: { shape: "text", at, text: "", height: DEFAULT_TEXT_HEIGHT_M, angle: 0, width }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -123,7 +124,7 @@ export const textboxCommand: Command = { { draft: null, done: true, - commit: (p) => appendEmptyTextbox(p, id, at, width, ctx), + commit: opsMutation(() => appendEmptyTextbox(id, at, width, ctx)), focusDrawingId: id, focusMinHeightM: heightM, }, diff --git a/src/commands/cmds/textpath.ts b/src/commands/cmds/textpath.ts index 0b1b2079..00b8bd9c 100644 --- a/src/commands/cmds/textpath.ts +++ b/src/commands/cmds/textpath.ts @@ -15,10 +15,11 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -59,7 +60,7 @@ function pathDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { return draft; } -function appendEmptyTextPath(p: Project, id: string, pts: Vec2[], ctx: CommandContext): Project { +function appendEmptyTextPath(id: string, pts: Vec2[], ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id, type: "drawing2d", @@ -67,7 +68,7 @@ function appendEmptyTextPath(p: Project, id: string, pts: Vec2[], ctx: CommandCo categoryCode: ctx.defaultCategoryCode, geom: { shape: "text", at: pts[0], text: "", height: DEFAULT_TEXT_HEIGHT_M, angle: 0, pathPts: pts }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -77,7 +78,7 @@ const idle = (): [CommandState, CommandResult] => [ function commitPath(pts: Vec2[], ctx: CommandContext): CommandResult { const id = uniqueId("dr2d"); - return { draft: null, done: true, commit: (p) => appendEmptyTextPath(p, id, pts, ctx), focusDrawingId: id }; + return { draft: null, done: true, commit: opsMutation(() => appendEmptyTextPath(id, pts, ctx)), focusDrawingId: id }; } export const textpathCommand: Command = { diff --git a/src/commands/cmds/wall.ts b/src/commands/cmds/wall.ts index c904fc44..6ee35578 100644 --- a/src/commands/cmds/wall.ts +++ b/src/commands/cmds/wall.ts @@ -31,6 +31,8 @@ import type { ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -109,7 +111,7 @@ function wallTypeForThickness( p: Project, base: WallType, thickness: number, -): { project: Project; wallTypeId: string } { +): { ops: CoreOp[]; wallTypeId: string } { const componentId = base.layers[0].componentId; const near = (a: number, b: number) => Math.abs(a - b) < 1e-4; const existing = p.wallTypes.find( @@ -118,13 +120,13 @@ function wallTypeForThickness( t.layers[0].componentId === componentId && near(t.layers[0].thickness, thickness), ); - if (existing) return { project: p, wallTypeId: existing.id }; + if (existing) return { ops: [], wallTypeId: existing.id }; const nt: WallType = { id: uniqueId("WT"), name: `${base.name} ${(thickness * 100).toFixed(0)} cm`, layers: [{ componentId, thickness }], }; - return { project: { ...p, wallTypes: [...p.wallTypes, nt] }, wallTypeId: nt.id }; + return { ops: addItems("wallTypes", [nt]), wallTypeId: nt.id }; } interface WallIdle extends CommandState { @@ -179,12 +181,12 @@ function appendWalls( pts: Vec2[], ctx: CommandContext, thickOverride: number | null, -): Project { +): CoreOp[] { const height = ctx.level.floorHeight && ctx.level.floorHeight > 0 ? ctx.level.floorHeight : DEFAULT_HEIGHT; // Dicke-Übersteuerung (nur einschichtig): passenden Wandtyp finden/erzeugen, // damit Plan/3D — die die Dicke aus dem Wandtyp lesen — korrekt darstellen. - let project = p; + let typeOps: CoreOp[] = []; let wallTypeId = activeWallTypeId(ctx); const base = activeWallType(ctx); if ( @@ -194,8 +196,8 @@ function appendWalls( thickOverride >= MIN_THICKNESS && Math.abs(thickOverride - wallTypeThickness(base)) > 1e-4 ) { - const r = wallTypeForThickness(project, base, thickOverride); - project = r.project; + const r = wallTypeForThickness(p, base, thickOverride); + typeOps = r.ops; wallTypeId = r.wallTypeId; } const newWalls: Wall[] = []; @@ -214,8 +216,8 @@ function appendWalls( height, }); } - if (newWalls.length === 0) return p; - return { ...project, walls: [...project.walls, ...newWalls] }; + if (newWalls.length === 0) return []; + return [...typeOps, ...addItems("walls", newWalls)]; } const idle = ( @@ -299,7 +301,7 @@ export const wallCommand: Command = { const to = s.thickOverride; return [ { phase: "start", lastPoint: null, thickOverride: to, single: s.single } as WallIdle, - { draft: null, done: true, commit: (p) => appendWalls(p, pts, ctx, to) }, + { draft: null, done: true, commit: opsMutation((p) => appendWalls(p, pts, ctx, to)) }, ]; } return idle(s.thickOverride, s.single); diff --git a/src/commands/cmds/wipeout.ts b/src/commands/cmds/wipeout.ts index d6d0d73f..2450767c 100644 --- a/src/commands/cmds/wipeout.ts +++ b/src/commands/cmds/wipeout.ts @@ -29,10 +29,11 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const CLOSE_HIT = 0.15; // Modell-Meter: Klick nahe Startpunkt schliesst den Zug @@ -59,7 +60,7 @@ function wipeoutDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { return draft; } -function appendWipeout(p: Project, points: Vec2[], ctx: CommandContext): Project { +function appendWipeout(points: Vec2[], ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -69,7 +70,7 @@ function appendWipeout(p: Project, points: Vec2[], ctx: CommandContext): Project background: MASK_COLOR, color: MASK_COLOR, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } const idle = (): [CommandState, CommandResult] => [ @@ -100,7 +101,7 @@ export const wipeoutCommand: Command = { // Klick nahe Startpunkt (≥3 Punkte) → schliessen (committet). if (s.points.length >= 3 && segLen(s.points[0], pt) < CLOSE_HIT) { const pts = s.points; - return [idle()[0], { draft: null, done: true, commit: (p) => appendWipeout(p, pts, ctx) }]; + return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendWipeout(pts, ctx)) }]; } const points = [...s.points, pt]; const ns: WipeoutDrawing = { phase: "next", points, cursor: pt, lastPoint: pt }; @@ -120,7 +121,7 @@ export const wipeoutCommand: Command = { const s = state as WipeoutState; if (s.phase === "next" && s.points.length >= 3) { const pts = s.points; - return [idle()[0], { draft: null, done: true, commit: (p) => appendWipeout(p, pts, ctx) }]; + return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendWipeout(pts, ctx)) }]; } return idle(); }, diff --git a/src/commands/cmds/xline.ts b/src/commands/cmds/xline.ts index 3f415185..cb5d1d13 100644 --- a/src/commands/cmds/xline.ts +++ b/src/commands/cmds/xline.ts @@ -14,10 +14,11 @@ import type { CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; +import { addItems, opsMutation } from "../../core"; +import type { CoreOp } from "../../core"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -66,7 +67,7 @@ function xlineDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { return draft; } -function appendXline(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project { +function appendXline(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", @@ -74,7 +75,7 @@ function appendXline(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project categoryCode: ctx.defaultCategoryCode, geom: { shape: "xline", a, b }, }; - return { ...p, drawings2d: [...p.drawings2d, d] }; + return addItems("drawings2d", [d]); } export const xlineCommand: Command = { @@ -99,7 +100,7 @@ export const xlineCommand: Command = { const a = s.a; return [ { phase: "start", lastPoint: null }, - { draft: null, done: true, commit: (p) => appendXline(p, a, pt, ctx) }, + { draft: null, done: true, commit: opsMutation(() => appendXline(a, pt, ctx)) }, ]; }, diff --git a/src/state/applyChange.perf.test.ts b/src/state/applyChange.perf.test.ts new file mode 100644 index 00000000..09990769 --- /dev/null +++ b/src/state/applyChange.perf.test.ts @@ -0,0 +1,57 @@ +// [K4] S3 Messung: typische Hochfrequenz-Aktionen auf einem grossen Projekt (3000 Wände) über den +// Store — Griff ziehen (100 Schritte, ein Undo-Schritt), Auswahl verschieben (300 Wände, 20-mal), +// Eigenschaft tippen (100 Zeichen, ein Undo-Schritt). Werte gehen nach stderr (TODO [K4]); die +// Grenzen sind grosszügig (Container unter Last), geprüft wird vor allem das Ergebnis. +import { describe, expect, it } from "vitest"; +import { getState } from "./appStore"; +import { sampleProject } from "../model/sampleProject"; +import type { Project, Wall } from "../model/types"; + +const st = () => getState(); + +function bigProject(n: number): Project { + const base = sampleProject.walls; + const walls: Wall[] = Array.from({ length: n }, (_, i) => ({ + ...base[i % base.length], + id: `w${i}`, + start: { x: i, y: 0 }, + end: { x: i + 1, y: 0 }, + })); + return { ...structuredClone(sampleProject), walls }; +} + +describe("Messung Store-Aktionen, 3000 Wände", () => { + it("Griff ziehen, Auswahl verschieben, Eigenschaft tippen", () => { + st().setProject(bigProject(3000)); + st().clearHistory(); + const depth0 = st().undoDepth; + + // Griff ziehen: 100 Mausschritte, ein Undo-Schritt. + let t = performance.now(); + for (let i = 0; i < 100; i++) st().moveGripOf(null, "w1500", 0, { x: 1500 + i * 0.01, y: 0.5 }); + const gripMs = (performance.now() - t) / 100; + expect(st().project.walls[1500].start).toEqual({ x: 1500 + 99 * 0.01, y: 0.5 }); + expect(st().undoDepth).toBe(depth0 + 1); + + // Auswahl verschieben: 300 Wände, 20 Verschiebungen. + const ids = Array.from({ length: 300 }, (_, i) => `w${i * 10}`); + t = performance.now(); + for (let i = 0; i < 20; i++) { + st().commitTransformOn({ wallIds: ids, drawingId: null }, "move", [{ x: 0, y: 0 }, { x: 0, y: 0.1 }], "move", 1); + } + const moveMs = (performance.now() - t) / 20; + expect(st().project.walls[10].start.y).toBeCloseTo(2, 9); + expect(st().project.walls[11].start.y).toBe(0); + + // Eigenschaft tippen: 100 Tastenschritte mit coalesceKey. + t = performance.now(); + for (let i = 0; i < 100; i++) st().updateWall("w42", { height: 2.5 + i / 1000 }, "typing:w42"); + const typeMs = (performance.now() - t) / 100; + expect(st().project.walls[42].height).toBeCloseTo(2.599, 9); + + process.stderr.write( + `3000 Wände (Store): Griff ziehen ${gripMs.toFixed(2)} ms/Schritt, Auswahl verschieben (300) ${moveMs.toFixed(2)} ms, Eigenschaft tippen ${typeMs.toFixed(2)} ms\n`, + ); + expect(gripMs + moveMs + typeMs).toBeLessThan(200); + }); +}); diff --git a/src/state/applyChange.test.ts b/src/state/applyChange.test.ts new file mode 100644 index 00000000..c7e00ac5 --- /dev/null +++ b/src/state/applyChange.test.ts @@ -0,0 +1,177 @@ +// [K4] S3 zweite Etappe: Store-Aktionen erzeugen Ops direkt (`applyChange`, `opsMutation`) statt +// Projekt → Projekt + `diffToOps`. Geprüft: Ops gehen unverändert an den Kern (Verlauf, Prüfung), +// Leseansicht und Kern-Dokument bleiben gleich — auch über Zufallsfolgen der umgestellten +// Aktionen mit Undo bis zum Anfang und Redo bis zum Ende. +import { beforeEach, describe, expect, it } from "vitest"; +import { getState, setState } from "./appStore"; +import { storeDocument } from "./historySlice"; +import { sampleProject } from "../model/sampleProject"; +import type { Drawing2D, Project, Vec2 } from "../model/types"; +import { applyOps } from "../core/ops"; +import { opsMutation, patchItem, removeItems } from "../core/opsBuild"; + +const st = () => getState(); + +function rng(seed: number) { + let x = seed >>> 0; + return () => ((x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296); +} + +function drawings(r: () => number): Drawing2D[] { + const v = (): Vec2 => ({ x: Math.round(r() * 100) / 10, y: Math.round(r() * 100) / 10 }); + const base = { type: "drawing2d" as const, levelId: "eg", categoryCode: "20" }; + const geoms = [ + { shape: "line", a: v(), b: v() }, + { shape: "polyline", pts: [v(), v(), v(), v()], closed: true, bulge: [0, 0.3, 0, 0] }, + { shape: "polyline", pts: [v(), v(), v(), v()], closed: false }, + { shape: "rect", min: { x: 0, y: 0 }, max: { x: 2, y: 1 } }, + { shape: "circle", center: v(), r: 1.5 }, + { shape: "arc", center: v(), r: 1, a0: 0.2, a1: 2 }, + { shape: "text", at: v(), text: "A", height: 0.3, angle: 0 }, + { shape: "dimension", pts: [v(), v(), v()], offset: 0.5 }, + ] as Drawing2D["geom"][]; + return geoms.map((geom, i) => ({ ...base, id: `d${i}`, geom }) as Drawing2D); +} + +/** Kern-Dokument == TS-Leseansicht (JSON). */ +function expectMirror(): void { + const p = st().project; + expect(JSON.parse(storeDocument(p).json())).toEqual(JSON.parse(JSON.stringify(p))); +} + +beforeEach(() => { + st().setProject(structuredClone(sampleProject)); + st().clearHistory(); +}); + +describe("applyChange", () => { + it("Ops gehen ohne Differenz an den Kern: ein Undo-Schritt, Protokoll = genau diese Ops", () => { + const before = st().project; + const w = before.walls[0]; + const ops = patchItem(before, "walls", w.id, { height: 3.3 }); + st().applyChange(ops); + expect(st().project.walls[0].height).toBe(3.3); + // Unveränderte Elemente und Listen behalten ihre Identität. + expect(st().project.walls[1]).toBe(before.walls[1]); + expect(st().project.drawingLevels).toBe(before.drawingLevels); + expect(st().recentOps().at(-1)).toEqual(ops); + expect(st().undoDepth).toBe(1); + st().undo(); + expect(st().project.walls[0].height).toBe(w.height); + expectMirror(); + }); + + it("leere Ops: kein Schritt; NaN: abgelehnt, Projekt unverändert", () => { + const before = st().project; + st().applyChange([]); + st().applyChange((p) => patchItem(p, "walls", "gibt-es-nicht", { height: 1 })); + expect(st().project).toBe(before); + expect(st().undoDepth).toBe(0); + st().applyChange((p) => patchItem(p, "walls", p.walls[0].id, { height: NaN })); + expect(st().project).toBe(before); + expect(st().undoDepth).toBe(0); + }); + + it("coalesceKey: Serie = ein Schritt; setProject(opsMutation) nimmt die Ops direkt", () => { + const id = st().project.walls[0].id; + for (let i = 0; i < 50; i++) st().applyChange((p) => patchItem(p, "walls", id, { height: 2 + i / 100 }), "drag"); + expect(st().undoDepth).toBe(1); + const m = opsMutation((p) => removeItems(p, "walls", [id])); + st().setProject(m); + expect(st().recentOps().at(-1)).toEqual([{ kind: "remove", collection: "walls", ids: [id] }]); + expect(st().undoDepth).toBe(2); + st().undo(); + st().undo(); + expect(st().project.walls[0].height).toBe(sampleProject.walls[0].height); + expectMirror(); + }); + + it("groupChanges: mehrere Aktionen = ein Undo-Schritt", () => { + const p0 = st().project; + st().groupChanges(() => { + st().patchLevel(p0.drawingLevels[0].id, { linePoints: undefined, name: "X" }); + st().setProject(opsMutation((p) => removeItems(p, "walls", [p.walls[0].id, p.walls[1].id]))); + }); + expect(st().undoDepth).toBe(1); + st().undo(); + expect(st().project).toEqual(p0); + }); +}); + +describe("groupChanges mit Schlüssel", () => { + it("Griff-Zug mit mitgeführten Ecken: alle Mausschritte = ein Undo-Schritt", () => { + const p0 = st().project; + const [a, b] = p0.walls; + for (let i = 0; i < 30; i++) { + st().groupChanges(() => { + st().moveElementByOf(null, a.id, { x: 0.01, y: 0 }); + st().moveGripOf(null, b.id, 0, { x: b.start.x + (i + 1) * 0.01, y: b.start.y }); + }, `bodyDrag::${a.id}`); + } + expect(st().undoDepth).toBe(1); + st().undo(); + expect(st().project).toEqual(p0); + expectMirror(); + }); +}); + +describe("Zufallsfolgen der umgestellten Aktionen", () => { + it("Leseansicht = Kern, jede Aktion = applyOps(vorher, ihre Ops), Undo/Redo exakt", () => { + for (let seed = 1; seed <= 12; seed++) { + const r = rng(seed); + const start: Project = { ...structuredClone(sampleProject), drawings2d: drawings(r) }; + setState({ project: start }); + st().clearHistory(); + const v = (): Vec2 => ({ x: r() * 10, y: r() * 10 }); + let committed = 0; + for (let k = 0; k < 60; k++) { + const s = st(); + const p = s.project; + const wid = p.walls[Math.floor(r() * p.walls.length)]?.id ?? "x"; + const did = p.drawings2d[Math.floor(r() * p.drawings2d.length)]?.id ?? "x"; + const lid = p.drawingLevels[Math.floor(r() * p.drawingLevels.length)]?.id ?? "x"; + const cid = p.ceilings?.[0]?.id ?? "x"; + const rmid = p.rooms?.[0]?.id ?? "x"; + const idx = Math.floor(r() * 4); + const n = Math.floor(r() * 14); + const depth = s.undoDepth; + try { + switch (n) { + case 0: s.moveGripOf(null, wid, idx % 2, v()); break; + case 1: s.moveGripOf(did, null, idx % 2, v()); break; + case 2: s.moveElementByOf(did, null, v()); break; + case 3: s.moveEdgeOf(null, wid, 0, 1, v()); break; + case 4: s.updateWall(wid, { height: 2 + r() }); break; + case 5: s.setElementColor("drawing2d", did, "#abcdef"); break; + case 6: s.commitTransformOn({ wallIds: [wid], drawingId: did }, idx % 2 ? "move" : "rotate", [v(), v(), v()], idx < 2 ? "move" : "copy", 1); break; + case 7: s.moveCeilingBy(cid, v()); break; + case 8: s.moveRoomGrip(rmid, idx, v()); break; + case 9: s.toggleLevelVisible(lid); break; + case 10: s.patchLevel(lid, { floorHeight: 2.5 + r() }); break; + case 11: s.setWallThickness(wid, 0.1 + r() * 0.3); break; + case 12: s.resizeElement("drawing2d", did, 1 + r(), 1 + r(), { fx: 0, fy: 0 }); break; + case 13: s.setProject(opsMutation((q) => removeItems(q, "drawings2d", [did]))); break; + } + } catch { + continue; // ungültige Griff-Indizes (z. B. Kante einer kurzen Polylinie) — wie bisher + } + if (st().project !== p) { + committed++; + // Ein Schritt mehr — oder gleich viele, wenn dieselbe Griff-Serie verschmolzen wurde. + expect(st().undoDepth - depth).toBeGreaterThanOrEqual(0); + expect(st().undoDepth - depth).toBeLessThanOrEqual(1); + expect(st().project).toEqual(applyOps(p, st().recentOps().at(-1)!)); + } + } + expect(committed).toBeGreaterThan(30); + expectMirror(); + const end = JSON.stringify(st().project); + while (st().canUndo) st().undo(); + expect(JSON.stringify(st().project)).toBe(JSON.stringify(start)); + expectMirror(); + while (st().canRedo) st().redo(); + expect(JSON.stringify(st().project)).toBe(end); + expectMirror(); + } + }); +}); diff --git a/src/state/groupActions.test.ts b/src/state/groupActions.test.ts index 9ebb631f..41292723 100644 --- a/src/state/groupActions.test.ts +++ b/src/state/groupActions.test.ts @@ -7,6 +7,7 @@ import { describe, it, expect } from "vitest"; import { + activeGroupOps, addNewElementsToActiveGroup, applyGroupDimming, applyGroupDimmingToPlan, @@ -21,6 +22,9 @@ import { import type { Primitive } from "../plan/generatePlan/shared"; import { materializeUnderlay, type Plan } from "../plan/generatePlan"; import type { Drawing2D, Group, Project } from "../model/types"; +import { applyOps } from "../core/ops"; +import type { CoreOp } from "../core/ops"; +import { addItems, replaceItem } from "../core/opsBuild"; const EMPTY_MEM = { wallIds: [] as string[], @@ -261,6 +265,31 @@ describe("addNewElementsToActiveGroup", () => { }); }); +describe("activeGroupOps ([K4] S3: Ops statt Differenz)", () => { + const mk = (id: string): Group => ({ id, wallIds: ["w1"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: [] }); + const line = (id: string) => + ({ id, type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } } }) as Project["drawings2d"][number]; + const wall = (id: string) => ({ id, start: { x: 0, y: 0 }, end: { x: 1, y: 0 } }) as unknown as Project["walls"][number]; + + it("gleiches Ergebnis wie addNewElementsToActiveGroup, Zufall", () => { + let x = 11; + const r = () => ((x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296); + for (let n = 0; n < 200; n++) { + const before: Project = { ...project([mk("g1"), mk("g2")]), drawings2d: [line("d0")], walls: [wall("w0")] }; + const ops: CoreOp[] = []; + const k = Math.floor(r() * 4); + if (k >= 1) ops.push(...addItems("drawings2d", [line(`a${n}`), line(`b${n}`)], r() < 0.5 ? 0 : undefined)); + if (k >= 2) ops.push(...addItems("walls", [wall(`w${n}x`)])); + if (k >= 3) ops.push(replaceItem("drawings2d", { ...line("d0"), color: "#f00" })); + const path = r() < 0.2 ? [] : r() < 0.5 ? ["g1"] : ["g2", "g1", "gx"]; + const after = applyOps(before, ops); + const legacy = addNewElementsToActiveGroup(before, after, path); + const viaOps = applyOps(before, [...ops, ...activeGroupOps(before, ops, path)]); + expect(viaOps).toEqual(legacy); + } + }); +}); + describe("ungroup", () => { it("löst genau EIN Level auf; Untergruppen bleiben als eigene Gruppen bestehen", () => { const inner: Group = { id: "g1", wallIds: ["w1"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: [] }; diff --git a/src/state/groupActions.ts b/src/state/groupActions.ts index 978c9502..e7591800 100644 --- a/src/state/groupActions.ts +++ b/src/state/groupActions.ts @@ -9,6 +9,10 @@ import type { Drawing2D, Group, Project } from "../model/types"; import type { Plan, UnderlayGroup } from "../core"; import { uniqueId } from "../tools/types"; import type { Primitive } from "../core"; +import { applyOps } from "../core"; +import type { CoreOp } from "../core"; +import { itemsOf, patchItem } from "../core"; +import type { EntityCollection } from "../core"; /** Mitglieds-IDs je Elementart — dieselbe Form wie `Group`, ohne `id`/`name`/`groupIds`. */ export interface GroupMembership { @@ -292,6 +296,56 @@ export function addNewElementsToActiveGroup( }; } +/** Liste je Mitgliedsart. */ +const COLLECTION_OF: Record = { + wallIds: "walls", + drawingIds: "drawings2d", + ceilingIds: "ceilings", + roomIds: "rooms", + stairIds: "stairs", + columnIds: "columns", + roofIds: "roofs", + openingIds: "openings", +}; + +/** + * Wie {@link addNewElementsToActiveGroup}, für eine Änderung als Ops ([K4] S3): die zusätzlichen + * Ops, die die neu eingefügten Elemente (`add`-Ops) der aktiven Gruppe zuschlagen — ohne Differenz + * über alle Listen. Leer ohne aktive Gruppe oder ohne neue Elemente. + */ +export function activeGroupOps(before: Project, ops: readonly CoreOp[], groupPath: string[]): CoreOp[] { + if (groupPath.length === 0) return []; + const addedIds = new Set(); + const touched = new Set(); + for (const op of ops) { + if (op.kind !== "add") continue; + touched.add(op.collection); + for (const e of op.items) addedIds.add(e.id); + } + if (addedIds.size === 0) return []; + const after = applyOps(before, ops); + const activeId = groupPath[groupPath.length - 1]; + const g = (after.groups ?? []).find((x) => x.id === activeId); + if (!g) return []; + const added = { ...EMPTY_MEMBERSHIP }; + for (const k of KEYS) { + const coll = COLLECTION_OF[k]; + if (!touched.has(coll)) continue; + // Reihenfolge wie in der Liste (wie `newIds`); vorher vorhandene ids sind nie neu. + const existed = new Set(); + for (const e of itemsOf(before, coll)) { + const id = (e as { id: string }).id; + if (addedIds.has(id)) existed.add(id); + } + added[k] = itemsOf(after, coll) + .map((e) => (e as { id: string }).id) + .filter((id) => addedIds.has(id) && !existed.has(id)); + } + if (KEYS.every((k) => added[k].length === 0)) return []; + const merged: Group = { ...g, ...mergeMembership(g, added) }; + return patchItem(after, "groups", activeId, () => merged); +} + /** * Erzeugt eine neue Gruppe aus einer Mengen-Auswahl (+ optional bereits * gewählte Gruppen, die dabei als Untergruppen verschachtelt werden — „zwei diff --git a/src/state/projectSlice.ts b/src/state/projectSlice.ts index 6e5e940d..f48066b2 100644 --- a/src/state/projectSlice.ts +++ b/src/state/projectSlice.ts @@ -10,6 +10,15 @@ import { diffToOps } from "../core/ops"; import type { CoreOp } from "../core/ops"; +import { + addItems, + fieldOps, + isOpsMutation, + patchItem, + patchItems, + removeItems, + setField, +} from "../core"; import { withVertexType, type PolylineVertexType } from "../core"; import { sampleProject } from "../model/sampleProject"; import { @@ -37,7 +46,7 @@ import { PEN_FALLBACK_WEIGHT, } from "../model/penSets"; import { lineIntersect } from "../model/geometry"; -import { commitTransform } from "../tools/transform"; +import { transformOps } from "../tools/transform"; import type { CopyMode, TransformOp, TransformSelection } from "../tools/transform"; import { uniqueId } from "../tools/types"; import { centroid as roomCentroid } from "../core"; @@ -71,6 +80,12 @@ export interface ProjectSlice { * Implementierung unten. */ setProject: (next: Project | ((p: Project) => Project), coalesceKey?: string) => void; + /** + * Änderung direkt als Ops ([K4] S3): `ops` oder ein Op-Bauer auf dem aktuellen Projekt + * (`core/opsBuild.ts`). Geht ohne `diffToOps` an den Kern (Prüfung, Verlauf); sonst wie + * {@link setProject} (gleicher `coalesceKey` im Zeitfenster = ein Undo-Schritt). + */ + applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[]), coalesceKey?: string) => void; /** Die zuletzt angewendeten Ops (JSON-serialisierbar), jüngste zuletzt. */ recentOps: () => CoreOp[][]; @@ -447,17 +462,41 @@ export function createProjectSlice( const history = createHistorySlice(api as unknown as StoreApi); + // Kern-Commit einer Op-Folge auf `s.project` (Prüfung, Verlauf, Leseansicht nachführen). + // Verstösse werden zurückgerollt und gemeldet. + const commitOps = ( + s: { project: Project }, + ops: readonly CoreOp[], + coalesceKey: string | undefined, + ): Partial => { + if (ops.length === 0) return {}; + 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.slice()); + if (opLog.length > OP_LOG_LIMIT) opLog.shift(); + return { project: res.project, ...historyPatch(doc) }; + }; + // Bequemer immutabler Projekt-Updater (wie setProject in App). Zweiter, // optionaler Parameter `coalesceKey`: NUR von den paar bekannten - // Hochfrequenz-Aktionen (Grip-Drag & Co., s. u.) gesetzt — alle anderen ~50 - // Aktionen in dieser Datei rufen `setProject(fn)` ohne Key auf und pushen - // damit IMMER diskret (kein Koaleszieren zwischen unterschiedlichen - // Aktionen möglich, auch nicht bei zufällig identischem Timing in Tests). + // Hochfrequenz-Aktionen (Grip-Drag & Co., s. u.) gesetzt — alle anderen + // Aktionen rufen ohne Key auf und pushen damit IMMER diskret (kein + // Koaleszieren zwischen unterschiedlichen Aktionen möglich, auch nicht bei + // zufällig identischem Timing in Tests). + // [K4] S3: Projekt → Projekt-Funktionen gehen über `diffToOps` (Adapter für die Aktionen, die noch + // nicht umgestellt sind); Funktionen aus `opsMutation` tragen ihre Ops mit und sparen die Differenz. const setProject = ( next: Project | ((p: Project) => Project), coalesceKey?: string, ) => set((s) => { + if (isOpsMutation(next)) return commitOps(s, next.toOps(s.project), coalesceKey); const wanted = typeof next === "function" ? (next as (p: Project) => Project)(s.project) : next; // No-Op-Schutz: echte Immutable-Updates liefern bei tatsächlicher @@ -467,22 +506,16 @@ export function createProjectSlice( if (wanted === s.project) return {}; // Das Projekt ändert sich NUR über Ops (core/ops.ts): die gewünschte Änderung wird in // eine Op-Folge übersetzt; der Kern prüft (NaN, doppelte ids), wendet an und zeichnet den - // Undo-Schritt auf. Verstösse werden zurückgerollt und gemeldet. - const ops = diffToOps(s.project, wanted); - if (ops.length === 0) return {}; - 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(); - return { project: res.project, ...historyPatch(doc) }; + // Undo-Schritt auf. + return commitOps(s, diffToOps(s.project, wanted), coalesceKey); }); + // Änderung direkt als Ops (ohne Differenz), s. `ProjectSlice.applyChange`. + const applyChange = ( + ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[]), + coalesceKey?: string, + ) => set((s) => commitOps(s, typeof ops === "function" ? ops(s.project) : ops, coalesceKey)); + return { ...history, @@ -493,31 +526,28 @@ export function createProjectSlice( project: sampleProject, setProject, + applyChange, recentOps: () => opLog.slice(), // ── Zeichnungsebenen ─────────────────────────────────────────────────── toggleLevelVisible: (id) => - setProject((p) => ({ - ...p, - drawingLevels: p.drawingLevels.map((z) => - z.id === id ? { ...z, visible: !z.visible } : z, - ), - })), + applyChange((p) => patchItem(p, "drawingLevels", id, (z) => ({ ...z, visible: !z.visible }))), patchActiveFloor: (patch) => { const activeLevelId = get().activeLevelId; - setProject((p) => ({ - ...p, - drawingLevels: recomputeFloorElevations( - p.drawingLevels.map((z) => - z.id === activeLevelId ? { ...z, ...patch } : z, + applyChange((p) => + fieldOps( + p, + "drawingLevels", + recomputeFloorElevations( + p.drawingLevels.map((z) => (z.id === activeLevelId ? { ...z, ...patch } : z)), ), ), - })); + ); }, addFloor: () => - setProject((p) => { + applyChange((p) => { const n = p.drawingLevels.filter((z) => z.kind === "floor").length + 1; const floor: DrawingLevel = { id: `floor-${Date.now()}`, @@ -528,14 +558,11 @@ export function createProjectSlice( floorHeight: 2.6, cutHeight: 1.0, }; - return { - ...p, - drawingLevels: recomputeFloorElevations([...p.drawingLevels, floor]), - }; + return fieldOps(p, "drawingLevels", recomputeFloorElevations([...p.drawingLevels, floor])); }), addDrawing: () => - setProject((p) => { + applyChange((p) => { const n = p.drawingLevels.filter((z) => z.kind === "drawing").length + 1; const drawing: DrawingLevel = { id: `drawing-${Date.now()}`, @@ -544,13 +571,13 @@ export function createProjectSlice( visible: true, locked: false, }; - return { ...p, drawingLevels: [...p.drawingLevels, drawing] }; + return addItems("drawingLevels", [drawing]); }), // Schnitt/Ansicht sind vorerst Platzhalter ohne Schnittlinie (linePoints // bleibt undefined, bis die Schnitt-UI existiert — siehe toSection.ts). addSection: () => - setProject((p) => { + applyChange((p) => { const n = p.drawingLevels.filter((z) => z.kind === "section").length + 1; const section: DrawingLevel = { id: `section-${Date.now()}`, @@ -559,11 +586,11 @@ export function createProjectSlice( visible: true, locked: false, }; - return { ...p, drawingLevels: [...p.drawingLevels, section] }; + return addItems("drawingLevels", [section]); }), addElevation: () => - setProject((p) => { + applyChange((p) => { const n = p.drawingLevels.filter((z) => z.kind === "elevation").length + 1; const elevation: DrawingLevel = { id: `elevation-${Date.now()}`, @@ -572,7 +599,7 @@ export function createProjectSlice( visible: true, locked: false, }; - return { ...p, drawingLevels: [...p.drawingLevels, elevation] }; + return addItems("drawingLevels", [elevation]); }), // Neue freie Zeichnungsebene mit explizitem Namen anlegen und ihre ID @@ -580,7 +607,7 @@ export function createProjectSlice( // (Dialog); leere Eingabe fällt auf den Default-Namen zurück. addDrawingLevel: (name) => { const id = `drawing-${Date.now()}`; - setProject((p) => { + applyChange((p) => { const n = p.drawingLevels.filter((z) => z.kind === "drawing").length + 1; const drawing: DrawingLevel = { id, @@ -589,30 +616,26 @@ export function createProjectSlice( visible: true, locked: false, }; - return { ...p, drawingLevels: [...p.drawingLevels, drawing] }; + return addItems("drawingLevels", [drawing]); }); return id; }, - importDrawings: (drawings) => - setProject((p) => - drawings.length - ? { ...p, drawings2d: [...p.drawings2d, ...drawings] } - : p, - ), + importDrawings: (drawings) => applyChange(addItems("drawings2d", drawings)), patchLevel: (id, patch) => - setProject((p) => ({ - ...p, - drawingLevels: recomputeFloorElevations( - p.drawingLevels.map((z) => (z.id === id ? { ...z, ...patch } : z)), + applyChange((p) => + fieldOps( + p, + "drawingLevels", + recomputeFloorElevations(p.drawingLevels.map((z) => (z.id === id ? { ...z, ...patch } : z))), ), - })), + ), duplicateLevel: (id) => - setProject((p) => { + applyChange((p) => { const i = p.drawingLevels.findIndex((z) => z.id === id); - if (i < 0) return p; + if (i < 0) return []; const src = p.drawingLevels[i]; const clone: DrawingLevel = { ...src, @@ -621,7 +644,7 @@ export function createProjectSlice( }; const next = [...p.drawingLevels]; next.splice(i + 1, 0, clone); - return { ...p, drawingLevels: recomputeFloorElevations(next) }; + return fieldOps(p, "drawingLevels", recomputeFloorElevations(next)); }), // Zeichnungsebene löschen (≥1 behalten). War es das aktive Geschoss, auf @@ -634,35 +657,27 @@ export function createProjectSlice( const fallback = project.drawingLevels.find((z) => z.id !== id); if (fallback) set({ activeLevelId: fallback.id }); } - setProject((p) => { + applyChange((p) => { const removedWallIds = new Set( p.walls.filter((w) => w.floorId === id).map((w) => w.id), ); - return { - ...p, - drawingLevels: recomputeFloorElevations( - p.drawingLevels.filter((z) => z.id !== id), - ), - walls: p.walls.filter((w) => w.floorId !== id), - ceilings: (p.ceilings ?? []).filter((c) => c.floorId !== id), - stairs: (p.stairs ?? []).filter((s) => s.floorId !== id), - rooms: (p.rooms ?? []).filter((r) => r.floorId !== id), - openings: (p.openings ?? []).filter( - (o) => !removedWallIds.has(o.hostWallId), - ), - }; + return [ + ...fieldOps(p, "drawingLevels", recomputeFloorElevations(p.drawingLevels.filter((z) => z.id !== id))), + ...removeItems(p, "walls", removedWallIds), + ...removeItems(p, "ceilings", (c) => c.floorId === id), + ...removeItems(p, "stairs", (s) => s.floorId === id), + ...removeItems(p, "rooms", (r) => r.floorId === id), + ...removeItems(p, "openings", (o) => removedWallIds.has(o.hostWallId)), + ]; }); }, // ── Ebenen (Kategorien) ──────────────────────────────────────────────── toggleCategoryVisible: (code) => - setProject((p) => ({ - ...p, - layers: toggleCategoryByCode(p.layers, code), - })), + applyChange((p) => fieldOps(p, "layers", toggleCategoryByCode(p.layers, code))), addCategory: () => - setProject((p) => { + applyChange((p) => { const code = nextFreeCode(p.layers); const category: LayerCategory = { code, @@ -672,17 +687,14 @@ export function createProjectSlice( visible: true, locked: false, }; - return { ...p, layers: [...p.layers, category] }; + return [setField("layers", [...p.layers, category])]; }), patchCategory: (code, patch) => - setProject((p) => ({ - ...p, - layers: patchCategoryByCode(p.layers, code, patch), - })), + applyChange((p) => fieldOps(p, "layers", patchCategoryByCode(p.layers, code, patch))), addSubCategory: (parentCode) => - setProject((p) => { + applyChange((p) => { const code = nextFreeCode(p.layers); const child: LayerCategory = { code, @@ -692,27 +704,27 @@ export function createProjectSlice( visible: true, locked: false, }; - return { ...p, layers: addChildByCode(p.layers, parentCode, child) }; + return fieldOps(p, "layers", addChildByCode(p.layers, parentCode, child)); }), duplicateCategory: (code) => - setProject((p) => { + applyChange((p) => { const src = findCategory(p.layers, code); - if (!src) return p; + if (!src) return []; const clone: LayerCategory = { ...src, code: nextFreeCode(p.layers), name: t("default.copySuffixLayer", { name: src.name }), children: undefined, }; - return { ...p, layers: insertAfterCode(p.layers, code, clone) }; + return fieldOps(p, "layers", insertAfterCode(p.layers, code, clone)); }), deleteCategory: (code) => - setProject((p) => { - if (flattenCategories(p.layers).length <= 1) return p; // letzte behalten + applyChange((p) => { + if (flattenCategories(p.layers).length <= 1) return []; // letzte behalten const src = findCategory(p.layers, code); - if (!src) return p; + if (!src) return []; const codes = new Set(flattenCategories([src]).map((c) => c.code)); const usedByWall = p.walls.some((w) => codes.has(w.categoryCode)); const usedByOpening = (p.openings ?? []).some((o) => @@ -720,18 +732,13 @@ export function createProjectSlice( ); if (usedByWall || usedByOpening) { get().notify(t("alert.layerInUse", { code: src.code, name: src.name }), "warning"); - return p; + return []; } - return { ...p, layers: removeByCode(p.layers, code) }; + return fieldOps(p, "layers", removeByCode(p.layers, code)); }), assignWallCategory: (wallId, code) => - setProject((p) => ({ - ...p, - walls: p.walls.map((w) => - w.id === wallId ? { ...w, categoryCode: code } : w, - ), - })), + applyChange((p) => patchItem(p, "walls", wallId, { categoryCode: code })), // ── Sichtbarkeits-Kombinationen ──────────────────────────────────────── snapshotLayerVisibility: () => { @@ -743,10 +750,7 @@ export function createProjectSlice( }, applyLayerVisibility: (codes) => - setProject((p) => ({ - ...p, - layers: applyVisibilityByCode(p.layers, codes), - })), + applyChange((p) => fieldOps(p, "layers", applyVisibilityByCode(p.layers, codes))), snapshotDrawingVisibility: () => { const out: Record = {}; @@ -755,12 +759,9 @@ export function createProjectSlice( }, applyDrawingVisibility: (ids) => - setProject((p) => ({ - ...p, - drawingLevels: p.drawingLevels.map((z) => - z.id in ids ? { ...z, visible: ids[z.id] } : z, - ), - })), + applyChange((p) => + patchItems(p, "drawingLevels", (z) => z.id in ids, (z) => ({ ...z, visible: ids[z.id] })), + ), // ── Ressourcen ───────────────────────────────────────────────────────── patchComponent: (id, patch) => @@ -1100,10 +1101,9 @@ export function createProjectSlice( })), insertDrawingPoint: (drawingId, segIndex, pt) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => { - if (d.id !== drawingId || d.geom.shape !== "polyline") return d; + applyChange((p) => + patchItem(p, "drawings2d", drawingId, (d) => { + if (d.geom.shape !== "polyline") return d; const g = d.geom; const n = g.pts.length; const last = segIndex === n - 1; @@ -1128,44 +1128,36 @@ export function createProjectSlice( : undefined; return { ...d, geom: { ...g, pts, ...(nextBulge ? { bulge: nextBulge } : {}) } }; }), - })), + ), setPolylineVertexType: (drawingId, index, type) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => { - if (d.id !== drawingId || d.geom.shape !== "polyline" || d.locked) return d; + applyChange((p) => + patchItem(p, "drawings2d", drawingId, (d) => { + if (d.geom.shape !== "polyline" || d.locked) return d; const g = d.geom; const bulge = withVertexType(g, index, type); const { bulge: _old, ...rest } = g; return { ...d, geom: bulge.some((b) => b !== 0) ? { ...rest, bulge } : rest }; }), - })), + ), deleteDrawingPoint: (drawingId, index) => - setProject((p) => { + applyChange((p) => { const d = p.drawings2d.find((x) => x.id === drawingId); - if (!d || d.geom.shape !== "polyline") return p; + if (!d || d.geom.shape !== "polyline") return []; const g = d.geom; const min = g.closed ? 4 : 3; if (g.pts.length < min) { get().notify(t("alert.polylineMinPoints"), "warning"); - return p; + return []; } - if (index < 0 || index >= g.pts.length) return p; + if (index < 0 || index >= g.pts.length) return []; const pts = g.pts.filter((_, i) => i !== index); // Zwei Segmente werden zu einem: der Bulge des ENTFERNTEN Segments // fällt weg, das verbleibende behält seinen Wert (die exakte // Bogenform lässt sich nicht erhalten, wenn ihr Stützpunkt entfällt). const bulge = g.bulge ? g.bulge.filter((_, i) => i !== index) : undefined; - return { - ...p, - drawings2d: p.drawings2d.map((x) => - x.id === drawingId - ? { ...x, geom: { ...g, pts, ...(bulge ? { bulge } : {}) } } - : x, - ), - }; + return patchItem(p, "drawings2d", drawingId, (x) => ({ ...x, geom: { ...g, pts, ...(bulge ? { bulge } : {}) } })); }), // ── Editier-Griffe ───────────────────────────────────────────────────── @@ -1173,129 +1165,91 @@ export function createProjectSlice( // (kein Draft/Commit-Muster wie bei den Zeichenwerkzeugen) — daher mit // coalesceKey, damit EIN Drag EINEN Undo-Schritt erzeugt statt vieler. moveGripOf: (drawingId, wallId, index, pt, scaleDenominator) => - setProject( + applyChange( (p) => moveGrip(p, drawingId, wallId, index, pt, scaleDenominator), `moveGripOf:${drawingId ?? ""}:${wallId ?? ""}:${index}`, ), moveElementByOf: (drawingId, wallId, delta) => - setProject( + applyChange( (p) => moveElementBy(p, drawingId, wallId, delta), `moveElementByOf:${drawingId ?? ""}:${wallId ?? ""}`, ), moveEdgeOf: (drawingId, wallId, aIndex, bIndex, delta) => - setProject( + applyChange( (p) => moveEdge(p, drawingId, wallId, aIndex, bIndex, delta), `moveEdgeOf:${drawingId ?? ""}:${wallId ?? ""}:${aIndex}:${bIndex}`, ), // ── Selektions-Attribute ─────────────────────────────────────────────── setElementColor: (kind, id, color) => - setProject((p) => { - if (kind === "drawing2d") { - return { - ...p, - drawings2d: p.drawings2d.map((d) => - d.id === id ? { ...d, color } : d, - ), - }; - } - return { - ...p, - walls: p.walls.map((w) => (w.id === id ? { ...w, color } : w)), - }; - }), + applyChange((p) => + kind === "drawing2d" ? patchItem(p, "drawings2d", id, { color }) : patchItem(p, "walls", id, { color }), + ), // Strichstärke gibt es als direktes Feld NUR auf Drawing2D; bei unbekannter // ID bleibt das Projekt unverändert (No-op). - setElementWeight: (id, weightMm) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => - d.id === id ? { ...d, weightMm } : d, - ), - })), + setElementWeight: (id, weightMm) => applyChange((p) => patchItem(p, "drawings2d", id, { weightMm })), // Füllschraffur NUR für Drawing2D; `null` entfernt die Schraffur (Feld weg). setElementFill: (id, hatchId) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => { - if (d.id !== id) return d; + applyChange((p) => + patchItem(p, "drawings2d", id, (d) => { if (hatchId === null) { const { hatchId: _omit, ...rest } = d; return rest; } return { ...d, hatchId }; }), - })), + ), // Vollton-Füllfarbe NUR für Drawing2D; `null` entfernt das Feld. setElementFillColor: (id, fillColor) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => { - if (d.id !== id) return d; + applyChange((p) => + patchItem(p, "drawings2d", id, (d) => { if (fillColor === null) { const { fillColor: _omit, ...rest } = d; return rest; } return { ...d, fillColor }; }), - })), + ), // Vordergrund-/Hintergrund-Override (Wand/Decke/Drawing2D); `null` löscht // das Feld (→ „Nach System", erbt wieder vom Bauteil/System). setElementForeground: (kind, id, value) => - setProject((p) => setOverrideField(p, kind, id, "foreground", value)), + applyChange((p) => setOverrideField(p, kind, id, "foreground", value)), setElementBackground: (kind, id, value) => - setProject((p) => setOverrideField(p, kind, id, "background", value)), + applyChange((p) => setOverrideField(p, kind, id, "background", value)), - updateDrawing2D: (id, patch) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => (d.id === id ? { ...d, ...patch } : d)), - })), + updateDrawing2D: (id, patch) => applyChange((p) => patchItem(p, "drawings2d", id, patch)), reorderDrawings: (ids, op) => - setProject((p) => ({ - ...p, - drawings2d: reorderDrawings2D(p.drawings2d, ids, op), - })), + applyChange((p) => fieldOps(p, "drawings2d", reorderDrawings2D(p.drawings2d, ids, op))), reorderDrawingLevels: (ids, op) => - setProject((p) => ({ - ...p, - drawingLevels: reorderDrawingLevelsArr(p.drawingLevels, ids, op), - })), + applyChange((p) => fieldOps(p, "drawingLevels", reorderDrawingLevelsArr(p.drawingLevels, ids, op))), // ── Größe (Resize um Anker) ──────────────────────────────────────────── resizeElement: (kind, id, w, h, anchor) => - setProject((p) => resizeElement(p, kind, id, w, h, anchor)), + applyChange((p) => resizeElement(p, kind, id, w, h, anchor)), // ── Transformation ───────────────────────────────────────────────────── commitTransformOn: (sel, op, points, copyMode, count) => - setProject((p) => commitTransform(p, sel, op, points, copyMode, count)), + applyChange((p) => transformOps(p, sel, op, points, copyMode, count)), // ── Wand-Attribute ───────────────────────────────────────────────────── - updateWall: (id, patch, coalesceKey) => - setProject( - (p) => ({ - ...p, - walls: p.walls.map((w) => (w.id === id ? { ...w, ...patch } : w)), - }), - coalesceKey, - ), + updateWall: (id, patch, coalesceKey) => applyChange((p) => patchItem(p, "walls", id, patch), coalesceKey), setWallThickness: (wallId, thickness) => - setProject((p) => setWallThickness(p, wallId, thickness)), + applyChange((p) => setWallThickness(p, wallId, thickness)), // ── Decken-Editieren ────────────────────────────────────────────────── // (coalesceKey: siehe Kommentar bei moveGripOf — auch hier läuft die // Mutation bei jedem Maus-Move-Schritt eines Drags.) moveCeilingGrip: (ceilingId, index, pt) => - setProject( + applyChange( (p) => mapCeiling(p, ceilingId, (c) => ({ ...c, outline: c.outline.map((v, i) => (i === index ? pt : v)), @@ -1304,7 +1258,7 @@ export function createProjectSlice( ), moveCeilingBy: (ceilingId, delta) => - setProject( + applyChange( (p) => mapCeiling(p, ceilingId, (c) => ({ ...c, outline: c.outline.map((v) => ({ x: v.x + delta.x, y: v.y + delta.y })), @@ -1313,7 +1267,7 @@ export function createProjectSlice( ), moveCeilingEdge: (ceilingId, aIndex, bIndex, delta) => - setProject( + applyChange( (p) => mapCeiling(p, ceilingId, (c) => ({ ...c, outline: movePolygonEdge(c.outline, aIndex, bIndex, delta, true), @@ -1322,37 +1276,25 @@ export function createProjectSlice( ), updateCeiling: (id, patch) => - setProject((p) => mapCeiling(p, id, (c) => ({ ...c, ...patch }))), + applyChange((p) => mapCeiling(p, id, (c) => ({ ...c, ...patch }))), setCeilingThickness: (ceilingId, thickness) => - setProject((p) => setCeilingThickness(p, ceilingId, thickness)), + applyChange((p) => setCeilingThickness(p, ceilingId, thickness)), // ── Öffnungs-Editieren ──────────────────────────────────────────────── - updateOpening: (id, patch) => - setProject((p) => ({ - ...p, - openings: (p.openings ?? []).map((o) => (o.id === id ? { ...o, ...patch } : o)), - })), + updateOpening: (id, patch) => applyChange((p) => patchItem(p, "openings", id, patch)), // ── Dach-Editieren ───────────────────────────────────────────────────── - updateRoof: (id, patch, coalesceKey) => - setProject( - (p) => ({ - ...p, - roofs: (p.roofs ?? []).map((r) => (r.id === id ? { ...r, ...patch } : r)), - }), - coalesceKey, - ), + updateRoof: (id, patch, coalesceKey) => applyChange((p) => patchItem(p, "roofs", id, patch), coalesceKey), // Dach-Eckgriff (3D): der gezogene Umriss-Eckpunkt `index` wandert auf `pt`; // die GEGENÜBERLIEGENDE Ecke bleibt fix → der Umriss bleibt ein achsparalleles // Rechteck (die Dach-Geometrie rechnet ohnehin auf der Bounding-Box). moveRoofGrip: (roofId, index, pt) => - setProject( - (p) => ({ - ...p, - roofs: (p.roofs ?? []).map((r) => { - if (r.id !== roofId || r.outline.length < 4) return r; + applyChange( + (p) => + patchItem(p, "roofs", roofId, (r) => { + if (r.outline.length < 4) return r; const opp = r.outline[(index + 2) % r.outline.length]; const x0 = Math.min(pt.x, opp.x); const x1 = Math.max(pt.x, opp.x); @@ -1368,28 +1310,24 @@ export function createProjectSlice( ], }; }), - }), `moveRoofGrip:${roofId}`, ), // Dach als Ganzes verschieben (Verschiebe-Griff). moveRoofBy: (roofId, delta) => - setProject( - (p) => ({ - ...p, - roofs: (p.roofs ?? []).map((r) => - r.id === roofId - ? { ...r, outline: r.outline.map((v) => ({ x: v.x + delta.x, y: v.y + delta.y })) } - : r, - ), - }), + applyChange( + (p) => + patchItem(p, "roofs", roofId, (r) => ({ + ...r, + outline: r.outline.map((v) => ({ x: v.x + delta.x, y: v.y + delta.y })), + })), `moveRoofBy:${roofId}`, ), // ── Treppen-Editieren ────────────────────────────────────────────────── // (coalesceKey: siehe Kommentar bei moveGripOf.) moveStairBy: (stairId, delta) => - setProject( + applyChange( (p) => mapStair(p, stairId, (s) => ({ ...s, @@ -1402,12 +1340,12 @@ export function createProjectSlice( ), updateStair: (id, patch) => - setProject((p) => mapStair(p, id, (s) => ({ ...s, ...patch }))), + applyChange((p) => mapStair(p, id, (s) => ({ ...s, ...patch }))), // ── Raum-Editieren ────────────────────────────────────────────────────── // (coalesceKey: siehe Kommentar bei moveGripOf.) moveRoomBy: (roomId, delta) => - setProject( + applyChange( (p) => mapRoom(p, roomId, (r) => ({ ...r, @@ -1425,7 +1363,7 @@ export function createProjectSlice( ), moveRoomGrip: (roomId, index, pt) => - setProject( + applyChange( (p) => mapRoom(p, roomId, (r) => ({ ...r, @@ -1435,7 +1373,7 @@ export function createProjectSlice( ), moveRoomEdge: (roomId, aIndex, bIndex, delta) => - setProject( + applyChange( (p) => mapRoom(p, roomId, (r) => ({ ...r, @@ -1445,10 +1383,10 @@ export function createProjectSlice( ), updateRoom: (id, patch) => - setProject((p) => mapRoom(p, id, (r) => ({ ...r, ...patch }))), + applyChange((p) => mapRoom(p, id, (r) => ({ ...r, ...patch }))), moveRoomStamp: (roomId, delta) => - setProject((p) => + applyChange((p) => mapRoom(p, roomId, (r) => { const base = r.stampAnchor ?? roomCentroid(r.boundary); return { @@ -1459,13 +1397,13 @@ export function createProjectSlice( ), setRoomStampAnchor: (roomId, anchor) => - setProject((p) => mapRoom(p, roomId, (r) => ({ ...r, stampAnchor: anchor }))), + applyChange((p) => mapRoom(p, roomId, (r) => ({ ...r, stampAnchor: anchor }))), setRoomStampDoc: (roomId, doc) => - setProject((p) => mapRoom(p, roomId, (r) => ({ ...r, stampDoc: doc }))), + applyChange((p) => mapRoom(p, roomId, (r) => ({ ...r, stampDoc: doc }))), setRoomStamp: (roomId, stamp) => - setProject((p) => mapRoom(p, roomId, (r) => ({ ...r, stamp }))), + applyChange((p) => mapRoom(p, roomId, (r) => ({ ...r, stamp }))), }; } @@ -1474,12 +1412,8 @@ function mapRoom( project: Project, roomId: string, fn: (r: import("../model/types").Room) => import("../model/types").Room, -): Project { - const rooms = project.rooms ?? []; - return { - ...project, - rooms: rooms.map((r) => (r.id === roomId ? fn(r) : r)), - }; +): CoreOp[] { + return patchItem(project, "rooms", roomId, fn); } /** Immutabler Map über eine Treppe (per ID); No-op ohne Treffer. */ @@ -1487,12 +1421,8 @@ function mapStair( project: Project, stairId: string, fn: (s: import("../model/types").Stair) => import("../model/types").Stair, -): Project { - const stairs = project.stairs ?? []; - return { - ...project, - stairs: stairs.map((s) => (s.id === stairId ? fn(s) : s)), - }; +): CoreOp[] { + return patchItem(project, "stairs", stairId, fn); } /** Immutabler Map über eine Decke (per ID); No-op ohne Treffer. */ @@ -1507,19 +1437,17 @@ function setOverrideField( id: string, field: "foreground" | "background", value: string | null, -): Project { +): CoreOp[] { const apply = (item: T): T => { - if (item.id !== id) return item; if (value === null) { const { [field]: _omit, ...rest } = item as Record; return rest as unknown as T; } return { ...item, [field]: value }; }; - if (kind === "wall") return { ...project, walls: project.walls.map(apply) }; - if (kind === "ceiling") - return { ...project, ceilings: (project.ceilings ?? []).map(apply) }; - return { ...project, drawings2d: project.drawings2d.map(apply) }; + if (kind === "wall") return patchItem(project, "walls", id, apply); + if (kind === "ceiling") return patchItem(project, "ceilings", id, apply); + return patchItem(project, "drawings2d", id, apply); } /** @@ -1609,12 +1537,8 @@ function mapCeiling( project: Project, ceilingId: string, fn: (c: import("../model/types").Ceiling) => import("../model/types").Ceiling, -): Project { - const ceilings = project.ceilings ?? []; - return { - ...project, - ceilings: ceilings.map((c) => (c.id === ceilingId ? fn(c) : c)), - }; +): CoreOp[] { + return patchItem(project, "ceilings", ceilingId, fn); } /** @@ -1627,12 +1551,12 @@ function setWallThickness( project: Project, wallId: string, thickness: number, -): Project { - if (!isFinite(thickness) || thickness <= 0) return project; +): CoreOp[] { + if (!isFinite(thickness) || thickness <= 0) return []; const wall = project.walls.find((w) => w.id === wallId); - if (!wall) return project; + if (!wall) return []; const wt = project.wallTypes.find((t) => t.id === wall.wallTypeId); - if (!wt || wt.layers.length === 0) return project; + if (!wt || wt.layers.length === 0) return []; const single = wt.layers.length === 1; const usedByOthers = project.walls.some( @@ -1641,14 +1565,7 @@ function setWallThickness( if (single && !usedByOthers) { // Direkt die Schichtdicke des (exklusiven, einschichtigen) Wandtyps setzen. - return { - ...project, - wallTypes: project.wallTypes.map((t) => - t.id === wt.id - ? { ...t, layers: [{ ...t.layers[0], thickness }] } - : t, - ), - }; + return patchItem(project, "wallTypes", wt.id, (t) => ({ ...t, layers: [{ ...t.layers[0], thickness }] })); } // Dedizierten einschichtigen Wandtyp erzeugen (erste Schicht klonen) und der @@ -1659,13 +1576,7 @@ function setWallThickness( name: t("default.wallTypeSingle", { thickness: thickness.toFixed(2) }), layers: [{ ...wt.layers[0], thickness }], }; - return { - ...project, - wallTypes: [...project.wallTypes, clone], - walls: project.walls.map((w) => - w.id === wallId ? { ...w, wallTypeId: id } : w, - ), - }; + return [...addItems("wallTypes", [clone]), ...patchItem(project, "walls", wallId, { wallTypeId: id })]; } /** @@ -1681,15 +1592,15 @@ function setCeilingThickness( project: Project, ceilingId: string, thickness: number, -): Project { - if (!isFinite(thickness) || thickness <= 0) return project; +): CoreOp[] { + if (!isFinite(thickness) || thickness <= 0) return []; const ceiling = (project.ceilings ?? []).find((c) => c.id === ceilingId); - if (!ceiling) return project; + if (!ceiling) return []; const activeId = ceiling.ceilingTypeId ?? ceiling.wallTypeId; const ct = (project.ceilingTypes ?? []).find((t) => t.id === ceiling.ceilingTypeId) ?? project.wallTypes.find((t) => t.id === ceiling.wallTypeId); - if (!ct || ct.layers.length === 0) return project; + if (!ct || ct.layers.length === 0) return []; const single = ct.layers.length === 1; const usedByOthers = (project.ceilings ?? []).some( @@ -1698,12 +1609,7 @@ function setCeilingThickness( if (single && !usedByOthers && ceiling.ceilingTypeId) { // Direkt die Schichtdicke des (exklusiven, einschichtigen) Deckentyps setzen. - return { - ...project, - ceilingTypes: (project.ceilingTypes ?? []).map((t) => - t.id === ct.id ? { ...t, layers: [{ ...t.layers[0], thickness }] } : t, - ), - }; + return patchItem(project, "ceilingTypes", ct.id, (t) => ({ ...t, layers: [{ ...t.layers[0], thickness }] })); } // Dedizierten einschichtigen Deckentyp erzeugen (erste Schicht klonen) und @@ -1714,13 +1620,10 @@ function setCeilingThickness( name: t("default.ceilingTypeSingle", { thickness: thickness.toFixed(2) }), layers: [{ ...ct.layers[0], thickness }], }; - return { - ...project, - ceilingTypes: [...(project.ceilingTypes ?? []), clone], - ceilings: (project.ceilings ?? []).map((c) => - c.id === ceilingId ? { ...c, ceilingTypeId: id, thickness: undefined } : c, - ), - }; + return [ + ...addItems("ceilingTypes", [clone]), + ...patchItem(project, "ceilings", ceilingId, (c) => ({ ...c, ceilingTypeId: id, thickness: undefined })), + ]; } // ── Resize (Skalierung auf Zielmaß um einen Anker) ─────────────────────────── @@ -1738,28 +1641,19 @@ function resizeElement( w: number, h: number, anchor: { fx: number; fy: number }, -): Project { +): CoreOp[] { if (kind === "drawing2d") { - return { - ...project, - drawings2d: project.drawings2d.map((d) => - d.id === id ? { ...d, geom: resizeGeom(d.geom, w, h, anchor) } : d, - ), - }; + return patchItem(project, "drawings2d", id, (d) => ({ ...d, geom: resizeGeom(d.geom, w, h, anchor) })); } - return { - ...project, - walls: project.walls.map((wall) => { - if (wall.id !== id) return wall; + return patchItem(project, "walls", id, (wall) => { const box = bbox2([wall.start, wall.end]); const { ax, ay, sx, sy } = scaleAround(box, w, h, anchor); const apply = (p: Vec2): Vec2 => ({ x: ax + (p.x - ax) * sx, y: ay + (p.y - ay) * sy, }); - return { ...wall, start: apply(wall.start), end: apply(wall.end) }; - }), - }; + return { ...wall, start: apply(wall.start), end: apply(wall.end) }; + }); } /** bbox einer Punktliste. */ @@ -2107,16 +2001,13 @@ function moveGrip( pt: Vec2, /** Papier-Massstab (1:N) — nur für den Masszahl-Griff, s. `drawingVertices`. */ scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR, -): Project { +): CoreOp[] { // Objekt-Sperre: gesperrte Elemente lassen sich anwählen, aber nicht // ziehen (s. Kommentar bei `onPlanSelect` in useMouseSelectionHandlers.ts). - if (drawingId && project.drawings2d.find((d) => d.id === drawingId)?.locked) return project; - if (wallId && project.walls.find((w) => w.id === wallId)?.locked) return project; + if (drawingId && project.drawings2d.find((d) => d.id === drawingId)?.locked) return []; + if (wallId && project.walls.find((w) => w.id === wallId)?.locked) return []; if (drawingId) { - return { - ...project, - drawings2d: project.drawings2d.map((d) => { - if (d.id !== drawingId) return d; + return patchItem(project, "drawings2d", drawingId, (d) => { const g = d.geom; if (g.shape === "line" || g.shape === "xline" || g.shape === "ray") { return { ...d, geom: index === 0 ? { ...g, a: pt } : { ...g, b: pt } }; @@ -2283,18 +2174,12 @@ function moveGrip( return { ...d, geom: { ...g, rx, ry } }; } return d; - }), - }; + }); } if (wallId) { - return { - ...project, - walls: project.walls.map((w) => - w.id === wallId ? { ...w, ...(index === 0 ? { start: pt } : { end: pt }) } : w, - ), - }; + return patchItem(project, "walls", wallId, (w) => ({ ...w, ...(index === 0 ? { start: pt } : { end: pt }) })); } - return project; + return []; } /** Verschiebt das selektierte Element (2D-Element ODER Wand) um `delta` (parallel). */ @@ -2303,16 +2188,13 @@ function moveElementBy( drawingId: string | null, wallId: string | null, delta: Vec2, -): Project { +): CoreOp[] { // Objekt-Sperre: s. Kommentar in `moveGrip` oben. - if (drawingId && project.drawings2d.find((d) => d.id === drawingId)?.locked) return project; - if (wallId && project.walls.find((w) => w.id === wallId)?.locked) return project; + if (drawingId && project.drawings2d.find((d) => d.id === drawingId)?.locked) return []; + if (wallId && project.walls.find((w) => w.id === wallId)?.locked) return []; const mv = (p: Vec2): Vec2 => ({ x: p.x + delta.x, y: p.y + delta.y }); if (drawingId) { - return { - ...project, - drawings2d: project.drawings2d.map((d) => { - if (d.id !== drawingId) return d; + return patchItem(project, "drawings2d", drawingId, (d) => { const g = d.geom; switch (g.shape) { case "line": @@ -2343,18 +2225,12 @@ function moveElementBy( default: return d; } - }), - }; + }); } if (wallId) { - return { - ...project, - walls: project.walls.map((w) => - w.id === wallId ? { ...w, start: mv(w.start), end: mv(w.end) } : w, - ), - }; + return patchItem(project, "walls", wallId, (w) => ({ ...w, start: mv(w.start), end: mv(w.end) })); } - return project; + return []; } /** @@ -2458,16 +2334,13 @@ function moveEdge( aIndex: number, bIndex: number, delta: Vec2, -): Project { +): CoreOp[] { // Objekt-Sperre: s. Kommentar in `moveGrip` oben. - if (drawingId && project.drawings2d.find((d) => d.id === drawingId)?.locked) return project; - if (wallId && project.walls.find((w) => w.id === wallId)?.locked) return project; + if (drawingId && project.drawings2d.find((d) => d.id === drawingId)?.locked) return []; + if (wallId && project.walls.find((w) => w.id === wallId)?.locked) return []; const mv = (p: Vec2): Vec2 => ({ x: p.x + delta.x, y: p.y + delta.y }); if (drawingId) { - return { - ...project, - drawings2d: project.drawings2d.map((d) => { - if (d.id !== drawingId) return d; + return patchItem(project, "drawings2d", drawingId, (d) => { const g = d.geom; if (g.shape === "line") { // Linie hat nur eine Kante [0,1] → das ganze Segment verschieben. @@ -2497,19 +2370,13 @@ function moveEdge( return { ...d, geom: { ...g, min: { x: minX, y: minY }, max: { x: maxX, y: maxY } } }; } return d; - }), - }; + }); } if (wallId) { // Wand: beide Enden gemeinsam → ganze Wand senkrecht verschieben. - return { - ...project, - walls: project.walls.map((w) => - w.id === wallId ? { ...w, start: mv(w.start), end: mv(w.end) } : w, - ), - }; + return patchItem(project, "walls", wallId, (w) => ({ ...w, start: mv(w.start), end: mv(w.end) })); } - return project; + return []; } // ── Immutable Tree-Helfer (verschoben aus App.tsx, 1:1) ────────────────────── diff --git a/src/state/useGripEditing.ts b/src/state/useGripEditing.ts index 5be6940b..1c200bd2 100644 --- a/src/state/useGripEditing.ts +++ b/src/state/useGripEditing.ts @@ -92,6 +92,11 @@ export function useGripEditing(opts: { moveRoomBy: (id: string, delta: Vec2) => void; moveCeilingBy: (id: string, delta: Vec2) => void; moveElementByOf: (drawingId: string | null, wallId: string | null, delta: Vec2) => void; + /** + * Fasst mehrere Änderungen zu EINEM Undo-Schritt zusammen ([K4] S3, Store `groupChanges`); mit + * Schlüssel schliessen die Mausschritte desselben Zugs an denselben Schritt an. + */ + groupChanges?: (fn: () => void, coalesceKey?: string) => void; }) { const { project, @@ -129,6 +134,7 @@ export function useGripEditing(opts: { moveCeilingBy, moveElementByOf, } = opts; + const groupChanges = opts.groupChanges ?? ((fn: () => void) => fn()); // Bewegpunkt (Move-Handle) einer Treppe: liegt auf der Treppe (Mitte des // ersten Laufs bei gerade/L, Zentrum bei Wendel) und verschiebt beim Ziehen @@ -1000,7 +1006,8 @@ export function useGripEditing(opts: { }; /** Ausstehenden Zug jetzt in das Projekt schreiben (EINE Mutation). */ - const commitPendingGrip = () => { + const commitPendingGrip = () => groupChanges(commitPendingGripChanges); + const commitPendingGripChanges = () => { const ph = pendingSheetHeightRef.current; pendingSheetHeightRef.current = null; if (ph) { @@ -1053,7 +1060,8 @@ export function useGripEditing(opts: { }; /** Aufgeschobenes Körper-Verschieben jetzt ins Projekt schreiben. */ - const commitPendingBody = () => { + const commitPendingBody = () => groupChanges(commitPendingBodyChanges); + const commitPendingBodyChanges = () => { const pwm = pendingWallMoveRef.current; pendingWallMoveRef.current = null; sheetDuRef.current = null; @@ -1436,16 +1444,21 @@ export function useGripEditing(opts: { setDraft({ preview: bodyPreviewShapes(), vertices: [], snap: null }); return; } - moveElementByOf(moveDrawingId, moveWallId, delta); // Beim ersten Move-Event die Koinzidenz-Gruppe einmalig bestimmen (Snapshot // VOR der ersten Mutation der Siblings). Danach inkrementell mitführen. if (moveCoincidentRef.current === null) { moveCoincidentRef.current = findMoveCoincident2D(moveDrawingId, moveWallId); } - for (const c of moveCoincidentRef.current) { - c.pos = { x: c.pos.x + delta.x, y: c.pos.y + delta.y }; - moveGripOf(c.drawingId, c.wallId, c.index, c.pos, scaleDenominator); - } + const coincident = moveCoincidentRef.current; + // Element + mitgeführte Ecken: je Mausschritt eine Gruppe, die Schritte desselben Zugs + // schliessen an denselben Undo-Schritt an. + groupChanges(() => { + moveElementByOf(moveDrawingId, moveWallId, delta); + for (const c of coincident) { + c.pos = { x: c.pos.x + delta.x, y: c.pos.y + delta.y }; + moveGripOf(c.drawingId, c.wallId, c.index, c.pos, scaleDenominator); + } + }, `bodyDrag:${moveDrawingId ?? ""}:${moveWallId ?? ""}`); }, // Kanten-Griff ziehen. Zwei Verhalten (Zielpunkt jeweils ABSOLUT relativ // zum ORIGINALEN Anker `edge.mid`, angewandt über applyEdgeToward — s. dort): diff --git a/src/state/useMouseSelectionHandlers.ts b/src/state/useMouseSelectionHandlers.ts index 3536d068..093e651f 100644 --- a/src/state/useMouseSelectionHandlers.ts +++ b/src/state/useMouseSelectionHandlers.ts @@ -5,6 +5,7 @@ // // Extrahiert aus App.tsx. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). +import { opsMutation, patchItem, removeItems } from "../core"; import type { Project, Vec2 } from "../model/types"; import type { CategoryDisplayResolver } from "../core"; import type { DisplayResolver } from "../viewport/Viewport3D"; @@ -168,14 +169,11 @@ export function useMouseSelectionHandlers(opts: { const id = editTextId; if (!id) return; setProject( - (p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => - d.id === id && d.geom.shape === "text" - ? { ...d, geom: { ...d.geom, doc, text: plainText(doc) } } - : d, + opsMutation((p) => + patchItem(p, "drawings2d", id, (d) => + d.geom.shape === "text" ? { ...d, geom: { ...d.geom, doc, text: plainText(doc) } } : d, ), - }), + ), `commitTextEdit:${id}`, ); }; @@ -186,15 +184,14 @@ export function useMouseSelectionHandlers(opts: { const closeTextEdit = () => { const id = editTextId; if (id) { - setProject((p) => { - const d = p.drawings2d.find((x) => x.id === id); - // `text` ist immer der Reintext-Spiegel von `doc` (s. commitTextEdit) — - // reicht daher allein als Leer-Test, egal ob `doc` je gesetzt wurde. - if (d && d.geom.shape === "text" && d.geom.text.trim() === "") { - return { ...p, drawings2d: p.drawings2d.filter((x) => x.id !== id) }; - } - return p; - }); + setProject( + opsMutation((p) => { + const d = p.drawings2d.find((x) => x.id === id); + // `text` ist immer der Reintext-Spiegel von `doc` (s. commitTextEdit) — + // reicht daher allein als Leer-Test, egal ob `doc` je gesetzt wurde. + return d && d.geom.shape === "text" && d.geom.text.trim() === "" ? removeItems(p, "drawings2d", [id]) : []; + }), + ); } setEditTextId(null); setEditTextMinHeightM(null); diff --git a/src/state/usePanelHostBase.ts b/src/state/usePanelHostBase.ts index c134ac5c..1014dd91 100644 --- a/src/state/usePanelHostBase.ts +++ b/src/state/usePanelHostBase.ts @@ -8,6 +8,7 @@ // Extrahiert aus App.tsx. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import { applyFillMode } from "./fillMode"; +import { opsMutation, patchItem } from "../core"; import { useMemo, type RefObject } from "react"; import type { DrawingLevel, Layout, Project } from "../model/types"; import { resolvePenColor } from "../model/penSets"; @@ -474,21 +475,19 @@ export function usePanelHostBase(opts: { }, onSetSelectionFillMode: (mode) => { if (selection?.kind !== "drawing2d") return; - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => (d.id === selection.id ? applyFillMode(d, p.hatches, mode) : d)), - })); + const id = selection.id; + setProject(opsMutation((p) => patchItem(p, "drawings2d", id, (d) => applyFillMode(d, p.hatches, mode)))); }, onSetSelectionFillOpacity: (opacity) => { if (selection?.kind === "drawing2d") - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => { - if (d.id !== selection.id) return d; - const { fillOpacity: _old, ...rest } = d; - return opacity >= 1 ? rest : { ...rest, fillOpacity: Math.max(0, opacity) }; - }), - })); + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", selection.id, (d) => { + const { fillOpacity: _old, ...rest } = d; + return opacity >= 1 ? rest : { ...rest, fillOpacity: Math.max(0, opacity) }; + }), + ), + ); }, onSetSelectionOpacity: (opacity) => { // Deckkraft eines 2D-Elements. Bei BILDERN bleibt es die Deckkraft der @@ -497,15 +496,13 @@ export function usePanelHostBase(opts: { // Füllungen wirkt (`Drawing2D.opacity`). Nur EIN Bedienfeld — welches // Feld gesetzt wird, entscheidet die Form. if (selection?.kind === "drawing2d") - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => { - if (d.id !== selection.id) return d; - return d.geom.shape === "image" - ? { ...d, geom: { ...d.geom, opacity } } - : { ...d, opacity }; - }), - })); + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", selection.id, (d) => + d.geom.shape === "image" ? { ...d, geom: { ...d.geom, opacity } } : { ...d, opacity }, + ), + ), + ); else if (selection?.kind === "layoutAnnotation" && activeLayout) patchOpenLayout(activeLayout.id, (l) => patchAnnotationInLayout(l, selection.id, { opacity }), @@ -571,44 +568,39 @@ export function usePanelHostBase(opts: { }, onAddColorToCustomPalette: (paletteId, hex) => addColorToCustomPalette(paletteId, hex), onSetDashScale: (drawingId, scale) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => (d.id === drawingId ? { ...d, dashScale: scale } : d)), - })), + setProject(opsMutation((p) => patchItem(p, "drawings2d", drawingId, { dashScale: scale }))), onSetDetailRefLabel: (drawingId, label) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => - d.id === drawingId && d.geom.shape === "detailref" - ? { ...d, geom: { ...d.geom, label } } - : d, + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => + d.geom.shape === "detailref" ? { ...d, geom: { ...d.geom, label } } : d, + ), ), - })), + ), onSetDetailRefSheetLayout: (drawingId, sheetLayoutId) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => { - if (d.id !== drawingId || d.geom.shape !== "detailref") return d; - const geom = { ...d.geom }; - if (sheetLayoutId) geom.sheetLayoutId = sheetLayoutId; - else delete geom.sheetLayoutId; - return { ...d, geom }; - }), - })), - onSetDetailRefSheetLabel: (drawingId, sheetLabel) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => - d.id === drawingId && d.geom.shape === "detailref" - ? { ...d, geom: { ...d.geom, sheetLabel } } - : d, + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => { + if (d.geom.shape !== "detailref") return d; + const geom = { ...d.geom }; + if (sheetLayoutId) geom.sheetLayoutId = sheetLayoutId; + else delete geom.sheetLayoutId; + return { ...d, geom }; + }), ), - })), + ), + onSetDetailRefSheetLabel: (drawingId, sheetLabel) => + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => + d.geom.shape === "detailref" ? { ...d, geom: { ...d.geom, sheetLabel } } : d, + ), + ), + ), onSetHatchPlacement: (drawingId, patch) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => { - if (d.id !== drawingId) return d; + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => { const next = { ...d }; // `null` = zurück auf die Ressource (Feld entfernen). if ("angleDeg" in patch) @@ -618,24 +610,23 @@ export function usePanelHostBase(opts: { if ("origin" in patch) patch.origin === null ? delete next.hatchOrigin : (next.hatchOrigin = patch.origin); return next; - }), - })), + }), + ), + ), onSetEndMarks: (drawingId, patch) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => - d.id === drawingId ? { ...d, endMarks: { ...d.endMarks, ...patch } } : d, + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => ({ ...d, endMarks: { ...d.endMarks, ...patch } })), ), - })), + ), onSetDimensionStyle: (drawingId, patch) => - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => - d.id === drawingId && d.geom.shape === "dimension" - ? { ...d, geom: { ...d.geom, ...patch } } - : d, + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => + d.geom.shape === "dimension" ? { ...d, geom: { ...d.geom, ...patch } } : d, + ), ), - })), + ), onSetSelectionBackgroundPen: (penId) => { if (!selection) return; const background = penId ? resolvePenColor(project, penId) : undefined; diff --git a/src/tools/transform.ts b/src/tools/transform.ts index 78de0f52..38aa450f 100644 --- a/src/tools/transform.ts +++ b/src/tools/transform.ts @@ -7,7 +7,7 @@ // P distribute — Original bleibt + N Kopien gleichmäßig zwischen Original und Ziel. // // Bezeichner englisch, UI-Text via t() (CONVENTIONS.md). Reine Funktionen + Geometrie; -// die App hält den State und wendet `commitTransform` immutabel an. +// die App hält den State und wendet die Ops aus `transformOps` an ([K4] S3). import { transformSolid } from "../core"; import type { @@ -32,6 +32,10 @@ import { drawingPreviewShapes } from "./drawingPreview"; import { mvGeom, reversesOrientation, scaleFactor, scaleGeom } from "../core"; import { uniqueId } from "./types"; import type { CommandSelection } from "../commands/types"; +import { applyOps } from "../core"; +import type { CoreOp } from "../core"; +import { addItems, opsMutation, patchItems } from "../core"; +import type { ProjectMutation } from "../core"; export type TransformOp = "move" | "rotate" | "mirror" | "scale"; export type CopyMode = "move" | "copy" | "array" | "distribute"; // U / I / O / P @@ -497,17 +501,20 @@ export function rotateGizmoShapes(center: Vec2, refPoint: Vec2, cursor: Vec2): D // ── Commit ─────────────────────────────────────────────────────────────────── -/** Wendet die Transformation immutabel auf das Projekt an (Original + Kopien). */ -export function commitTransform( +/** + * Die Transformation als Ops ([K4] S3): `replace` je bewegtem Original (nur bei „move"), `add` der + * Kopien je Liste. Liest nur die gewählten Elemente — keine Projekt-Differenz über alle Wände. + */ +export function transformOps( project: Project, sel: TransformSelection, op: TransformOp, pts: Vec2[], mode: CopyMode, count: number, -): Project { +): CoreOp[] { const items = gatherItems(project, sel, op); - if (items.length === 0) return project; + if (items.length === 0) return []; const wallIds = new Set(sel.wallIds); // Bei einer Skalierung müssen auch Grössenfelder (Radius/Schrifthöhe/…) // mitziehen — dafür `scaleGeom` statt `mvGeom` (s. dort); analog für @@ -517,18 +524,11 @@ export function commitTransform( const stairAt = (s: Stair, fn: (p: Vec2) => Vec2, t: number): Stair => mvStair(s, fn, op === "scale" ? scaleFactor(pts, t) : 1); - let walls = project.walls; - let drawings2d = project.drawings2d; - let extrudedSolids = project.extrudedSolids ?? []; - let columns = project.columns ?? []; - let ceilings = project.ceilings ?? []; - let roofs = project.roofs ?? []; - let stairs = project.stairs ?? []; - let rooms = project.rooms ?? []; const ceilingIds = new Set(sel.ceilingIds ?? []); const roofIds = new Set(sel.roofIds ?? []); const stairIds = new Set(sel.stairIds ?? []); const roomIds = new Set(sel.roomIds ?? []); + const ops: CoreOp[] = []; // U (move): Original an die Endlage (t=1) transformieren. Objekt-Sperre // (`locked`) überall mitgeprüft — dieselbe Semantik wie `gatherItems` @@ -537,13 +537,20 @@ export function commitTransform( // genau diese Art von Doppel-Pflege). if (movesOriginal(mode)) { const fn = transformFn(op, pts, 1); - walls = walls.map((w) => - wallIds.has(w.id) && !w.locked ? { ...w, start: fn(w.start), end: fn(w.end) } : w, + ops.push( + ...patchItems(project, "walls", (w) => wallIds.has(w.id) && !w.locked, (w) => ({ + ...w, + start: fn(w.start), + end: fn(w.end), + })), ); const moveDrawIds = drawingIdSet(sel); if (moveDrawIds.size > 0) { - drawings2d = drawings2d.map((d) => - moveDrawIds.has(d.id) && !d.locked ? { ...d, geom: geomAt(d.geom, fn, 1) } : d, + ops.push( + ...patchItems(project, "drawings2d", (d) => moveDrawIds.has(d.id) && !d.locked, (d) => ({ + ...d, + geom: geomAt(d.geom, fn, 1), + })), ); } if (sel.extrudedSolidId) { @@ -552,19 +559,21 @@ export function commitTransform( // nutzt) müssen mitziehen — sonst weicht das 3D-Volumen sichtbar von // der Grundriss-Kontur ab (nur `center` mitzuführen genügt nicht). const f1 = op === "scale" ? scaleFactor(pts, 1) : 1; - extrudedSolids = extrudedSolids.map((s) => (s.id === sel.extrudedSolidId ? transformSolid(s, fn, f1) : s)); + const solidId = sel.extrudedSolidId; + ops.push(...patchItems(project, "extrudedSolids", (s) => s.id === solidId, (s) => transformSolid(s, fn, f1))); } if (sel.columnId) { - columns = columns.map((c) => (c.id === sel.columnId && !c.locked ? mvColumn(c, fn) : c)); + const columnId = sel.columnId; + ops.push(...patchItems(project, "columns", (c) => c.id === columnId && !c.locked, (c) => mvColumn(c, fn))); } if (ceilingIds.size > 0) - ceilings = ceilings.map((c) => (ceilingIds.has(c.id) && !c.locked ? mvCeiling(c, fn) : c)); - if (roofIds.size > 0 && roofTransformAllowed(op)) { - roofs = roofs.map((r) => (roofIds.has(r.id) && !r.locked ? mvRoof(r, fn) : r)); - } + ops.push(...patchItems(project, "ceilings", (c) => ceilingIds.has(c.id) && !c.locked, (c) => mvCeiling(c, fn))); + if (roofIds.size > 0 && roofTransformAllowed(op)) + ops.push(...patchItems(project, "roofs", (r) => roofIds.has(r.id) && !r.locked, (r) => mvRoof(r, fn))); if (stairIds.size > 0) - stairs = stairs.map((s) => (stairIds.has(s.id) && !s.locked ? stairAt(s, fn, 1) : s)); - if (roomIds.size > 0) rooms = rooms.map((r) => (roomIds.has(r.id) && !r.locked ? mvRoom(r, fn) : r)); + ops.push(...patchItems(project, "stairs", (s) => stairIds.has(s.id) && !s.locked, (s) => stairAt(s, fn, 1))); + if (roomIds.size > 0) + ops.push(...patchItems(project, "rooms", (r) => roomIds.has(r.id) && !r.locked, (r) => mvRoom(r, fn))); } // Kopien anhängen (I/O/P bzw. mirror copy). @@ -614,16 +623,41 @@ export function commitTransform( } } } - - return { - ...project, - walls: newWalls.length ? [...walls, ...newWalls] : walls, - drawings2d: newDrawings.length ? [...drawings2d, ...newDrawings] : drawings2d, - extrudedSolids: newSolids.length ? [...extrudedSolids, ...newSolids] : extrudedSolids, - columns: newColumns.length ? [...columns, ...newColumns] : columns, - ceilings: newCeilings.length ? [...ceilings, ...newCeilings] : ceilings, - roofs: newRoofs.length ? [...roofs, ...newRoofs] : roofs, - stairs: newStairs.length ? [...stairs, ...newStairs] : stairs, - rooms: newRooms.length ? [...rooms, ...newRooms] : rooms, - }; + ops.push( + ...addItems("walls", newWalls), + ...addItems("drawings2d", newDrawings), + ...addItems("extrudedSolids", newSolids), + ...addItems("columns", newColumns), + ...addItems("ceilings", newCeilings), + ...addItems("roofs", newRoofs), + ...addItems("stairs", newStairs), + ...addItems("rooms", newRooms), + ); + return ops; +} + +/** Wendet die Transformation immutabel auf das Projekt an (Original + Kopien), über {@link transformOps}. */ +export function commitTransform( + project: Project, + sel: TransformSelection, + op: TransformOp, + pts: Vec2[], + mode: CopyMode, + count: number, +): Project { + return applyOps(project, transformOps(project, sel, op, pts, mode, count)); +} + +/** + * Wie {@link commitTransform}, als Projekt → Projekt-Funktion mit mitgeführten Ops (`opsMutation`) — + * für `CommandResult.commit`: `setProject` übergibt die Ops ohne Projekt-Differenz an den Kern. + */ +export function transformMutation( + sel: TransformSelection, + op: TransformOp, + pts: Vec2[], + mode: CopyMode, + count: number, +): ProjectMutation { + return opsMutation((p) => transformOps(p, sel, op, pts, mode, count)); } From ef9dc1127cf5b058792495ffb6ae331cea603dbc Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 22:03:28 +0000 Subject: [PATCH 5/5] =?UTF-8?q?[K4][6][8]=20TODO:=20S3=20zweite=20Etappe?= =?UTF-8?q?=20(Aktionen=20erzeugen=20Ops),=20Messung,=20Rest-Liste=20?= =?UTF-8?q?=C3=BCber=20setProject?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- TODO.md | 37 +++++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/TODO.md b/TODO.md index 3c207db6..822f9a6b 100644 --- a/TODO.md +++ b/TODO.md @@ -199,8 +199,33 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern **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]. + **Zweite Etappe (28.10.): Aktionen erzeugen Ops direkt.** Op-Bauhelfer `core/opsBuild.ts` (`patchItem`, `patchItems`, + `addItems`, `removeItems`, `setField`, `fieldOps` = Differenz nur über ein kleines Feld, `opsMutation` = Projekt → Projekt- + Funktion mit mitgeführten Ops); Store `applyChange(ops | (p) => ops, coalesceKey?)`, `setProject` nimmt die Ops einer + `opsMutation` ohne `diffToOps`. Umgestellt: alle Griffe (Wand/2D/Decke/Dach/Treppe/Raum, Kanten, Stempel), Objekt-Info der + Store-Aktionen (update*, Farbe/Füllung/Vorder-/Hintergrund, Resize, Dicken, Polylinien-Punkte), Panel-Eigenschaften der + 2D-Elemente, Auswahl verschieben/kopieren/drehen/spiegeln/skalieren (`transformOps`), Löschen der Auswahl, Ebenen/ + Sichtbarkeit/Kategorien, Text-Tippen, Zeichenbefehle (Wand, Decke, Raum, Treppe, Öffnung, Dach, Stütze, Extrusion, alle + 2D-Zeichenbefehle, Bemassung, move/copy/mirror/rotate/scale/array; Gruppen-Zuordnung beim Zeichnen in einer Gruppe über + `activeGroupOps`). Gruppen: Löschen (+ Schnittlinien) und aufgeschobene Griff-Commits = ein Schritt; `groupChanges(fn, key)` + mit Schlüssel (Kern `begin_group_keyed`): ein Griff-Zug, der je Mausschritt mitgeführte Ecken bewegt, ist EIN Undo-Schritt + (vorher mehrere je Mausschritt). Kern: Positions-Index für `replace`-Serien (`PosCache`), `commit` übernimmt die Ops (eine + Kopie weniger); TS-`applyOps` kopiert jede Liste je Aufruf einmal, Index ab der zweiten Suche. Gleichheit: beim Umbau 2400 + Zufallsschritte gegen die alte setProject-Fassung und 400 Transformationen gegen das alte `commitTransform` (gleiches Projekt + bis auf erzeugte ids und fehlend/leere Listen); bleibende Tests `applyChange.test.ts`, `opsBuild.test.ts`, `ops.apply.test.ts`. + **Messung** (vitest/WASM, Linux-Container unter Last, 3000 Wände, `applyChange.perf.test.ts`): Griff ziehen 3,3 → 0,2–0,3 ms + je Mausschritt, Auswahl (300 Wände) verschieben 30 → 5,5–7,5 ms, Eigenschaft tippen 2,3–3,8 → 0,03 ms; Undo/Redo 0,45 → 0,07 ms. + Kern nativ: 300 `replace` auf 5000 Wände 11,2 → 1,5 ms. Rest beim Verschieben: JSON der 300 Wände (TS→Kern) und Kopien im Kern. + **Noch über `setProject(fn)` + `diffToOps`** (Kosten nur proportional zu den geänderten Listen; keine Mausschritt-Pfade mehr): + Ressourcen/Stifte/Paletten/Text-Stile in `projectSlice.ts` (kleine Listen; `setActivePenSet`/`patchPenSet*` mit + `rebakePenColors` fassen ganze Listen an), `usePanelHostBase.ts` (Stützen, Extrusionen, Layouts/Masterlayouts, Ausschnitte, + Kontext-Objekte), `useProjectActions.ts` (Wand-/Decken-/Dachtypen, Override-Regeln …), `App.tsx` (Stil übertragen, Sperren, + Kategorien ein/aus/isolieren, IFC-/Datei-Import, Kollisions-Marken, Layout-Handler, Georeferenz), Einfügen/Gruppieren/ + Ungruppieren (`useKeyboardShortcuts.ts`), Raumprogramm/Baurecht/Sonnenstand-Panels, `siteSlice.ts`, Ressourcen-Fenster, + Werkzeug-Commits (`tools/`), Editier-Befehle trim/extend/fillet/chamfer/break/join/explode/align/autodim/defblock/georef/ + sectionline/solid/solidbool/voidbox/terrain/ceilingOpening, Befehls-Commits innerhalb einer Gruppe ohne `opsMutation`. + Offen: diese Liste abbauen, danach `diffToOps` nur noch für Laden/Fremdstände; Ebenen-/Gruppen-Logik (`groupActions.ts`) nach + Rust; 3D-Griffe mit mitgeführten Ecken (`onEdit3dVertex`) ebenfalls als Gruppe; 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 @@ -290,7 +315,9 @@ Entscheid CLA vs. Verzicht auf Dual Licensing. ### Befehle, Undo, Validierung - ◐ **[6] Jede Aktion ist ein Befehl mit JSON-Parametern.** Registratur vorhanden, aber interaktiv; - Panels/Griffe ändern das Projekt direkt. · L + Panels/Griffe ändern das Projekt direkt. 28.10.: die häufigsten Aktionen (Griffe, Objekt-Info, Auswahl-Transformationen, + Löschen, Zeichenbefehle) liefern ihre Änderung als JSON-Ops (`core/opsBuild.ts`, Store `applyChange`) — Grundlage für + Makros/MCP; Rest-Liste unter [K4] S3. · L - ◐ **[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 @@ -298,7 +325,9 @@ Entscheid CLA vs. Verzicht auf Dual Licensing. 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 + Snapshots mehr ([K4] S3). 28.10.: Griffe, Objekt-Info, Auswahl-Transformationen, Löschen und Zeichenbefehle erzeugen Ops + direkt (`applyChange`/`opsMutation`); Gruppen mit Schlüssel: ein Griff-Zug mit mitgeführten Ecken = ein Schritt. Offen: + Rest-Liste unter [K4] S3. · M - ◐ **[9] MCP-Brücke.** Headless `dossier-cli … mcp`; Brücke zum offenen Fenster fehlt. · M ### Daten