Merge [K4][6][8] Aktionen erzeugen Ops direkt (Griffe, Objekt-Info, Auswahl, Zeichenbefehle ohne diffToOps), Gruppen mit Schluessel, schnelleres applyOps
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
60 files changed
+1780
-817
No files matched your search
@@ -229,8 +229,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
|
||||
@@ -320,7 +345,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
|
||||
@@ -328,7 +355,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
|
||||
|
||||
+208
-35
@@ -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<String, PosEntry>);
|
||||
|
||||
enum PosEntry {
|
||||
/// Einmal linear gesucht.
|
||||
Once,
|
||||
Built(HashMap<u64, usize>),
|
||||
}
|
||||
|
||||
/// 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<usize> {
|
||||
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<u64, usize> = 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<Document, String> {
|
||||
match serde_json::from_str::<Value>(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>, Op) {
|
||||
fn apply_recorded(&mut self, op: &Op, pos: &mut PosCache) -> (Vec<Op>, 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<Op>, Vec<Op>), Vec<String>> {
|
||||
fn apply_checked(&mut self, ops: &[Op], sanitize: bool) -> Result<(Vec<bool>, Vec<Op>), Vec<String>> {
|
||||
// Alt-Doppelungen der Listen merken, in die eingefügt oder die gesetzt wird.
|
||||
let mut had_dup: HashSet<String> = HashSet::new();
|
||||
for op in ops {
|
||||
@@ -218,17 +285,19 @@ impl Document {
|
||||
}
|
||||
}
|
||||
let mut inverses: Vec<Vec<Op>> = Vec::with_capacity(ops.len());
|
||||
let mut forward: Vec<Op> = Vec::with_capacity(ops.len());
|
||||
let mut as_add: Vec<bool> = 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<String>> {
|
||||
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<Op>, key: Option<&str>, now: f64, sanitize: bool) -> Result<(), Vec<String>> {
|
||||
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<Op> = 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<Value> = (0..10).map(|i| json!({"id": format!("e{i}"), "pad": "x".repeat(100)})).collect();
|
||||
for i in 0..20 {
|
||||
d.commit(&ops(json!([{"kind":"setField","key":"blob","value":big.clone()}, {"kind":"setField","key":"i","value":i}])), None, i as f64 * 1000.0, false).unwrap();
|
||||
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<Value> = (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();
|
||||
|
||||
@@ -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<String>,
|
||||
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) => {
|
||||
|
||||
@@ -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());
|
||||
|
||||
+49
-32
@@ -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,
|
||||
|
||||
@@ -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)) },
|
||||
];
|
||||
},
|
||||
|
||||
|
||||
@@ -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) },
|
||||
];
|
||||
},
|
||||
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
@@ -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)) },
|
||||
];
|
||||
},
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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)) },
|
||||
];
|
||||
},
|
||||
|
||||
|
||||
@@ -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 }];
|
||||
|
||||
@@ -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),
|
||||
},
|
||||
];
|
||||
},
|
||||
|
||||
@@ -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)) },
|
||||
];
|
||||
},
|
||||
|
||||
|
||||
@@ -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)) },
|
||||
];
|
||||
},
|
||||
|
||||
|
||||
@@ -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)) },
|
||||
];
|
||||
},
|
||||
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
@@ -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)) },
|
||||
];
|
||||
},
|
||||
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -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] => {
|
||||
|
||||
@@ -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),
|
||||
},
|
||||
];
|
||||
},
|
||||
|
||||
@@ -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),
|
||||
},
|
||||
];
|
||||
},
|
||||
|
||||
@@ -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 }];
|
||||
|
||||
@@ -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)) },
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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)) },
|
||||
];
|
||||
},
|
||||
|
||||
|
||||
@@ -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)) },
|
||||
];
|
||||
},
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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)) },
|
||||
];
|
||||
},
|
||||
|
||||
|
||||
+18
-17
@@ -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);
|
||||
}),
|
||||
},
|
||||
];
|
||||
},
|
||||
|
||||
@@ -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();
|
||||
},
|
||||
|
||||
@@ -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)) },
|
||||
];
|
||||
},
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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),
|
||||
},
|
||||
];
|
||||
},
|
||||
|
||||
@@ -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),
|
||||
},
|
||||
];
|
||||
},
|
||||
|
||||
@@ -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) }],
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
+12
-10
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
},
|
||||
|
||||
@@ -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)) },
|
||||
];
|
||||
},
|
||||
|
||||
|
||||
@@ -210,6 +210,15 @@ export class ProjectDocument {
|
||||
if (this.handle) core().doc_group_begin(this.handle);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wie {@link beginGroup}, mit `coalesceKey` (+ `now` in ms): aufeinanderfolgende Gruppen mit
|
||||
* gleichem Schlüssel im Zeitfenster schliessen an denselben Undo-Schritt an (Griff-Zug, der je
|
||||
* Mausschritt mehrere Elemente bewegt), [K4] S3.
|
||||
*/
|
||||
beginKeyedGroup(coalesceKey: string, now: number): void {
|
||||
if (this.handle) core().doc_group_begin_keyed(this.handle, coalesceKey, now);
|
||||
}
|
||||
|
||||
endGroup(): void {
|
||||
if (this.handle) core().doc_group_end(this.handle);
|
||||
}
|
||||
|
||||
@@ -50,3 +50,5 @@ export { readPdfVectorPage, pdfPageToImport, pdfPageInfo, pdfMetersPerPt, isPdfF
|
||||
export type { PdfVectorPage, PdfVectorPath, PdfVectorText } from "../io/pdfVector";
|
||||
export { readMesh, meshObjectsToImportedMeshes, formatMeshReport, isMeshFile, MESH_UNITS, MESH_UNIT_SCALE } from "../io/meshImport";
|
||||
export type { MeshObject, MeshImportReport, MeshUnit, MeshUp, MeshPlacement } from "../io/meshImport";
|
||||
export { addItems, fieldOps, findItem, isOpsMutation, itemsOf, opsMutation, patchItem, patchItems, removeItems, replaceItem, setField, setFieldIfChanged } from "./opsBuild";
|
||||
export type { EntityCollection, EntityOf, ProjectMutation } from "./opsBuild";
|
||||
@@ -0,0 +1,130 @@
|
||||
// [K4] S3: `applyOps` führt die Leseansicht mit Op-Serien nach (z. B. 300 `replace` beim Verschieben
|
||||
// einer Auswahl). Die schnelle Fassung (Listen innerhalb eines Aufrufs nur einmal kopiert, id-Index
|
||||
// je Liste) muss genau das Ergebnis der einfachen Fassung liefern — hier als Referenz festgehalten.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { applyOps } from "./ops";
|
||||
import type { CoreOp } from "./ops";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Project } from "../model/types";
|
||||
|
||||
type Entity = { id: string } & Record<string, unknown>;
|
||||
|
||||
/** Referenz: die einfache Fassung (je Op eine neue Liste, lineare Suche). */
|
||||
function referenceApplyOps(project: Project, ops: readonly CoreOp[]): Project {
|
||||
let cur = project as unknown as Record<string, unknown>;
|
||||
const listOf = (c: string): Entity[] => (Array.isArray(cur[c]) ? (cur[c] as Entity[]) : []);
|
||||
for (const op of ops) {
|
||||
switch (op.kind) {
|
||||
case "setField": {
|
||||
if (op.value !== undefined && op.at !== undefined && !(op.key in cur)) {
|
||||
const entries = Object.entries(cur);
|
||||
entries.splice(Math.max(0, Math.min(entries.length, op.at)), 0, [op.key, op.value]);
|
||||
cur = Object.fromEntries(entries);
|
||||
break;
|
||||
}
|
||||
const next = { ...cur };
|
||||
if (op.value === undefined) delete next[op.key];
|
||||
else next[op.key] = op.value;
|
||||
cur = next;
|
||||
break;
|
||||
}
|
||||
case "add": {
|
||||
const list = listOf(op.collection);
|
||||
const at = op.at === undefined ? list.length : Math.max(0, Math.min(list.length, op.at));
|
||||
cur = { ...cur, [op.collection]: [...list.slice(0, at), ...op.items, ...list.slice(at)] };
|
||||
break;
|
||||
}
|
||||
case "replace": {
|
||||
const list = listOf(op.collection);
|
||||
const idx = list.findIndex((e) => e.id === op.entity.id);
|
||||
if (idx < 0) cur = { ...cur, [op.collection]: [...list, op.entity] };
|
||||
else {
|
||||
const out = list.slice();
|
||||
out[idx] = op.entity;
|
||||
cur = { ...cur, [op.collection]: out };
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "remove": {
|
||||
const drop = new Set(op.ids);
|
||||
cur = { ...cur, [op.collection]: listOf(op.collection).filter((e) => !drop.has(e.id)) };
|
||||
break;
|
||||
}
|
||||
case "reorder": {
|
||||
const list = listOf(op.collection);
|
||||
const byId = new Map(list.map((e) => [e.id, e]));
|
||||
const ordered = op.ids.map((id) => byId.get(id)).filter((e): e is Entity => e !== undefined);
|
||||
const inOps = new Set(op.ids);
|
||||
cur = { ...cur, [op.collection]: [...ordered, ...list.filter((e) => !inOps.has(e.id))] };
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return cur as unknown as Project;
|
||||
}
|
||||
|
||||
function rng(seed: number): () => number {
|
||||
let x = seed >>> 0;
|
||||
return () => ((x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296);
|
||||
}
|
||||
|
||||
/** Zufällige Op-Folge, auch Unsinn (fehlende ids, Doppelungen, Felder ohne Liste). */
|
||||
function randomOps(p: Project, seed: number): CoreOp[] {
|
||||
const r = rng(seed);
|
||||
const pick = <T,>(a: readonly T[]): T => a[Math.floor(r() * a.length)];
|
||||
const colls = ["walls", "drawings2d", "rooms", "nope", "name"];
|
||||
const ids = [...p.walls.map((w) => w.id), ...p.drawings2d.map((d) => d.id), "x1", "x2", "x3"];
|
||||
const ops: CoreOp[] = [];
|
||||
const n = 1 + Math.floor(r() * 25);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const c = pick(colls);
|
||||
const k = r();
|
||||
if (k < 0.45) ops.push({ kind: "replace", collection: c, entity: { id: pick(ids), v: Math.floor(r() * 100) } });
|
||||
else if (k < 0.6) {
|
||||
const items = Array.from({ length: Math.floor(r() * 3) }, () => ({ id: pick(ids), a: r() }));
|
||||
ops.push(r() < 0.5 ? { kind: "add", collection: c, items } : { kind: "add", collection: c, items, at: Math.floor(r() * 20) - 3 });
|
||||
} else if (k < 0.72) ops.push({ kind: "remove", collection: c, ids: [pick(ids), pick(ids)] });
|
||||
else if (k < 0.82) ops.push({ kind: "reorder", collection: c, ids: [pick(ids), pick(ids), pick(ids)] });
|
||||
else if (k < 0.9) ops.push({ kind: "setField", key: pick(colls), value: r() < 0.5 ? [{ id: pick(ids) }] : r() });
|
||||
else if (k < 0.95) ops.push({ kind: "setField", key: pick(colls) });
|
||||
else ops.push({ kind: "setField", key: `neu${Math.floor(r() * 3)}`, value: r(), at: Math.floor(r() * 5) });
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
describe("applyOps (schnelle Fassung) = Referenz", () => {
|
||||
it("2000 zufällige Op-Folgen: gleiches JSON, gleiche Feld-Reihenfolge, Original unberührt", () => {
|
||||
const snap = JSON.stringify(sampleProject);
|
||||
for (let seed = 1; seed <= 2000; seed++) {
|
||||
const ops = randomOps(sampleProject, seed);
|
||||
const a = applyOps(sampleProject, ops);
|
||||
const b = referenceApplyOps(sampleProject, ops);
|
||||
expect(JSON.stringify(a)).toBe(JSON.stringify(b));
|
||||
}
|
||||
expect(JSON.stringify(sampleProject)).toBe(snap);
|
||||
});
|
||||
|
||||
it("unberührte Listen und Elemente behalten ihre Identität", () => {
|
||||
const w = sampleProject.walls;
|
||||
const out = applyOps(sampleProject, [
|
||||
{ kind: "replace", collection: "walls", entity: { ...w[0], height: 7 } },
|
||||
{ kind: "replace", collection: "walls", entity: { ...w[1], height: 8 } },
|
||||
]);
|
||||
expect(out.drawings2d).toBe(sampleProject.drawings2d);
|
||||
expect(out.walls[2]).toBe(w[2]);
|
||||
expect(out.walls[0].height).toBe(7);
|
||||
expect(sampleProject.walls[0]).toBe(w[0]);
|
||||
expect(applyOps(sampleProject, [])).toBe(sampleProject);
|
||||
});
|
||||
|
||||
it("vom Aufrufer übergebene Werte werden nicht verändert", () => {
|
||||
const list = [{ id: "a" }, { id: "b" }];
|
||||
const out = applyOps(sampleProject, [
|
||||
{ kind: "setField", key: "walls", value: list },
|
||||
{ kind: "replace", collection: "walls", entity: { id: "a", z: 1 } },
|
||||
{ kind: "add", collection: "walls", items: [{ id: "c" }] },
|
||||
]);
|
||||
expect(list).toEqual([{ id: "a" }, { id: "b" }]);
|
||||
expect(out.walls).toEqual([{ id: "a", z: 1 }, { id: "b" }, { id: "c" }]);
|
||||
});
|
||||
});
|
||||
+73
-19
@@ -106,11 +106,27 @@ function diffList(collection: string, va: Entity[], vb: Entity[], ops: CoreOp[])
|
||||
}
|
||||
}
|
||||
|
||||
/** Wendet eine Op-Folge rein an (kein Zugriff auf Store/UI). */
|
||||
/**
|
||||
* Wendet eine Op-Folge rein an (kein Zugriff auf Store/UI). Unberührte Listen und Elemente behalten
|
||||
* ihre Identität. Innerhalb eines Aufrufs wird jede Liste höchstens einmal kopiert und für
|
||||
* `replace`-Serien (Auswahl verschieben: hunderte Elemente) über einen id-Index angesprochen —
|
||||
* Ergebnis gleich der einfachen Fassung (Test `ops.apply.test.ts`).
|
||||
*/
|
||||
export function applyOps(project: Project, ops: readonly CoreOp[]): Project {
|
||||
let cur = project as unknown as Record<string, unknown>;
|
||||
for (const op of ops) cur = applyOne(cur, op);
|
||||
return cur as unknown as Project;
|
||||
if (ops.length === 0) return project;
|
||||
const st: ApplyState = { cur: { ...(project as unknown as Record<string, unknown>) }, owned: new Set(), index: new Map() };
|
||||
for (const op of ops) applyOne(st, op);
|
||||
return st.cur as unknown as Project;
|
||||
}
|
||||
|
||||
/** Zustand eines `applyOps`-Aufrufs: `cur` ist eine eigene Kopie der obersten Ebene; Listen in
|
||||
* `owned` wurden in diesem Aufruf neu angelegt (dürfen verändert werden), `index` = id → Position
|
||||
* (erstes Vorkommen) solcher Listen. */
|
||||
interface ApplyState {
|
||||
cur: Record<string, unknown>;
|
||||
owned: Set<string>;
|
||||
/** `null` = einmal linear gesucht, der Index wird bei der nächsten Suche gebaut. */
|
||||
index: Map<string, Map<string, number> | null>;
|
||||
}
|
||||
|
||||
function listOf(cur: Record<string, unknown>, collection: string): Entity[] {
|
||||
@@ -118,43 +134,81 @@ function listOf(cur: Record<string, unknown>, collection: string): Entity[] {
|
||||
return Array.isArray(v) ? (v as Entity[]) : [];
|
||||
}
|
||||
|
||||
function applyOne(cur: Record<string, unknown>, op: CoreOp): Record<string, unknown> {
|
||||
/** Setzt `collection` auf eine neue (eigene) Liste; ein vorhandener Index verfällt. */
|
||||
function putList(st: ApplyState, collection: string, list: Entity[]): void {
|
||||
st.cur[collection] = list;
|
||||
st.owned.add(collection);
|
||||
st.index.delete(collection);
|
||||
}
|
||||
|
||||
function applyOne(st: ApplyState, op: CoreOp): void {
|
||||
const cur = st.cur;
|
||||
switch (op.kind) {
|
||||
case "setField": {
|
||||
// Der Wert gehört dem Aufrufer: nie verändern.
|
||||
st.owned.delete(op.key);
|
||||
st.index.delete(op.key);
|
||||
if (op.value !== undefined && op.at !== undefined && !(op.key in cur)) {
|
||||
// Neues Feld an Position `at` (wie `shift_insert` im Kern).
|
||||
const entries = Object.entries(cur);
|
||||
entries.splice(Math.max(0, Math.min(entries.length, op.at)), 0, [op.key, op.value]);
|
||||
return Object.fromEntries(entries);
|
||||
st.cur = Object.fromEntries(entries);
|
||||
return;
|
||||
}
|
||||
const next = { ...cur };
|
||||
if (op.value === undefined) delete next[op.key];
|
||||
else next[op.key] = op.value;
|
||||
return next;
|
||||
if (op.value === undefined) delete cur[op.key];
|
||||
else cur[op.key] = op.value;
|
||||
return;
|
||||
}
|
||||
case "add": {
|
||||
const list = listOf(cur, op.collection);
|
||||
const at = op.at === undefined ? list.length : Math.max(0, Math.min(list.length, op.at));
|
||||
return { ...cur, [op.collection]: [...list.slice(0, at), ...op.items, ...list.slice(at)] };
|
||||
putList(st, op.collection, [...list.slice(0, at), ...op.items, ...list.slice(at)]);
|
||||
return;
|
||||
}
|
||||
case "replace": {
|
||||
const list = listOf(cur, op.collection);
|
||||
const idx = list.findIndex((e) => e.id === op.entity.id);
|
||||
if (idx < 0) return { ...cur, [op.collection]: [...list, op.entity] };
|
||||
const out = list.slice();
|
||||
out[idx] = op.entity;
|
||||
return { ...cur, [op.collection]: out };
|
||||
const c = op.collection;
|
||||
let list: Entity[];
|
||||
if (st.owned.has(c)) list = cur[c] as Entity[];
|
||||
else {
|
||||
list = listOf(cur, c).slice();
|
||||
putList(st, c, list);
|
||||
}
|
||||
// Erste Suche in dieser Liste linear (ein Drag-Schritt), ab der zweiten über den Index.
|
||||
let idx = st.index.get(c);
|
||||
let at: number | undefined;
|
||||
if (idx === undefined) {
|
||||
st.index.set(c, null);
|
||||
const i = list.findIndex((e) => e?.id === op.entity.id);
|
||||
at = i < 0 ? undefined : i;
|
||||
} else {
|
||||
if (idx === null) {
|
||||
idx = new Map();
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const id = list[i]?.id;
|
||||
if (!idx.has(id)) idx.set(id, i);
|
||||
}
|
||||
st.index.set(c, idx);
|
||||
}
|
||||
at = idx.get(op.entity.id);
|
||||
}
|
||||
if (at === undefined) {
|
||||
idx?.set(op.entity.id, list.length);
|
||||
list.push(op.entity);
|
||||
} else list[at] = op.entity;
|
||||
return;
|
||||
}
|
||||
case "remove": {
|
||||
const drop = new Set(op.ids);
|
||||
return { ...cur, [op.collection]: listOf(cur, op.collection).filter((e) => !drop.has(e.id)) };
|
||||
putList(st, op.collection, listOf(cur, op.collection).filter((e) => !drop.has(e.id)));
|
||||
return;
|
||||
}
|
||||
case "reorder": {
|
||||
const list = listOf(cur, op.collection);
|
||||
const byId = new Map(list.map((e) => [e.id, e]));
|
||||
const ordered = op.ids.map((id) => byId.get(id)).filter((e): e is Entity => e !== undefined);
|
||||
const inOps = new Set(op.ids);
|
||||
return { ...cur, [op.collection]: [...ordered, ...list.filter((e) => !inOps.has(e.id))] };
|
||||
putList(st, op.collection, [...ordered, ...list.filter((e) => !inOps.has(e.id))]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
// Op-Bauhelfer ([K4] S3): Ergebnis = das bisherige Projekt → Projekt-Muster (`map`/`filter`/Anhängen)
|
||||
// über `diffToOps`, auf Zufallsprojekten; unveränderte Elemente bleiben identisch.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { applyOps, diffToOps } from "./ops";
|
||||
import {
|
||||
addItems,
|
||||
fieldOps,
|
||||
findItem,
|
||||
isOpsMutation,
|
||||
opsMutation,
|
||||
patchItem,
|
||||
patchItems,
|
||||
removeItems,
|
||||
setField,
|
||||
setFieldIfChanged,
|
||||
} from "./opsBuild";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Project, Wall } from "../model/types";
|
||||
|
||||
function rng(seed: number): () => number {
|
||||
let x = seed >>> 0;
|
||||
return () => ((x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296);
|
||||
}
|
||||
|
||||
function project(seed: number): Project {
|
||||
const r = rng(seed);
|
||||
const n = 1 + Math.floor(r() * 40);
|
||||
const base = sampleProject.walls;
|
||||
const walls: Wall[] = Array.from({ length: n }, (_, i) => ({ ...base[i % base.length], id: `w${i}`, height: r() * 3 }));
|
||||
return { ...sampleProject, walls };
|
||||
}
|
||||
|
||||
/** Alter Weg: Projekt → Projekt, dann über die Differenz. */
|
||||
const viaDiff = (p: Project, next: Project): Project => applyOps(p, diffToOps(p, next));
|
||||
|
||||
describe("Op-Bauhelfer", () => {
|
||||
it("patchItem = map über die Liste (Teilobjekt und Funktion), Zufall", () => {
|
||||
for (let seed = 1; seed <= 300; seed++) {
|
||||
const p = project(seed);
|
||||
const r = rng(seed + 1000);
|
||||
const id = `w${Math.floor(r() * (p.walls.length + 3))}`; // auch fehlende ids
|
||||
const h = r();
|
||||
const a = applyOps(p, patchItem(p, "walls", id, { height: h }));
|
||||
const b = viaDiff(p, { ...p, walls: p.walls.map((w) => (w.id === id ? { ...w, height: h } : w)) });
|
||||
expect(a).toEqual(b);
|
||||
const f = (w: Wall): Wall => ({ ...w, start: { x: w.start.x + h, y: w.start.y } });
|
||||
expect(applyOps(p, patchItem(p, "walls", id, f))).toEqual(viaDiff(p, { ...p, walls: p.walls.map((w) => (w.id === id ? f(w) : w)) }));
|
||||
// Unveränderte Elemente identisch.
|
||||
const out = applyOps(p, patchItem(p, "walls", "w0", { height: 9 }));
|
||||
if (p.walls.length > 1) expect(out.walls[1]).toBe(p.walls[1]);
|
||||
}
|
||||
});
|
||||
|
||||
it("patchItem: fehlendes Element oder gleiches Objekt → keine Op", () => {
|
||||
expect(patchItem(sampleProject, "walls", "gibt-es-nicht", { height: 1 })).toEqual([]);
|
||||
expect(patchItem(sampleProject, "walls", sampleProject.walls[0].id, (w) => w)).toEqual([]);
|
||||
});
|
||||
|
||||
it("patchItems / removeItems / addItems = map / filter / Anhängen, Zufall", () => {
|
||||
for (let seed = 1; seed <= 300; seed++) {
|
||||
const p = project(seed);
|
||||
const r = rng(seed + 7);
|
||||
const ids = p.walls.filter(() => r() < 0.3).map((w) => w.id);
|
||||
const set = new Set(ids);
|
||||
const mv = (w: Wall): Wall => ({ ...w, start: { x: w.start.x, y: w.start.y + 1 }, end: { x: w.end.x, y: w.end.y + 1 } });
|
||||
expect(applyOps(p, patchItems(p, "walls", ids, mv))).toEqual(viaDiff(p, { ...p, walls: p.walls.map((w) => (set.has(w.id) ? mv(w) : w)) }));
|
||||
expect(applyOps(p, removeItems(p, "walls", set))).toEqual(viaDiff(p, { ...p, walls: p.walls.filter((w) => !set.has(w.id)) }));
|
||||
const extra: Wall[] = [{ ...p.walls[0], id: `neu${seed}` }];
|
||||
expect(applyOps(p, addItems("walls", extra))).toEqual(viaDiff(p, { ...p, walls: [...p.walls, ...extra] }));
|
||||
const at = Math.floor(r() * p.walls.length);
|
||||
expect(applyOps(p, addItems("walls", extra, at))).toEqual(
|
||||
viaDiff(p, { ...p, walls: [...p.walls.slice(0, at), ...extra, ...p.walls.slice(at)] }),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("leere Änderungen ergeben keine Ops; Prädikat statt ids", () => {
|
||||
expect(removeItems(sampleProject, "walls", [])).toEqual([]);
|
||||
expect(addItems("walls", [])).toEqual([]);
|
||||
expect(patchItems(sampleProject, "walls", () => false, (w) => ({ ...w }))).toEqual([]);
|
||||
const first = sampleProject.walls[0].id;
|
||||
expect(removeItems(sampleProject, "walls", (w) => w.id === first)).toEqual([{ kind: "remove", collection: "walls", ids: [first] }]);
|
||||
expect(findItem(sampleProject, "walls", first)).toBe(sampleProject.walls[0]);
|
||||
});
|
||||
|
||||
it("setField / setFieldIfChanged", () => {
|
||||
expect(setField("name", "X")).toEqual({ kind: "setField", key: "name", value: "X" });
|
||||
expect(setField("geoAnchor", undefined)).toEqual({ kind: "setField", key: "geoAnchor" });
|
||||
expect(setFieldIfChanged(sampleProject, "name", sampleProject.name)).toEqual([]);
|
||||
expect(applyOps(sampleProject, setFieldIfChanged(sampleProject, "name", "Y")).name).toBe("Y");
|
||||
});
|
||||
|
||||
it("fieldOps: Differenz nur über ein Feld = volle Differenz, Zufall", () => {
|
||||
for (let seed = 1; seed <= 200; seed++) {
|
||||
const p = project(seed);
|
||||
const r = rng(seed + 99);
|
||||
const levels = p.drawingLevels.filter(() => r() < 0.8).map((z) => (r() < 0.3 ? { ...z, visible: !z.visible } : z));
|
||||
if (r() < 0.3) levels.reverse();
|
||||
const next = { ...p, drawingLevels: levels };
|
||||
expect(fieldOps(p, "drawingLevels", levels)).toEqual(diffToOps(p, next));
|
||||
expect(applyOps(p, fieldOps(p, "drawingLevels", levels))).toEqual(next);
|
||||
}
|
||||
expect(fieldOps(sampleProject, "layers", sampleProject.layers)).toEqual([]);
|
||||
expect(fieldOps(sampleProject, "geoAnchor", undefined)).toEqual(diffToOps(sampleProject, { ...sampleProject, geoAnchor: undefined }));
|
||||
});
|
||||
|
||||
it("opsMutation: wirkt wie eine Projekt → Projekt-Funktion und trägt die Ops mit", () => {
|
||||
const id = sampleProject.walls[0].id;
|
||||
const m = opsMutation((p) => patchItem(p, "walls", id, { height: 4.2 }));
|
||||
expect(isOpsMutation(m)).toBe(true);
|
||||
expect(isOpsMutation((p: Project) => p)).toBe(false);
|
||||
expect(m(sampleProject).walls[0].height).toBe(4.2);
|
||||
expect(m.toOps(sampleProject)).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
// Op-Bauhelfer ([K4] S3, zweite Etappe): Aktionen beschreiben ihre Änderung direkt als
|
||||
// {@link CoreOp}s statt als Projekt → Projekt-Funktion, die `setProject` erst per `diffToOps` über
|
||||
// alle Listen zurückübersetzen muss (bei 3000 Wänden ≈ 2,4 ms je Mausschritt). Die Helfer lesen
|
||||
// nur das betroffene Element; unveränderte Elemente bleiben unberührt (Identität in der
|
||||
// TS-Leseansicht, `applyOps`).
|
||||
//
|
||||
// Store: `applyChange(ops | (p) => ops, coalesceKey?)`. Wo eine Schnittstelle weiter eine
|
||||
// Projekt → Projekt-Funktion erwartet (Befehle: `CommandResult.commit`), trägt
|
||||
// {@link opsMutation} die Ops mit — `setProject` nimmt dann die Ops ohne Differenz.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { applyOps, diffToOps } from "./ops";
|
||||
import type { CoreOp } from "./ops";
|
||||
|
||||
/** Projekt-Felder, die Listen von Elementen mit `id` sind (walls, drawings2d, rooms, …). */
|
||||
export type EntityCollection = {
|
||||
[K in keyof Project]-?: NonNullable<Project[K]> extends readonly (infer E)[]
|
||||
? E extends { id: string }
|
||||
? K
|
||||
: never
|
||||
: never;
|
||||
}[keyof Project];
|
||||
|
||||
/** Elementtyp einer Liste. */
|
||||
export type EntityOf<K extends EntityCollection> = NonNullable<Project[K]> extends readonly (infer E)[] ? E : never;
|
||||
|
||||
type AnyEntity = { id: string } & Record<string, unknown>;
|
||||
|
||||
/** Die Liste `collection` (fehlend = leer). */
|
||||
export function itemsOf<K extends EntityCollection>(p: Project, collection: K): readonly EntityOf<K>[] {
|
||||
const v = (p as unknown as Record<string, unknown>)[collection];
|
||||
return Array.isArray(v) ? (v as EntityOf<K>[]) : [];
|
||||
}
|
||||
|
||||
/** Element `id` aus `collection` (erstes Vorkommen). */
|
||||
export function findItem<K extends EntityCollection>(p: Project, collection: K, id: string): EntityOf<K> | undefined {
|
||||
return itemsOf(p, collection).find((e) => (e as { id: string }).id === id);
|
||||
}
|
||||
|
||||
/** Ersetzt ein Element (gleiche id, Position bleibt). */
|
||||
export function replaceItem<K extends EntityCollection>(collection: K, entity: EntityOf<K>): CoreOp {
|
||||
return { kind: "replace", collection, entity: entity as unknown as AnyEntity };
|
||||
}
|
||||
|
||||
/**
|
||||
* Ändert Element `id` in `collection`: `patch` als Teilobjekt (`{ ...e, ...patch }`) oder Funktion.
|
||||
* Leer, wenn das Element fehlt oder die Funktion dasselbe Objekt zurückgibt (keine Änderung).
|
||||
*/
|
||||
export function patchItem<K extends EntityCollection>(
|
||||
p: Project,
|
||||
collection: K,
|
||||
id: string,
|
||||
patch: Partial<EntityOf<K>> | ((e: EntityOf<K>) => EntityOf<K>),
|
||||
): CoreOp[] {
|
||||
const old = findItem(p, collection, id);
|
||||
if (old === undefined) return [];
|
||||
const next = typeof patch === "function" ? patch(old) : ({ ...old, ...patch } as EntityOf<K>);
|
||||
return next === old ? [] : [replaceItem(collection, next)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Ändert alle Elemente, deren id in `ids` liegt (bzw. für die `ids(e)` wahr ist), mit `fn`; eine
|
||||
* `replace`-Op je tatsächlich geändertem Element, in Listen-Reihenfolge.
|
||||
*/
|
||||
export function patchItems<K extends EntityCollection>(
|
||||
p: Project,
|
||||
collection: K,
|
||||
ids: ReadonlySet<string> | readonly string[] | ((e: EntityOf<K>) => boolean),
|
||||
fn: (e: EntityOf<K>) => EntityOf<K>,
|
||||
): CoreOp[] {
|
||||
const hit = idTest(ids);
|
||||
const ops: CoreOp[] = [];
|
||||
for (const e of itemsOf(p, collection)) {
|
||||
if (!hit(e)) continue;
|
||||
const next = fn(e);
|
||||
if (next !== e) ops.push(replaceItem(collection, next));
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
/** Fügt Elemente an `at` (Default: Ende) ein; leer ohne Elemente. */
|
||||
export function addItems<K extends EntityCollection>(collection: K, items: readonly EntityOf<K>[], at?: number): CoreOp[] {
|
||||
if (items.length === 0) return [];
|
||||
const op: CoreOp = { kind: "add", collection, items: items as unknown as AnyEntity[] };
|
||||
if (at !== undefined) op.at = at;
|
||||
return [op];
|
||||
}
|
||||
|
||||
/** Entfernt die Elemente aus `ids` (bzw. für die `ids(e)` wahr ist), die es gibt; leer, wenn keines trifft. */
|
||||
export function removeItems<K extends EntityCollection>(
|
||||
p: Project,
|
||||
collection: K,
|
||||
ids: ReadonlySet<string> | readonly string[] | ((e: EntityOf<K>) => boolean),
|
||||
): CoreOp[] {
|
||||
const hit = idTest(ids);
|
||||
const drop: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const e of itemsOf(p, collection)) {
|
||||
const id = (e as { id: string }).id;
|
||||
if (hit(e) && !seen.has(id)) {
|
||||
seen.add(id);
|
||||
drop.push(id);
|
||||
}
|
||||
}
|
||||
return drop.length ? [{ kind: "remove", collection, ids: drop }] : [];
|
||||
}
|
||||
|
||||
/** Setzt ein Projekt-Feld (`undefined` ⇒ Feld entfernen). */
|
||||
export function setField<K extends keyof Project>(key: K, value: Project[K] | undefined): CoreOp {
|
||||
return value === undefined ? { kind: "setField", key } : { kind: "setField", key, value };
|
||||
}
|
||||
|
||||
/** Setzt ein Projekt-Feld nur, wenn sich der Wert (per Referenz) ändert. */
|
||||
export function setFieldIfChanged<K extends keyof Project>(p: Project, key: K, value: Project[K] | undefined): CoreOp[] {
|
||||
return p[key] === value ? [] : [setField(key, value)];
|
||||
}
|
||||
|
||||
function idTest<E>(ids: ReadonlySet<string> | readonly string[] | ((e: E) => boolean)): (e: E) => boolean {
|
||||
if (typeof ids === "function") return ids;
|
||||
const set = ids instanceof Set ? ids : new Set(ids as readonly string[]);
|
||||
return (e) => set.has((e as unknown as { id: string }).id);
|
||||
}
|
||||
|
||||
// ── Projekt → Projekt mit mitgeführten Ops ─────────────────────────────────
|
||||
|
||||
/** Projekt → Projekt-Funktion, die ihre Ops mitträgt (s. {@link opsMutation}). */
|
||||
export type ProjectMutation = ((p: Project) => Project) & { readonly toOps: (p: Project) => CoreOp[] };
|
||||
|
||||
/**
|
||||
* Verpackt einen Op-Bauer als Projekt → Projekt-Funktion (für Schnittstellen wie
|
||||
* `CommandResult.commit`). Aufgerufen liefert sie `applyOps(p, build(p))`; `setProject` erkennt
|
||||
* sie an `toOps` und übergibt die Ops ohne `diffToOps` an den Kern.
|
||||
*/
|
||||
export function opsMutation(build: (p: Project) => CoreOp[]): ProjectMutation {
|
||||
const fn = (p: Project): Project => applyOps(p, build(p));
|
||||
return Object.assign(fn, { toOps: build });
|
||||
}
|
||||
|
||||
/** Ob `fn` ihre Ops mitträgt. */
|
||||
export function isOpsMutation(fn: unknown): fn is ProjectMutation {
|
||||
return typeof fn === "function" && typeof (fn as Partial<ProjectMutation>).toOps === "function";
|
||||
}
|
||||
|
||||
/**
|
||||
* Ops, die das Feld `key` auf `value` bringen — für KLEINE Listen, die eine Hilfsfunktion als Ganzes
|
||||
* neu liefert (Ebenen nach `recomputeFloorElevations`, Kategorien-Baum …): Differenz nur über
|
||||
* dieses eine Feld (Elemente mit id einzeln, sonst `setField`). Grosse Listen (Wände, 2D) gehören
|
||||
* über {@link patchItem}/{@link patchItems}/{@link addItems}/{@link removeItems}.
|
||||
*/
|
||||
export function fieldOps<K extends keyof Project>(p: Project, key: K, value: Project[K] | undefined): CoreOp[] {
|
||||
if (p[key] === value) return [];
|
||||
const before = { [key]: p[key] } as unknown as Project;
|
||||
const after = (value === undefined ? {} : { [key]: value }) as unknown as Project;
|
||||
return diffToOps(before, after);
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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: [] };
|
||||
|
||||
@@ -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<MemberKind, EntityCollection> = {
|
||||
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<string>();
|
||||
const touched = new Set<string>();
|
||||
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<string>();
|
||||
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
|
||||
|
||||
@@ -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<HistorySlice & { project: Proje
|
||||
d.clearHistory();
|
||||
set(historyPatch(d));
|
||||
},
|
||||
groupChanges: (fn) => {
|
||||
groupChanges: (fn, coalesceKey) => {
|
||||
const d = storeDocument(get().project);
|
||||
d.beginGroup();
|
||||
if (coalesceKey) d.beginKeyedGroup(coalesceKey, Date.now());
|
||||
else d.beginGroup();
|
||||
try {
|
||||
fn();
|
||||
} finally {
|
||||
|
||||
+222
-355
File diff suppressed because it is too large.
Load diff
@@ -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):
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
+71
-37
@@ -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));
|
||||
}
|
||||
Reference in new issue
Block a user