[K4] Merge: S4 Projektdatei im Kern (Öffnen/Speichern/Autosave), Importe als Ops, diffToOps gelöscht, Gruppen-Logik in Rust
CLAUDE.md: Abschnitt Ops nachgeführt. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
45 files changed
+1166
-661
No files matched your search
@@ -50,9 +50,10 @@ Der ganze Kern wandert nach Rust (`src-tauri/core`, Crate `dossier-core`); die U
|
||||
`src/core`. Neue Exporte **von Hand** in `src/core/index.ts` bzw. `src/core/extra.ts` eintragen —
|
||||
`scripts/core-facade.py` nicht mehr laufen lassen (es baut die Fassade aus direkten Importen neu und
|
||||
würde sie heute fast leeren).
|
||||
- **Das Projekt ändert sich nur über Ops** (`src/core/ops.ts`): `setProject(fn, coalesceKey?)` übersetzt
|
||||
die Änderung in `CoreOp`s, validiert und wendet sie an. NaN/doppelte ids werden zurückgerollt. Gleicher
|
||||
`coalesceKey` (Regler, Tippen) = ein Undo-Schritt.
|
||||
- **Das Projekt ändert sich nur über Ops** (Kern prüft und führt den Verlauf): `applyChange(ops | (p) => ops, coalesceKey?)`
|
||||
mit den Helfern aus `src/core/opsBuild.ts` (`patchItem`, `addItems`, `removeItems` …); Befehle liefern `opsMutation`.
|
||||
Mehrere Änderungen = ein Undo-Schritt über `groupChanges(fn, key?)`; gleicher `coalesceKey` (Regler, Tippen) ebenso.
|
||||
Öffnen/Neu über `openProjectFile`/`loadProject` (Kern lädt, Verlauf leer). Kein `diffToOps` mehr.
|
||||
- **Modell-Typen kommen aus Rust** ([K4] S4): Neue Modellfelder/-typen NUR im Rust-Modell
|
||||
(`src-tauri/core/src/model/generated.rs`, `manual.rs`; serde- + ts-rs-Attribute, Regeln in `model/ts_export.rs`),
|
||||
dann `npm run gen:types` → `src/model/types.generated.ts` (nie von Hand ändern; `types.ts` re-exportiert sie und
|
||||
|
||||
@@ -351,6 +351,30 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
Rückfall für Befehle ohne mitgeführte Ops in `App.tsx` (gibt es keine mehr; der Typ `commit: (p) => Project` erlaubt es noch).
|
||||
Offen: Ebenen-/Gruppen-Logik (`groupActions.ts`) nach Rust; Undo-Verlauf als Liste in der UI [84]; `diffToOps` entfällt erst, wenn auch
|
||||
Laden/Import/CLI Ops liefern.
|
||||
**Vierte Etappe (29.10.): `diffToOps` gelöscht.** Laden, Import und CLI liefern Ops bzw. laden über den Kern:
|
||||
Öffnen/Vorlage/Wiederherstellen = Store `openProjectFile(text)` (Kern liest, migriert, lädt direkt ins Dokument,
|
||||
Verlauf leer, s. S4), Neu/Musterhaus = `loadProject(p)` (eine explizite Kern-Funktion „Projekt laden“,
|
||||
`doc_load_json`, keine Differenz). DXF/PDF-Import (`runImport`: Ebene, Kategorien, Linienstile, Zeichnungen,
|
||||
Kontext) als Ops in EINER Gruppe = ein Undo-Schritt (vorher bis zu fünf); Bilder einfügen (`imageDrawing2d` +
|
||||
`addItems`); IFC-Bauteile (`ifcElementsToProject` liefert `ops` + `project`, App `applyChange`); CLI-Importe
|
||||
(`fieldOps`/`addItems`/`contextOps`). Das Ressourcen-Fenster ruft nur die echten Handler (schon Ops), sein Projekt
|
||||
ist eine Leseansicht. `setProject` nimmt nur noch `opsMutation` (Typ `ProjectMutation`), `CommandResult.commit`/
|
||||
`ToolResult.commit`/`EngineHost.commit` ebenso; Rückfall `addNewElementsToActiveGroup` und `isOpsMutation`
|
||||
gelöscht. Das gemeinsame Abfrage-Dokument (`documentFor` für fremde Projekte, CLI) folgt feldweise
|
||||
(`fieldOps` je geänderter Referenz, kein Verlauf); Änderungen vorbei an den Ops laden das Store-Dokument neu
|
||||
(`load`, Verlauf leer). Tests erzeugen Zufallsänderungen über `core/projectDiff.testutil.ts` (nur Tests).
|
||||
e2e: Öffnen leert den Verlauf, DXF-Import = ein Undo-Schritt. Nicht in der Tauri-App geprüft (natives Öffnen mit
|
||||
Sperre, Ressourcen-Fenster).
|
||||
**Gruppen-Logik im Kern (29.10.):** `groups.rs` (transitive Mitgliedschaft mit Zyklenschutz, sichtbare Gruppe
|
||||
im Isolations-Kontext, Auswahl um Gruppen erweitern; Abfragen `groupMembership`/`containingGroup`/
|
||||
`expandToGroups`), Fassade `model/groups.ts` (letzte Mitgliedschaft gemerkt: Rahmen-Filter fragt je Element).
|
||||
TS-Rechnung gelöscht (`transitiveMembership`, `topLevelGroups`, `containingGroupId`, `isInsideActiveGroup`,
|
||||
`expandToGroups`); in `state/groupActions.ts` bleiben die Op-Bauer (`groupSelection`, `ungroup`,
|
||||
`activeGroupOps`), das Dimmen der Plan-Primitive und `mergeMembership` für Auswahl-Mengen. Gleichheit (einmalig):
|
||||
400 Zufallsprojekte × 10 Abfragen (Zyklen, doppelte Gruppen-ids, fehlende Gruppen, Pfade mit unbekannter
|
||||
Gruppe), 16000 Vergleiche gleich der alten TS-Fassung. Ebenen-Logik (Kategorien-Baum, `recomputeFloorElevations`)
|
||||
noch TS.
|
||||
Offen: Ebenen-Logik nach Rust; Undo-Verlauf als Liste in der UI [84].
|
||||
- ◐ **S4 Typen aus Rust**: `types.ts` wird aus den Rust-Strukturen erzeugt (ts-rs); Datei-I/O (`projectFormat`, Migration, IFC/DXF/
|
||||
STEP-Ex- und -Import) im Kern.
|
||||
**Typen (28.10.):** Das Rust-Modell (`core/src/model/generated.rs`, `manual.rs`) ist die Quelle; ts-rs 12 (MIT, nur
|
||||
@@ -367,6 +391,24 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
Zufallsprojekte TS → JSON → Rust → JSON (Abfrage `modelJson`: typisiertes Modell OHNE `Extra`-Felder) gleich.
|
||||
`KNOWN_KEYS` per Test aus `model::Project` abgeglichen. `scripts/gen-rust-model.py` gelöscht. Offen: Varianten-Doku
|
||||
getaggter Enums (z. B. `Drawing2DGeom`-Varianten) lässt ts-rs weg (steht in Rust); Datei-I/O-Rest.
|
||||
**Datei-I/O (29.10.):** Öffnen lädt die Datei im Kern direkt ins Dokument (`Document::load_file`, `doc_load_file`:
|
||||
Parse, Migration, Prüfung; TS bekommt die Leseansicht als JSON des Dokuments) — kein TS-Parse und keine
|
||||
Differenz mehr; Speichern, Autosave (jetzt Datei-Text statt Objekt in IndexedDB; alte Objekt-Kopien werden beim
|
||||
Lesen zu Text) und Wiederherstellen (wie Öffnen, mit Migration) gehen denselben Weg. CLI/MCP laden ins
|
||||
gemeinsame Abfrage-Dokument (`sharedDocument().loadFile`), Abfragen danach ohne erneute Übergabe. Speichern ist
|
||||
jetzt Zeichen für Zeichen `JSON.stringify(…, null, 2)`: vorher schrieb der Kern Zahlen wie `5e-6`/`1.2e+20`
|
||||
(JS: `0.000005`/`120000000000000000000`) — `JsFormatter` mit JS-Zahlen, Index-Schlüssel („10“, „21“) beim
|
||||
Laden vorn wie in einem JS-Objekt, ganze Zahlen über 2⁵³ wie JS gerundet; Meldungen mit JS-Zahlen.
|
||||
Gleichheit (einmalig, gegen die frühere TS-Fassung `e02c01d^:src/io/projectFormat.ts` + `JSON.stringify`):
|
||||
1804 Dateien (Beispiel, leer, Projekt mit allen Element-Arten, bigSample(3), 80 Zufallsprojekte, 80 mit
|
||||
kniffligen Zahlen/Index-Schlüsseln/Sonderzeichen; je 11 Fassungen: kompakt, eingerückt, Version 0, Version 1
|
||||
mit Türen, kaputte Listen/unbekannte Felder/ohne id, zu neue/ungültige Version, ohne `walls`, „fremder
|
||||
Schreiber“ mit `1.0`/`1e0`), 977 ladbar: Ergebnis, Hinweise, Migration, Fehlermeldungen (ausser JSON-Syntax-
|
||||
Text) und gespeicherte Datei zeichengleich. Bleibende Tests: `projectFormat.test.ts`, `setProjectOps.test.ts`,
|
||||
Rust `project_format`/`document`. CLI: `convert` obp → obp bytegleich, DXF/IFC-Import (auch `--elements`) gleich
|
||||
wie vorher bis auf erzeugte ids. Messung (vitest/Node, `--no-opt`-WASM, Container unter Last, bigSample(20),
|
||||
2,6 MB, 3600 Wände): Öffnen 106–115 ms (alter Weg ohne den Kern-Parse ≈ 210–260 ms: JSON zurück, Differenz,
|
||||
Commit), Speichern im Kern 32 ms (vorher Kopie des Baums ≈ 80 ms; `JSON.stringify` in JS 17–19 ms).
|
||||
Offene Entscheide/Risiken: Kosten der JSON-Übergabe bei grossen Projekten (Teil-Updates statt Neuaufbau), Struktur-Sharing im
|
||||
React-Store (TS-Spiegel bleibt bis S3), Befehls-Zustandsautomaten sind viel Code (`src/commands/cmds/*`).
|
||||
- **Fertig wenn** (je Etappe): TS-Fassung gelöscht, `npm run check` grün, App/CLI/IFC unverändert.
|
||||
@@ -457,6 +499,7 @@ Entscheid CLA vs. Verzicht auf Dual Licensing.
|
||||
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 (nur Laden/Import/CLI) unter [K4] S3. · L
|
||||
29.10.: auch Laden, Import und CLI liefern Ops bzw. laden über den Kern; `diffToOps` gelöscht ([K4] S3).
|
||||
- ◐ **[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
|
||||
@@ -467,6 +510,7 @@ Entscheid CLA vs. Verzicht auf Dual Licensing.
|
||||
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 (nur Laden/Import/CLI) unter [K4] S3. · M
|
||||
29.10.: auch Laden/Import/CLI ohne Projekt-Differenz (`diffToOps` gelöscht); Öffnen/Neu leeren den Verlauf im Kern, ein Import = ein Schritt ([K4] S3/S4).
|
||||
- ◐ **[9] MCP-Brücke.** Headless `dossier-cli … mcp`; Brücke zum offenen Fenster fehlt. · M
|
||||
|
||||
### Daten
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import type { Page } from "@playwright/test";
|
||||
import {
|
||||
blurFocus,
|
||||
discardIfAsked,
|
||||
elementRows,
|
||||
expect,
|
||||
@@ -66,6 +67,12 @@ test("Speichern und Laden: .obp-Rundreise", async ({ page }) => {
|
||||
await expect(page.locator(".project-name")).toHaveText("Demo-Haus", { timeout: 4000 });
|
||||
await openTab(page, "Elemente");
|
||||
await expect(elementRows(page).filter({ hasText: "W9" })).toBeVisible();
|
||||
|
||||
// Öffnen leert den Verlauf ([K4] S4): Rückgängig führt nicht ins vorherige (leere) Projekt.
|
||||
await blurFocus(page);
|
||||
await page.keyboard.press("ControlOrMeta+z");
|
||||
await expect(page.locator(".project-name")).toHaveText("Demo-Haus");
|
||||
await expect(elementRows(page).filter({ hasText: "W9" })).toBeVisible();
|
||||
});
|
||||
|
||||
test("Export IFC: Datei nicht leer, STEP-Kopf stimmt", async ({ page }) => {
|
||||
@@ -109,4 +116,11 @@ test("Import einer kleinen DXF legt eine Zeichnung an", async ({ page }) => {
|
||||
await expect(dialog).toBeHidden();
|
||||
await openTab(page, "Zeichnungsebenen");
|
||||
await expect(page.getByText("klein", { exact: false }).first()).toBeVisible();
|
||||
|
||||
// Ein Import = ein Undo-Schritt ([K4] S3): einmal Rückgängig entfernt Ebene und Zeichnungen, Wiederholen bringt alles zurück.
|
||||
await blurFocus(page);
|
||||
await page.keyboard.press("ControlOrMeta+z");
|
||||
await expect(page.getByText("klein", { exact: false })).toHaveCount(0);
|
||||
await page.keyboard.press("ControlOrMeta+Shift+z");
|
||||
await expect(page.getByText("klein", { exact: false }).first()).toBeVisible();
|
||||
});
|
||||
@@ -94,6 +94,27 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// Projekt laden ([K4] S4: Öffnen, Neu, Vorlage, Wiederherstellen): ersetzt den ganzen Inhalt und
|
||||
/// leert den Verlauf (Rückgängig führt nicht ins vorherige Projekt).
|
||||
pub fn load(&mut self, root: Map<String, Value>) {
|
||||
self.root = root;
|
||||
self.typed = None;
|
||||
self.dirty.clear();
|
||||
self.history.clear();
|
||||
}
|
||||
|
||||
/// Projektdatei (Text) einlesen, migrieren, prüfen (`project_format`) und laden wie [`Document::load`].
|
||||
/// Ergebnis: Hinweise und Ausgangsversion einer Migration; bei Fehler bleibt das Dokument unverändert.
|
||||
pub fn load_file(&mut self, text: &str, now_ms: f64) -> Result<(Vec<String>, Option<u64>), String> {
|
||||
match crate::project_format::parse_project_file(text, now_ms) {
|
||||
crate::project_format::Parsed::Ok { project, warnings, migrated_from } => {
|
||||
self.load(project);
|
||||
Ok((warnings, migrated_from))
|
||||
}
|
||||
crate::project_format::Parsed::Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Datei-Text des Projekts (`serializeProject`): Formatversion vorn, Einrückung 2.
|
||||
pub fn serialize(&self) -> String {
|
||||
crate::project_format::serialize_project(&self.root)
|
||||
@@ -445,6 +466,29 @@ mod tests {
|
||||
assert_eq!(d.project().unwrap().name, "X");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn laden_ersetzt_inhalt_und_leert_verlauf() {
|
||||
let mut d = doc();
|
||||
d.commit(ops(json!([{"kind":"setField","key":"name","value":"M"}])), None, 0.0, false).unwrap();
|
||||
assert_eq!(d.history().undo_depth(), 1);
|
||||
let n = d.field("walls").unwrap().as_array().unwrap().len();
|
||||
assert_eq!(n, 2);
|
||||
// Kaputte Datei: Fehler, Dokument und Verlauf unverändert.
|
||||
assert!(d.load_file(r#"{"walls":[]}"#, 0.0).is_err());
|
||||
assert_eq!(d.history().undo_depth(), 1);
|
||||
// Alte Datei (Version 1 mit Türen): migriert geladen, Verlauf leer, typisierte Sicht neu.
|
||||
let (warnings, from) = d
|
||||
.load_file(r#"{"formatVersion":1,"id":"q","name":"Q","walls":[],"layers":[],"drawingLevels":[],"doors":[{"id":"D"}]}"#, 0.0)
|
||||
.unwrap();
|
||||
assert!(warnings.is_empty());
|
||||
assert_eq!(from, Some(1));
|
||||
assert_eq!(d.history().undo_depth(), 0);
|
||||
assert_eq!(d.project().unwrap().walls.len(), 0);
|
||||
assert_eq!(d.field("openings").unwrap()[0]["kind"], "door");
|
||||
assert!(d.undo().is_none());
|
||||
assert!(d.serialize().starts_with("{\n \"formatVersion\": 2,\n \"id\": \"q\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kaputte_ops_sind_fehler() {
|
||||
assert!(Op::from_json(&json!({"kind":"add","collection":"w","items":[{"x":1}]})).is_err());
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
//! Gruppen (Vectorworks-artig, [K4] S3, vorher `src/state/groupActions.ts`): Mitgliedschaft über
|
||||
//! verschachtelte Gruppen, die im Isolations-Kontext sichtbare Gruppe eines Elements und das
|
||||
//! Erweitern einer Treffer-Auswahl um ganze Gruppen. Reihenfolgen und Doppelungen wie in der
|
||||
//! TS-Fassung (Vereinigung = `[...new Set([...a, ...b])]`, eigene Listen ohne Untergruppen bleiben roh).
|
||||
|
||||
use crate::model::{Group, Project};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// Mitglieds-IDs je Elementart (Form wie `Group` ohne `id`/`name`/`groupIds`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct Membership {
|
||||
pub wall_ids: Vec<String>,
|
||||
pub drawing_ids: Vec<String>,
|
||||
pub ceiling_ids: Vec<String>,
|
||||
pub room_ids: Vec<String>,
|
||||
pub stair_ids: Vec<String>,
|
||||
pub column_ids: Vec<String>,
|
||||
pub roof_ids: Vec<String>,
|
||||
pub opening_ids: Vec<String>,
|
||||
}
|
||||
|
||||
/// Elementart (`MemberKind` in TS: `"wallIds"` …).
|
||||
pub const KINDS: [&str; 8] = ["wallIds", "drawingIds", "ceilingIds", "roomIds", "stairIds", "columnIds", "roofIds", "openingIds"];
|
||||
|
||||
impl Membership {
|
||||
pub fn list(&self, kind: &str) -> Option<&Vec<String>> {
|
||||
Some(match kind {
|
||||
"wallIds" => &self.wall_ids,
|
||||
"drawingIds" => &self.drawing_ids,
|
||||
"ceilingIds" => &self.ceiling_ids,
|
||||
"roomIds" => &self.room_ids,
|
||||
"stairIds" => &self.stair_ids,
|
||||
"columnIds" => &self.column_ids,
|
||||
"roofIds" => &self.roof_ids,
|
||||
"openingIds" => &self.opening_ids,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn list_mut(&mut self, kind: &str) -> Option<&mut Vec<String>> {
|
||||
Some(match kind {
|
||||
"wallIds" => &mut self.wall_ids,
|
||||
"drawingIds" => &mut self.drawing_ids,
|
||||
"ceilingIds" => &mut self.ceiling_ids,
|
||||
"roomIds" => &mut self.room_ids,
|
||||
"stairIds" => &mut self.stair_ids,
|
||||
"columnIds" => &mut self.column_ids,
|
||||
"roofIds" => &mut self.roof_ids,
|
||||
"openingIds" => &mut self.opening_ids,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn of_group(g: &Group) -> Membership {
|
||||
Membership {
|
||||
wall_ids: g.wall_ids.clone(),
|
||||
drawing_ids: g.drawing_ids.clone(),
|
||||
ceiling_ids: g.ceiling_ids.clone(),
|
||||
room_ids: g.room_ids.clone(),
|
||||
stair_ids: g.stair_ids.clone(),
|
||||
column_ids: g.column_ids.clone(),
|
||||
roof_ids: g.roof_ids.clone(),
|
||||
opening_ids: g.opening_ids.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Vereinigung je Art, erste Vorkommen in Reihenfolge (`mergeMembership`).
|
||||
pub fn merge(&mut self, other: &Membership) {
|
||||
for k in KINDS {
|
||||
let a = self.list_mut(k).expect("Art");
|
||||
let mut seen: HashSet<String> = HashSet::with_capacity(a.len());
|
||||
let mut out: Vec<String> = Vec::with_capacity(a.len());
|
||||
for id in a.drain(..).chain(other.list(k).expect("Art").iter().cloned()) {
|
||||
if seen.insert(id.clone()) {
|
||||
out.push(id);
|
||||
}
|
||||
}
|
||||
*a = out;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn groups(p: &Project) -> &[Group] {
|
||||
p.groups.as_deref().unwrap_or(&[])
|
||||
}
|
||||
|
||||
fn find<'a>(p: &'a Project, id: &str) -> Option<&'a Group> {
|
||||
groups(p).iter().find(|g| g.id == id)
|
||||
}
|
||||
|
||||
/// Transitive Mitgliedschaft einer Gruppe (Untergruppen rekursiv); Zyklenschutz über `seen`
|
||||
/// (gemeinsam für alle Zweige, wie in TS).
|
||||
pub fn transitive_membership(p: &Project, group_id: &str) -> Membership {
|
||||
transitive(p, group_id, &mut HashSet::new())
|
||||
}
|
||||
|
||||
fn transitive(p: &Project, group_id: &str, seen: &mut HashSet<String>) -> Membership {
|
||||
if !seen.insert(group_id.to_string()) {
|
||||
return Membership::default();
|
||||
}
|
||||
let Some(g) = find(p, group_id) else { return Membership::default() };
|
||||
let mut out = Membership::of_group(g);
|
||||
for sub in &g.group_ids {
|
||||
let m = transitive(p, sub, seen);
|
||||
out.merge(&m);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Gruppen, die nicht Untergruppe einer Gruppe sind.
|
||||
fn top_level(p: &Project) -> Vec<&Group> {
|
||||
let nested: HashSet<&str> = groups(p).iter().flat_map(|g| g.group_ids.iter().map(String::as_str)).collect();
|
||||
groups(p).iter().filter(|g| !nested.contains(g.id.as_str())).collect()
|
||||
}
|
||||
|
||||
/// Die im Isolations-Kontext `path` (leer = nicht isoliert) sichtbare Gruppe, die das Element
|
||||
/// enthält: ohne Isolation unter den obersten Gruppen, isoliert nur unter den direkten
|
||||
/// Untergruppen der aktiven Gruppe. `None` = keine.
|
||||
pub fn containing_group_id(p: &Project, kind: &str, id: &str, path: &[String]) -> Option<String> {
|
||||
let candidates: Vec<&Group> = match path.last() {
|
||||
None => top_level(p),
|
||||
Some(active) => find(p, active)?.group_ids.iter().filter_map(|gid| find(p, gid)).collect(),
|
||||
};
|
||||
candidates
|
||||
.into_iter()
|
||||
.find(|g| transitive_membership(p, &g.id).list(kind).is_some_and(|l| l.iter().any(|x| x == id)))
|
||||
.map(|g| g.id.clone())
|
||||
}
|
||||
|
||||
/// Erweitert eine Treffer-Auswahl um die im Kontext sichtbaren Gruppen (deren transitive
|
||||
/// Mitgliedschaft ersetzt die getroffene id); dazu die getroffenen Gruppen-ids in Reihenfolge.
|
||||
pub fn expand_to_groups(p: &Project, raw: &Membership, path: &[String]) -> (Membership, Vec<String>) {
|
||||
let mut expanded = Membership::default();
|
||||
let mut group_ids: Vec<String> = Vec::new();
|
||||
for k in KINDS {
|
||||
for id in raw.list(k).expect("Art") {
|
||||
match containing_group_id(p, k, id, path) {
|
||||
Some(gid) => {
|
||||
let m = transitive_membership(p, &gid);
|
||||
if !group_ids.contains(&gid) {
|
||||
group_ids.push(gid);
|
||||
}
|
||||
expanded.merge(&m);
|
||||
}
|
||||
None => {
|
||||
let mut one = Membership::default();
|
||||
one.list_mut(k).expect("Art").push(id.clone());
|
||||
expanded.merge(&one);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(expanded, group_ids)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn project(groups: serde_json::Value) -> Project {
|
||||
serde_json::from_value(json!({"id":"p","name":"","lineStyles":[],"hatches":[],"components":[],"wallTypes":[],"drawingLevels":[],"layers":[],"walls":[],"drawings2d":[],"groups":groups})).unwrap()
|
||||
}
|
||||
fn g(id: &str, walls: &[&str], subs: &[&str]) -> serde_json::Value {
|
||||
json!({"id":id,"wallIds":walls,"drawingIds":[],"ceilingIds":[],"roomIds":[],"stairIds":[],"columnIds":[],"roofIds":[],"openingIds":[],"groupIds":subs})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transitiv_mit_zyklus_und_doppelungen() {
|
||||
let p = project(json!([g("a", &["w1", "w1"], &[]), g("b", &["w2", "w1"], &["a", "c"]), g("c", &["w3"], &["b"])]));
|
||||
// Ohne Untergruppen bleiben Doppelungen (wie TS: Kopie ohne Vereinigung).
|
||||
assert_eq!(transitive_membership(&p, "a").wall_ids, ["w1", "w1"]);
|
||||
// Mit Untergruppen vereinigt; Zyklus b → c → b endet.
|
||||
assert_eq!(transitive_membership(&p, "b").wall_ids, ["w2", "w1", "w3"]);
|
||||
assert_eq!(transitive_membership(&p, "x"), Membership::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sichtbare_gruppe_und_erweitern() {
|
||||
let p = project(json!([g("inner", &["w1"], &[]), g("outer", &["w2"], &["inner"]), g("solo", &["w9"], &[])]));
|
||||
assert_eq!(containing_group_id(&p, "wallIds", "w1", &[]), Some("outer".into()));
|
||||
assert_eq!(containing_group_id(&p, "wallIds", "w1", &["outer".into()]), Some("inner".into()));
|
||||
assert_eq!(containing_group_id(&p, "wallIds", "w2", &["outer".into()]), None);
|
||||
assert_eq!(containing_group_id(&p, "wallIds", "w5", &[]), None);
|
||||
assert_eq!(containing_group_id(&p, "nope", "w1", &[]), None);
|
||||
let raw = Membership { wall_ids: vec!["w5".into(), "w1".into(), "w2".into()], ..Default::default() };
|
||||
let (e, ids) = expand_to_groups(&p, &raw, &[]);
|
||||
assert_eq!(e.wall_ids, ["w5", "w2", "w1"]);
|
||||
assert_eq!(ids, ["outer"]);
|
||||
}
|
||||
}
|
||||
@@ -71,6 +71,7 @@ pub mod ifc_quantities;
|
||||
pub mod ifc_stairs;
|
||||
pub mod ifc_data;
|
||||
pub mod mesh_data;
|
||||
pub mod groups;
|
||||
|
||||
#[cfg(feature = "web")]
|
||||
mod web;
|
||||
@@ -37,7 +37,7 @@ fn js_string(v: &Value) -> String {
|
||||
match v {
|
||||
Value::Null => "null".into(),
|
||||
Value::Bool(b) => b.to_string(),
|
||||
Value::Number(n) => n.as_f64().map_or(n.to_string(), |f| if f.fract() == 0.0 && f.abs() < 1e21 { format!("{}", f as i64) } else { f.to_string() }),
|
||||
Value::Number(n) => n.as_f64().map_or(n.to_string(), crate::js_fmt::js_number),
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Array(a) => a.iter().map(|x| if x.is_null() { String::new() } else { js_string(x) }).collect::<Vec<_>>().join(","),
|
||||
Value::Object(_) => "[object Object]".into(),
|
||||
@@ -100,7 +100,10 @@ fn migrate_doors(mut raw: Map<String, Value>) -> Map<String, Value> {
|
||||
/// eine Ersatz-ID, falls die Datei keine trägt.
|
||||
pub fn parse_project_file(text: &str, now_ms: f64) -> Parsed {
|
||||
match serde_json::from_str::<Value>(text) {
|
||||
Ok(raw) => parse_project_object(raw, now_ms),
|
||||
Ok(mut raw) => {
|
||||
js_key_order(&mut raw);
|
||||
parse_project_object(raw, now_ms)
|
||||
}
|
||||
Err(e) => Parsed::Err(format!("Die Datei ist kein gültiges JSON ({e}).")),
|
||||
}
|
||||
}
|
||||
@@ -113,15 +116,18 @@ pub fn parse_project_object(raw: Value, now_ms: f64) -> Parsed {
|
||||
let mut version: u64 = 0;
|
||||
if let Some(v) = obj.get("formatVersion") {
|
||||
match v.as_f64() {
|
||||
Some(f) if f.fract() == 0.0 && f >= 0.0 => version = f as u64,
|
||||
Some(f) if f.fract() == 0.0 && f >= 0.0 => {
|
||||
if f > PROJECT_FORMAT_VERSION as f64 {
|
||||
return Parsed::Err(format!(
|
||||
"Die Datei wurde mit einer neueren Dossier-Version gespeichert (Format {}, dieses Programm kennt bis {PROJECT_FORMAT_VERSION}). Bitte Dossier aktualisieren.",
|
||||
crate::js_fmt::js_number(f)
|
||||
));
|
||||
}
|
||||
version = f as u64;
|
||||
}
|
||||
_ => return Parsed::Err(format!("Ungültige Formatversion „{}\".", js_string(v))),
|
||||
}
|
||||
}
|
||||
if version > PROJECT_FORMAT_VERSION {
|
||||
return Parsed::Err(format!(
|
||||
"Die Datei wurde mit einer neueren Dossier-Version gespeichert (Format {version}, dieses Programm kennt bis {PROJECT_FORMAT_VERSION}). Bitte Dossier aktualisieren."
|
||||
));
|
||||
}
|
||||
for key in REQUIRED_ARRAYS {
|
||||
if !obj.get(key).is_some_and(Value::is_array) {
|
||||
return Parsed::Err(format!("Die Datei enthält kein Dossier-Projekt (Liste „{key}\" fehlt)."));
|
||||
@@ -175,16 +181,131 @@ fn to_base36(mut n: u64) -> String {
|
||||
String::from_utf8(digits).expect("ASCII")
|
||||
}
|
||||
|
||||
/// Serialisiert ein Projekt für die Datei: aktuelle Formatversion vorne, Einrückung 2.
|
||||
/// Serialisiert ein Projekt für die Datei: aktuelle Formatversion vorne, Einrückung 2 — Zeichen für
|
||||
/// Zeichen wie `JSON.stringify({ formatVersion, ...rest }, null, 2)` (Zahlen über [`JsFormatter`]).
|
||||
pub fn serialize_project(project: &Map<String, Value>) -> String {
|
||||
let mut out = Map::new();
|
||||
out.insert("formatVersion".into(), PROJECT_FORMAT_VERSION.into());
|
||||
for (k, v) in project {
|
||||
if k != "formatVersion" {
|
||||
out.insert(k.clone(), v.clone());
|
||||
to_js_json_pretty(&FileView(project))
|
||||
}
|
||||
|
||||
/// Das Projekt mit `formatVersion` vorn, ohne Kopie des Baums.
|
||||
struct FileView<'a>(&'a Map<String, Value>);
|
||||
|
||||
impl serde::Serialize for FileView<'_> {
|
||||
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
use serde::ser::SerializeMap;
|
||||
let n = self.0.len() + usize::from(!self.0.contains_key("formatVersion"));
|
||||
let mut m = s.serialize_map(Some(n))?;
|
||||
m.serialize_entry("formatVersion", &PROJECT_FORMAT_VERSION)?;
|
||||
for (k, v) in self.0 {
|
||||
if k != "formatVersion" {
|
||||
m.serialize_entry(k, v)?;
|
||||
}
|
||||
}
|
||||
m.end()
|
||||
}
|
||||
}
|
||||
|
||||
/// `JSON.stringify(v, null, 2)`: Einrückung 2, Zahlen wie JS `String(n)` (`0.000005` statt `5e-6`,
|
||||
/// `1e+21`, `-0` → `0`; ganze Zahlen über 2⁵³ so gerundet, wie JS sie liest).
|
||||
pub fn to_js_json_pretty<T: serde::Serialize + ?Sized>(v: &T) -> String {
|
||||
let mut buf = Vec::with_capacity(1 << 16);
|
||||
let mut ser = serde_json::Serializer::with_formatter(&mut buf, JsFormatter(serde_json::ser::PrettyFormatter::with_indent(b" ")));
|
||||
if v.serialize(&mut ser).is_err() {
|
||||
return String::new();
|
||||
}
|
||||
String::from_utf8(buf).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Formatierer mit den Zahlen von JS (`js_fmt::js_number`), sonst wie `PrettyFormatter`.
|
||||
struct JsFormatter<'a>(serde_json::ser::PrettyFormatter<'a>);
|
||||
|
||||
/// Ganze Zahlen ab hier liest JS nicht mehr exakt (2⁵³).
|
||||
const JS_SAFE: u64 = 1 << 53;
|
||||
|
||||
impl serde_json::ser::Formatter for JsFormatter<'_> {
|
||||
fn write_f64<W: ?Sized + std::io::Write>(&mut self, w: &mut W, value: f64) -> std::io::Result<()> {
|
||||
// JSON.stringify schreibt nicht-endliche Zahlen als null (kommen im Dokument nicht vor).
|
||||
if value == 0.0 {
|
||||
w.write_all(b"0")
|
||||
} else if (1e-6..1e21).contains(&value.abs()) {
|
||||
// Schneller Weg: Rusts `Display` schreibt hier dieselbe kürzeste Ziffernfolge ohne
|
||||
// Exponent wie JS (Test `zahlen_und_einrueckung_wie_json_stringify`, `js_number` als Gegenprobe).
|
||||
write!(w, "{value}")
|
||||
} else if value.is_finite() {
|
||||
w.write_all(crate::js_fmt::js_number(value).as_bytes())
|
||||
} else {
|
||||
w.write_all(b"null")
|
||||
}
|
||||
}
|
||||
serde_json::to_string_pretty(&Value::Object(out)).unwrap_or_default()
|
||||
fn write_u64<W: ?Sized + std::io::Write>(&mut self, w: &mut W, value: u64) -> std::io::Result<()> {
|
||||
if value > JS_SAFE {
|
||||
self.write_f64(w, value as f64)
|
||||
} else {
|
||||
w.write_all(value.to_string().as_bytes())
|
||||
}
|
||||
}
|
||||
fn write_i64<W: ?Sized + std::io::Write>(&mut self, w: &mut W, value: i64) -> std::io::Result<()> {
|
||||
if value.unsigned_abs() > JS_SAFE {
|
||||
self.write_f64(w, value as f64)
|
||||
} else {
|
||||
w.write_all(value.to_string().as_bytes())
|
||||
}
|
||||
}
|
||||
fn begin_array<W: ?Sized + std::io::Write>(&mut self, w: &mut W) -> std::io::Result<()> {
|
||||
self.0.begin_array(w)
|
||||
}
|
||||
fn end_array<W: ?Sized + std::io::Write>(&mut self, w: &mut W) -> std::io::Result<()> {
|
||||
self.0.end_array(w)
|
||||
}
|
||||
fn begin_array_value<W: ?Sized + std::io::Write>(&mut self, w: &mut W, first: bool) -> std::io::Result<()> {
|
||||
self.0.begin_array_value(w, first)
|
||||
}
|
||||
fn end_array_value<W: ?Sized + std::io::Write>(&mut self, w: &mut W) -> std::io::Result<()> {
|
||||
self.0.end_array_value(w)
|
||||
}
|
||||
fn begin_object<W: ?Sized + std::io::Write>(&mut self, w: &mut W) -> std::io::Result<()> {
|
||||
self.0.begin_object(w)
|
||||
}
|
||||
fn end_object<W: ?Sized + std::io::Write>(&mut self, w: &mut W) -> std::io::Result<()> {
|
||||
self.0.end_object(w)
|
||||
}
|
||||
fn begin_object_key<W: ?Sized + std::io::Write>(&mut self, w: &mut W, first: bool) -> std::io::Result<()> {
|
||||
self.0.begin_object_key(w, first)
|
||||
}
|
||||
fn begin_object_value<W: ?Sized + std::io::Write>(&mut self, w: &mut W) -> std::io::Result<()> {
|
||||
self.0.begin_object_value(w)
|
||||
}
|
||||
fn end_object_value<W: ?Sized + std::io::Write>(&mut self, w: &mut W) -> std::io::Result<()> {
|
||||
self.0.end_object_value(w)
|
||||
}
|
||||
}
|
||||
|
||||
/// Ob `k` ein Array-Index-Schlüssel ist (`"0"`, `"12"` …, < 2³² − 1): solche Schlüssel stellt ein
|
||||
/// JS-Objekt vor alle anderen, aufsteigend nach Zahl.
|
||||
fn index_key(k: &str) -> Option<u32> {
|
||||
if k.is_empty() || k.len() > 10 || (k.len() > 1 && k.starts_with('0')) || !k.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
k.parse::<u64>().ok().filter(|&n| n < u32::MAX as u64).map(|n| n as u32)
|
||||
}
|
||||
|
||||
/// Bringt die Schlüssel aller Objekte in die Reihenfolge, die `JSON.parse` in JS liefert
|
||||
/// (Array-Index-Schlüssel zuerst, aufsteigend; sonst Einfüge-Reihenfolge). So schreibt das Speichern
|
||||
/// eine geladene Datei genau wie die frühere TS-Fassung (`JSON.parse` → `JSON.stringify`).
|
||||
pub fn js_key_order(v: &mut Value) {
|
||||
match v {
|
||||
Value::Array(a) => a.iter_mut().for_each(js_key_order),
|
||||
Value::Object(m) => {
|
||||
m.values_mut().for_each(js_key_order);
|
||||
if m.keys().any(|k| index_key(k).is_some()) {
|
||||
let mut entries: Vec<(String, Value)> = std::mem::take(m).into_iter().collect();
|
||||
// Stabil: Index-Schlüssel nach Zahl vorn, die übrigen in ihrer Reihenfolge dahinter.
|
||||
entries.sort_by_key(|(k, _)| index_key(k).map_or((1, 0), |n| (0, n)));
|
||||
m.extend(entries);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -220,6 +341,13 @@ mod tests {
|
||||
let mut v = minimal();
|
||||
v["formatVersion"] = json!(99);
|
||||
assert!(matches!(parse_project_object(v, 0.0), Parsed::Err(m) if m.contains("neueren")));
|
||||
// Meldung mit der Zahl wie JS `String(n)`.
|
||||
let mut v = minimal();
|
||||
v["formatVersion"] = json!(1e21);
|
||||
assert!(matches!(parse_project_object(v, 0.0), Parsed::Err(m) if m.contains("(Format 1e+21,")));
|
||||
let mut v = minimal();
|
||||
v["formatVersion"] = json!(1e-7);
|
||||
assert_eq!(parse_project_object(v, 0.0), Parsed::Err("Ungültige Formatversion „1e-7\".".into()));
|
||||
let mut v = minimal();
|
||||
v["formatVersion"] = json!("x");
|
||||
assert_eq!(parse_project_object(v, 0.0), Parsed::Err("Ungültige Formatversion „x\".".into()));
|
||||
@@ -262,6 +390,42 @@ mod tests {
|
||||
assert_eq!(project["id"], "project-105");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zahlen_und_einrueckung_wie_json_stringify() {
|
||||
let text = r#"{"a":[0.000005,1.5e-7,1e21,123456789012345680000,9007199254740993,-9007199254740993,1.0,-0.0,3,[],{}],"b":{"c":"x\u0001\n
é\u007f"}}"#;
|
||||
let v: Value = serde_json::from_str(text).unwrap();
|
||||
// Erwartet = JSON.stringify(JSON.parse(text), null, 2) in Node.
|
||||
let want = "{\n \"a\": [\n 0.000005,\n 1.5e-7,\n 1e+21,\n 123456789012345680000,\n 9007199254740992,\n -9007199254740992,\n 1,\n 0,\n 3,\n [],\n {}\n ],\n \"b\": {\n \"c\": \"x\\u0001\\n\u{2028}é\u{7f}\"\n }\n}";
|
||||
assert_eq!(to_js_json_pretty(&v), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schneller_zahlenweg_gleich_js_number() {
|
||||
let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
|
||||
for i in 0..200_000 {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 7;
|
||||
x ^= x << 17;
|
||||
// Zufällige Bitmuster und gerundete Werte über alle Grössenordnungen.
|
||||
let v = if i % 2 == 0 { f64::from_bits(x) } else { ((x % 2_000_001) as f64 - 1e6) * 10f64.powi((x % 40) as i32 - 20) };
|
||||
if !v.is_finite() {
|
||||
continue;
|
||||
}
|
||||
let s = to_js_json_pretty(&serde_json::json!(v));
|
||||
assert_eq!(s, crate::js_fmt::js_number(v), "{v:e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schluessel_reihenfolge_wie_js_objekt() {
|
||||
let mut v: Value = serde_json::from_str(r#"{"b":1,"21":2,"a":{"x":1,"10":2,"2":3,"01":4,"4294967295":5,"4294967294":6},"3":0}"#).unwrap();
|
||||
js_key_order(&mut v);
|
||||
let keys = |v: &Value| v.as_object().unwrap().keys().cloned().collect::<Vec<_>>();
|
||||
// Erwartet = Object.keys(JSON.parse(…)) in Node.
|
||||
assert_eq!(keys(&v), ["3", "21", "b", "a"]);
|
||||
assert_eq!(keys(&v["a"]), ["2", "10", "4294967294", "x", "01", "4294967295"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serialisierung_setzt_version_nach_vorn() {
|
||||
let Value::Object(m) = minimal() else { panic!() };
|
||||
|
||||
@@ -41,10 +41,31 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
|
||||
("pickGeometry", _) => json(&model3d::pick_geometry(p)?),
|
||||
("modelJson", _) => crate::model::to_value_typed_only(p).map(|v| v.to_string()).map_err(|e| e.to_string()),
|
||||
("model3dParts", 3) => json(&model3d::parts(p, args[0] != 0.0, args[1], args[2] != 0.0)?),
|
||||
// Gruppen ([K4] S3, `groups.rs`): `text` = Gruppen-id bzw. JSON der Argumente.
|
||||
("groupMembership", _) => json(&crate::groups::transitive_membership(p, text)),
|
||||
("containingGroup", _) => {
|
||||
let a: GroupArgs = serde_json::from_str(text).map_err(|e| format!("containingGroup: {e}"))?;
|
||||
json(&crate::groups::containing_group_id(p, &a.kind, &a.id, &a.path))
|
||||
}
|
||||
("expandToGroups", _) => {
|
||||
let a: GroupArgs = serde_json::from_str(text).map_err(|e| format!("expandToGroups: {e}"))?;
|
||||
let (expanded, group_ids) = crate::groups::expand_to_groups(p, &a.raw, &a.path);
|
||||
json(&serde_json::json!({"expanded": expanded, "groupIds": group_ids}))
|
||||
}
|
||||
_ => Err(format!("Unbekannte Abfrage: {name}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Argumente der Gruppen-Abfragen (`containingGroup`: kind/id/path, `expandToGroups`: raw/path).
|
||||
#[derive(serde::Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct GroupArgs {
|
||||
kind: String,
|
||||
id: String,
|
||||
path: Vec<String>,
|
||||
raw: crate::groups::Membership,
|
||||
}
|
||||
|
||||
/// Abfragen mit binärer Antwort (Plan-Puffer v2, s. `plan_buf.rs`).
|
||||
pub fn run_bin(p: &Project, name: &str, args: &[f64], text: &str) -> Result<Vec<u8>, String> {
|
||||
match (name, args.len()) {
|
||||
|
||||
@@ -31,6 +31,28 @@ pub fn doc_open(json: &str) -> u32 {
|
||||
})
|
||||
}
|
||||
|
||||
/// Projektdatei (Text) einlesen, migrieren, prüfen und ins Dokument laden ([K4] S4: Öffnen, Vorlage,
|
||||
/// Wiederherstellen); der Verlauf wird geleert. Antwort als JSON:
|
||||
/// `{"ok":true,"warnings":[…],"migratedFrom":null|n}` oder `{"ok":false,"error":"…"}` (Dokument unverändert).
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_load_file(h: u32, text: &str, now_ms: f64) -> String {
|
||||
let now = if now_ms.is_finite() { now_ms } else { 0.0 };
|
||||
let v = match with_doc(h, |d| d.load_file(text, now)) {
|
||||
Some(Ok((warnings, migrated_from))) => serde_json::json!({"ok": true, "warnings": warnings, "migratedFrom": migrated_from}),
|
||||
Some(Err(error)) => serde_json::json!({"ok": false, "error": error}),
|
||||
None => serde_json::json!({"ok": false, "error": "Dokument nicht offen"}),
|
||||
};
|
||||
v.to_string()
|
||||
}
|
||||
|
||||
/// Projekt-JSON (ein Objekt, schon im aktuellen Format) ins Dokument laden (Neu, Musterhaus, Abgleich
|
||||
/// nach einer Änderung vorbei an den Ops); der Verlauf wird geleert. `false` bei kaputtem JSON (unverändert).
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_load_json(h: u32, json: &str) -> bool {
|
||||
let Ok(Value::Object(root)) = serde_json::from_str::<Value>(json) else { return false };
|
||||
with_doc(h, |d| d.load(root)).is_some()
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_close(h: u32) {
|
||||
DOCS.with(|d| {
|
||||
|
||||
@@ -1,20 +1,8 @@
|
||||
//! Bindungen des Projektdatei-Formats (`crate::project_format`).
|
||||
//! Bindungen des Projektdatei-Formats (`crate::project_format`). Laden/Speichern laufen über das
|
||||
//! Dokument (`doc_load_file`, `doc_serialize` in `web/document.rs`).
|
||||
|
||||
use crate::project_format::{parse_project_file, Parsed};
|
||||
use serde_json::{json, Value};
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
/// Liest eine Projektdatei (Text). Antwort als JSON:
|
||||
/// `{"ok":true,"project":{…},"warnings":[…],"migratedFrom":null|n}` oder `{"ok":false,"error":"…"}`.
|
||||
#[wasm_bindgen]
|
||||
pub fn project_parse(text: &str, now_ms: f64) -> String {
|
||||
let v: Value = match parse_project_file(text, now_ms) {
|
||||
Parsed::Ok { project, warnings, migrated_from } => json!({"ok": true, "project": project, "warnings": warnings, "migratedFrom": migrated_from}),
|
||||
Parsed::Err(error) => json!({"ok": false, "error": error}),
|
||||
};
|
||||
v.to_string()
|
||||
}
|
||||
|
||||
/// Aktuelle Version des Dateiformats.
|
||||
#[wasm_bindgen]
|
||||
pub fn project_format_version() -> u32 {
|
||||
|
||||
+19
-25
@@ -36,7 +36,7 @@ import { activePenSet, resolvePenColor, resolvePenWeight } from "./model/penSets
|
||||
import { PenColorField } from "./ui/PenColorField";
|
||||
import { generatePlan, computeKennzahlen, checkRoomProgram } from "./core";
|
||||
import { programStatusLabel } from "./panels/KennzahlenSection";
|
||||
import type { CategoryDisplayResolver } from "./core";
|
||||
import type { CategoryDisplayResolver, ProjectMutation } from "./core";
|
||||
import { sectionPlaneFromLevel, sectionUAxisModel } from "./core";
|
||||
import { roofBaseElevation, roofGeometry } from "./core";
|
||||
import { setDxfImportTrigger } from "./io/dxfImportHook";
|
||||
@@ -156,8 +156,8 @@ import { useGripEditing } from "./state/useGripEditing";
|
||||
import { usePanelHostBase } from "./state/usePanelHostBase";
|
||||
import { useDockDragState } from "./state/useDockDragState";
|
||||
import { useMouseSelectionHandlers } from "./state/useMouseSelectionHandlers";
|
||||
import { activeGroupOps, addNewElementsToActiveGroup, containingGroupId, EMPTY_MEMBERSHIP } from "./state/groupActions";
|
||||
import { addItems, fieldOps, isOpsMutation, opsMutation, patchItem, patchItems, removeItems, replaceItem, replaceWithMany, setFieldIfChanged } from "./core";
|
||||
import { activeGroupOps, containingGroupId, EMPTY_MEMBERSHIP } from "./state/groupActions";
|
||||
import { addItems, fieldOps, opsMutation, patchItem, patchItems, removeItems, replaceItem, replaceWithMany, setFieldIfChanged } from "./core";
|
||||
import type { GroupMembership, MemberKind } from "./state/groupActions";
|
||||
import { isLocked, lockMembersOps } from "./state/objectLock";
|
||||
import { useProjectFileActions } from "./state/useProjectFileActions";
|
||||
@@ -666,7 +666,7 @@ export default function App() {
|
||||
|
||||
// Wendet ein ToolResult an: Draft (+ Snap-Marker) zeigen, ggf. committen/abschließen.
|
||||
const applyToolResult = (
|
||||
res: { draft: ToolDraft | null; commit?: (p: Project) => Project; done?: boolean },
|
||||
res: { draft: ToolDraft | null; commit?: ProjectMutation; done?: boolean },
|
||||
snapResult: ReturnType<typeof snapFor>,
|
||||
) => {
|
||||
if (res.draft) setDraft({ ...res.draft, snap: snapResult });
|
||||
@@ -937,23 +937,17 @@ export default function App() {
|
||||
setDraft: (d) => cmdLatest.current.setDraft(d),
|
||||
// Zeichnet man WÄHREND man eine Gruppe betreten hat (Isolation), wird
|
||||
// das neue Element automatisch Mitglied dieser Gruppe (Nutzer-Wunsch:
|
||||
// „wenn man etwas neu zeichnet ... zeichnet man in der Gruppe") — s.
|
||||
// state/groupActions.ts::addNewElementsToActiveGroup (Diff vor/nach
|
||||
// Commit über alle Elementarten, additiv zur eigentlichen Mutation).
|
||||
// [K4] S3: Befehle mit mitgeführten Ops (`opsMutation`) gehen ohne Projekt-Differenz an den
|
||||
// Kern; die Gruppen-Zuordnung kommt dann als weitere Ops dazu (`activeGroupOps`).
|
||||
// „wenn man etwas neu zeichnet ... zeichnet man in der Gruppe"). [K4] S3:
|
||||
// Befehle tragen ihre Ops mit (`opsMutation`); die Gruppen-Zuordnung kommt
|
||||
// als weitere Ops dazu (`activeGroupOps`).
|
||||
commit: (mutate) => {
|
||||
const groupPath = cmdLatest.current.groupPath;
|
||||
if (isOpsMutation(mutate)) {
|
||||
cmdLatest.current.setProject(
|
||||
opsMutation((p) => {
|
||||
const ops = mutate.toOps(p);
|
||||
return [...ops, ...activeGroupOps(p, ops, groupPath)];
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
cmdLatest.current.setProject((p) => addNewElementsToActiveGroup(p, mutate(p), groupPath));
|
||||
}
|
||||
cmdLatest.current.setProject(
|
||||
opsMutation((p) => {
|
||||
const ops = mutate.toOps(p);
|
||||
return [...ops, ...activeGroupOps(p, ops, groupPath)];
|
||||
}),
|
||||
);
|
||||
},
|
||||
isFloor: () => cmdLatest.current.activeLevel.kind === "floor",
|
||||
// Frisch über `text`/`textbox` erzeugtes Element sofort inline editieren
|
||||
@@ -1711,7 +1705,7 @@ export default function App() {
|
||||
} = useProjectActions(applyChange, notify, planViewRef);
|
||||
|
||||
// IFC-Import: erst die Wahl Mesh/Bauteile (`IfcImportDialog`), dann [B3] Kontext-Meshes
|
||||
// (`io/ifcImport.ts`) oder [B4] echte Bauteile (`io/ifcElements.ts`, übernommen über setProject).
|
||||
// (`io/ifcImport.ts`) oder [B4] echte Bauteile (`io/ifcElements.ts`, übernommen als Ops).
|
||||
const [pendingIfc, setPendingIfc] = useState<File | null>(null);
|
||||
const importIfcFile = (f: File) => setPendingIfc(f);
|
||||
const runIfcImport = (f: File, mode: IfcImportMode) => {
|
||||
@@ -1722,12 +1716,13 @@ export default function App() {
|
||||
.then(({ products, report, elements }) => {
|
||||
let summary: ReturnType<typeof ifcElementsToProject>["summary"] | null = null;
|
||||
let bounds: { x: number; y: number }[] = [];
|
||||
setProject((p) => {
|
||||
// Als Ops in einem Schritt ([K4] S3): ein IFC-Import = ein Undo-Schritt.
|
||||
applyChange((p) => {
|
||||
const r = ifcElementsToProject(p, products, elements, { fileName: f.name, geoOrigin: projectGeoOrigin(p) });
|
||||
summary = r.summary;
|
||||
const added = new Set(p.walls.map((w) => w.id));
|
||||
bounds = r.project.walls.filter((w) => !added.has(w.id)).flatMap((w) => [w.start, w.end]);
|
||||
return r.project;
|
||||
return r.ops;
|
||||
});
|
||||
if (bounds.length) planViewRef.current?.fitBounds(bounds);
|
||||
if (summary) {
|
||||
@@ -1913,7 +1908,7 @@ export default function App() {
|
||||
runImport,
|
||||
} = useProjectFileActions(
|
||||
project,
|
||||
setProject,
|
||||
applyChange,
|
||||
setImportState,
|
||||
setExportSaveFormat,
|
||||
activeCategoryCode,
|
||||
@@ -3124,10 +3119,9 @@ export default function App() {
|
||||
|
||||
// „Bild einfügen" (Werkzeug „image") — siehe state/useImportHandling.ts.
|
||||
const { onImageOrPdfFileChosen } = useImageImportHandling({
|
||||
project,
|
||||
activeLevelId: activeLevel.id,
|
||||
activeCategoryCode,
|
||||
setProject,
|
||||
applyChange,
|
||||
notify,
|
||||
setSelectedDrawingId,
|
||||
setSelectedWallIds,
|
||||
|
||||
+22
-23
@@ -94,8 +94,10 @@ import {
|
||||
distinctImportLayers,
|
||||
emptyProject,
|
||||
generateElevationPlan,
|
||||
diffToOps,
|
||||
applyOps,
|
||||
addItems,
|
||||
fieldOps,
|
||||
patchItem,
|
||||
generatePlan,
|
||||
generateSectionPlan,
|
||||
planToRenderScene,
|
||||
@@ -110,7 +112,7 @@ import {
|
||||
validateProject,
|
||||
sampleProject,
|
||||
} from "../core";
|
||||
import type { Project } from "../core";
|
||||
import type { CoreOp, Project } from "../core";
|
||||
import { serveStdio } from "./mcp";
|
||||
|
||||
type Args = { positional: string[]; flags: Map<string, string>; cmds: string[] };
|
||||
@@ -396,7 +398,11 @@ async function importAny(path: string, args: Args): Promise<Project> {
|
||||
...contoursToDrawings(parsed.contours, level.id, "byLayer", fallback, toCode, (l) => parsed.layerFillColors?.[l]),
|
||||
...textsToDrawings(parsed.texts ?? [], level.id, "byLayer", fallback, toCode),
|
||||
];
|
||||
return applyOps(base, diffToOps(base, { ...base, layers, drawings2d: drawings, context: [...parsed.meshes] }));
|
||||
return applyOps(base, [
|
||||
...fieldOps(base, "layers", layers),
|
||||
...fieldOps(base, "drawings2d", drawings),
|
||||
...fieldOps(base, "context", [...parsed.meshes]),
|
||||
]);
|
||||
}
|
||||
return fail(`Eingabeformat nicht unterstützt: .${ext} (obp, dxf, dwg, ifc, pdf, obj, stl, gltf, glb, ply)`);
|
||||
}
|
||||
@@ -436,6 +442,14 @@ async function convert(input: string | undefined, output: string | undefined, ar
|
||||
return code === 0 ? runCmds(project, input, args) : code;
|
||||
}
|
||||
|
||||
/** Ops: Kontext-Meshes anhängen und — wie in der App (siteSlice) — fehlende Kontext-Kategorien als Ebene ergänzen. */
|
||||
function contextOps(project: Project, meshes: NonNullable<Project["context"]>): CoreOp[] {
|
||||
return [
|
||||
...(project.context ? addItems("context", meshes) : fieldOps(project, "context", meshes)),
|
||||
...fieldOps(project, "layers", ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : [])))),
|
||||
];
|
||||
}
|
||||
|
||||
/** IFC in ein Projekt übernehmen (Kontext-Meshes, mit `--elements` als Bauteile); `report` = Bericht für `import-ifc`. */
|
||||
async function ifcInto(project: Project, bytes: Uint8Array, fileName: string, args: Args): Promise<{ next: Project; report: unknown }> {
|
||||
const group = args.flags.get("group");
|
||||
@@ -444,7 +458,7 @@ async function ifcInto(project: Project, bytes: Uint8Array, fileName: string, ar
|
||||
const { products, report, elements } = await readIfcElements(bytes);
|
||||
const r = ifcElementsToProject(project, products, elements, { fileName, geoOrigin: projectGeoOrigin(project), group: grouping });
|
||||
return {
|
||||
next: applyOps(project, diffToOps(project, r.project)),
|
||||
next: r.project,
|
||||
report: { ...report, products: undefined, elements: r.summary, kept: elements.kept },
|
||||
};
|
||||
}
|
||||
@@ -453,15 +467,7 @@ async function ifcInto(project: Project, bytes: Uint8Array, fileName: string, ar
|
||||
const byClass: Record<string, number> = {};
|
||||
for (const p of products) byClass[p.ifcClass] = (byClass[p.ifcClass] ?? 0) + 1;
|
||||
const triangles = products.reduce((s, p) => s + p.indices.length / 3, 0);
|
||||
const next = applyOps(
|
||||
project,
|
||||
diffToOps(project, {
|
||||
...project,
|
||||
context: [...(project.context ?? []), ...meshes],
|
||||
// Wie in der App (siteSlice): fehlende Kontext-Kategorie als Ebene ergänzen.
|
||||
layers: ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : []))),
|
||||
}),
|
||||
);
|
||||
const next = applyOps(project, contextOps(project, meshes));
|
||||
return { next, report: { ...report, byClass, triangles, contextObjects: meshes.length } };
|
||||
}
|
||||
|
||||
@@ -508,14 +514,7 @@ async function meshInto(project: Project, bytes: Uint8Array, path: string, args:
|
||||
return fail(`${path}: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
const meshes = meshObjectsToImportedMeshes(read.objects, fileName, { placement, geoOrigin: projectGeoOrigin(project) });
|
||||
const next = applyOps(
|
||||
project,
|
||||
diffToOps(project, {
|
||||
...project,
|
||||
context: [...(project.context ?? []), ...meshes],
|
||||
layers: ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : []))),
|
||||
}),
|
||||
);
|
||||
const next = applyOps(project, contextOps(project, meshes));
|
||||
return { next, report: { ...read.report, contextObjects: meshes.length } };
|
||||
}
|
||||
|
||||
@@ -796,8 +795,8 @@ async function execute(project: Project, file: string, command: string, rest: st
|
||||
if (sec) await time("computeSection", () => computeSection(project, sec), Math.max(3, runs / 2));
|
||||
if (elev) await time("generateElevationPlan", () => generateElevationPlan(project, elev), Math.max(3, runs / 2));
|
||||
if (project.walls.length) {
|
||||
const moved = { ...project, walls: [{ ...project.walls[0], height: (project.walls[0].height ?? 2.6) + 0.1 }, ...project.walls.slice(1)] };
|
||||
await time("Op: diff+apply (1 Wand)", () => applyOps(project, diffToOps(project, moved)), runs * 20);
|
||||
const w0 = project.walls[0];
|
||||
await time("Op: patch+apply (1 Wand)", () => applyOps(project, patchItem(project, "walls", w0.id, { height: (w0.height ?? 2.6) + 0.1 })), runs * 20);
|
||||
}
|
||||
for (const [n, ms] of rows) process.stdout.write(`${n.padEnd(28)} ${ms.toFixed(2).padStart(9)} ms\n`);
|
||||
return 0;
|
||||
|
||||
@@ -7,7 +7,7 @@ import type { Command, CommandContext, CmdInput } from "../types";
|
||||
import { explodeOps } from "../../editors/explode";
|
||||
import { translateOps, translateProject } from "../../model/geoRebase";
|
||||
import { applyOps } from "../../core/ops";
|
||||
import { isOpsMutation } from "../../core";
|
||||
import type { ProjectMutation } from "../../core";
|
||||
import { joinCommand } from "./join";
|
||||
import { defblockCommand } from "./defblock";
|
||||
import { terrainCommand } from "./terrain";
|
||||
@@ -45,13 +45,13 @@ function ctxOf(p: Project, ids: string[] = []): CommandContext {
|
||||
function commitOf(cmd: Command, p: Project, inputs: CmdInput[], ids: string[] = []): { out: Project; viaOps: boolean } {
|
||||
const ctx = ctxOf(p, ids);
|
||||
let st = cmd.init();
|
||||
let fn: ((p: Project) => Project) | undefined = cmd.autoRun?.(ctx).commit;
|
||||
let fn: ProjectMutation | undefined = cmd.autoRun?.(ctx).commit;
|
||||
for (const input of inputs) {
|
||||
const [ns, res] = cmd.onInput(st, input, ctx);
|
||||
st = ns;
|
||||
if (res.commit) fn = res.commit;
|
||||
}
|
||||
return { out: fn ? fn(p) : p, viaOps: fn ? isOpsMutation(fn) : true };
|
||||
return { out: fn ? fn(p) : p, viaOps: fn ? typeof fn.toOps === "function" : true };
|
||||
}
|
||||
|
||||
describe("Editier-Befehle: Ops", () => {
|
||||
|
||||
@@ -13,8 +13,9 @@
|
||||
// Zustandsänderung ruft sie `emit()` → React-Komponenten (CommandLine, App)
|
||||
// abonnieren via subscribe() und re-rendern.
|
||||
|
||||
import type { Project, Vec2 } from "../model/types";
|
||||
import type { Vec2 } from "../model/types";
|
||||
import type { SnapResult, ToolDraft } from "../tools/types";
|
||||
import type { ProjectMutation } from "../core";
|
||||
import { parseInput, resolvePoint } from "./parseInput";
|
||||
import { getCommand, resolveCommand, autocomplete } from "./registry";
|
||||
import type {
|
||||
@@ -49,7 +50,7 @@ export interface EngineHost {
|
||||
/** Vorschau setzen (oder löschen). */
|
||||
setDraft(draft: ToolDraft | null): void;
|
||||
/** Commit immutabel anwenden. */
|
||||
commit(mutate: (p: Project) => Project): void;
|
||||
commit(mutate: ProjectMutation): void;
|
||||
/** Ist die aktive Ebene ein Geschoss? (für floorOnly-Befehle). */
|
||||
isFloor(): boolean;
|
||||
/**
|
||||
|
||||
@@ -6,7 +6,8 @@ import { describe, expect, it } from "vitest";
|
||||
import { COMMANDS } from "./registry";
|
||||
import type { CmdInput, CommandContext } from "./types";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { applyOps, diffToOps, validateOps } from "../core/ops";
|
||||
import { applyOps, validateOps } from "../core/ops";
|
||||
import { projectDiffOps } from "../core/projectDiff.testutil";
|
||||
|
||||
const level = sampleProject.drawingLevels.find((l) => l.kind === "floor")!;
|
||||
const ctx: CommandContext = {
|
||||
@@ -76,7 +77,7 @@ describe("Befehle mit feindlichen Eingaben", () => {
|
||||
else [state, res] = cmd.onInput(state, hostile(opts), ctx);
|
||||
if (res?.commit) {
|
||||
const next = res.commit(sampleProject);
|
||||
const ops = diffToOps(sampleProject, next);
|
||||
const ops = projectDiffOps(sampleProject, next);
|
||||
const applied = applyOps(sampleProject, ops);
|
||||
validateOps(applied, ops, sampleProject); // darf melden, aber nicht werfen
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import type { Project, Vec2 } from "../model/types";
|
||||
import type { TranslationKey } from "../i18n";
|
||||
import type { DrawingLevel } from "../model/types";
|
||||
import type { SnapResult, ToolDraft } from "../tools/types";
|
||||
import type { ProjectMutation } from "../core";
|
||||
|
||||
export type { DraftShape, SnapResult, ToolDraft } from "../tools/types";
|
||||
|
||||
@@ -112,8 +113,8 @@ export interface CommandContext {
|
||||
export interface CommandResult {
|
||||
/** Neuer Vorschau-Zustand; null = nichts zu zeigen. */
|
||||
draft: ToolDraft | null;
|
||||
/** Bei Abschluss: immutable Mutation, die die Engine über setProject anwendet. */
|
||||
commit?: (p: Project) => Project;
|
||||
/** Bei Abschluss: Änderung mit mitgeführten Ops (`opsMutation`), die die Engine über setProject anwendet. */
|
||||
commit?: ProjectMutation;
|
||||
/** true → Befehl ist fertig und kehrt in den Ruhezustand zurück. */
|
||||
done?: boolean;
|
||||
/**
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
// Verlauf in Rust), Undo/Redo liefern Ops, mit denen die TS-Leseansicht nachgeführt wird.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ProjectDocument } from "./document";
|
||||
import { diffToOps, validateOps, validateProject } from "./ops";
|
||||
import { validateOps, validateProject } from "./ops";
|
||||
import { projectDiffOps } from "./projectDiff.testutil";
|
||||
import type { CoreOp } from "./ops";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Project, Wall } from "../model/types";
|
||||
@@ -41,7 +42,7 @@ describe("Undo/Redo im Kern-Dokument", () => {
|
||||
let steps = 0;
|
||||
for (let seed = 1; seed <= 1000; seed++) {
|
||||
const next = mutate(cur, seed);
|
||||
const ops = diffToOps(cur, next);
|
||||
const ops = projectDiffOps(cur, next);
|
||||
if (!ops.length) continue;
|
||||
const r = d.commit(cur, ops, undefined, seed * 1000);
|
||||
expect("project" in r, `seed ${seed}`).toBe(true);
|
||||
@@ -76,7 +77,7 @@ describe("Undo/Redo im Kern-Dokument", () => {
|
||||
for (let i = 0; i < 50; i++) {
|
||||
const w = cur.walls[0];
|
||||
const next = { ...cur, walls: [{ ...w, height: 3 + i / 100 }, ...cur.walls.slice(1)] };
|
||||
const r = d.commit(cur, diffToOps(cur, next), "drag:W", 1000 + i * 10);
|
||||
const r = d.commit(cur, projectDiffOps(cur, next), "drag:W", 1000 + i * 10);
|
||||
if ("project" in r) cur = r.project;
|
||||
}
|
||||
expect(d.historyState().undo).toBe(1);
|
||||
@@ -85,7 +86,7 @@ describe("Undo/Redo im Kern-Dokument", () => {
|
||||
expect(back.walls[1]).toBe(cur.walls[1]);
|
||||
// Nach Undo beginnt dieselbe Serie einen neuen Schritt.
|
||||
const again = d.redo(back)!;
|
||||
const r = d.commit(again, diffToOps(again, { ...again, name: "x" }), "drag:W", 1500);
|
||||
const r = d.commit(again, projectDiffOps(again, { ...again, name: "x" }), "drag:W", 1500);
|
||||
expect("project" in r).toBe(true);
|
||||
expect(d.historyState().undo).toBe(2);
|
||||
d.close();
|
||||
@@ -96,7 +97,7 @@ describe("Undo/Redo im Kern-Dokument", () => {
|
||||
let cur: Project = sampleProject;
|
||||
d.beginGroup();
|
||||
for (const name of ["a", "b", "c"]) {
|
||||
const r = d.commit(cur, diffToOps(cur, { ...cur, name }), undefined, 0);
|
||||
const r = d.commit(cur, projectDiffOps(cur, { ...cur, name }), undefined, 0);
|
||||
if ("project" in r) cur = r.project;
|
||||
}
|
||||
d.endGroup();
|
||||
@@ -109,13 +110,13 @@ describe("Undo/Redo im Kern-Dokument", () => {
|
||||
const d = new ProjectDocument(sampleProject);
|
||||
const w = sampleProject.walls[0];
|
||||
const nan = { ...sampleProject, walls: [{ ...w, height: NaN }, ...sampleProject.walls.slice(1)] };
|
||||
const r1 = d.commit(sampleProject, diffToOps(sampleProject, nan), undefined, 0);
|
||||
const r1 = d.commit(sampleProject, projectDiffOps(sampleProject, nan), undefined, 0);
|
||||
expect(r1).toEqual({ problems: [`„walls" ${w.id}: NaN ist nicht endlich.`] });
|
||||
const dup = { ...sampleProject, walls: [...sampleProject.walls, { ...w }] };
|
||||
const r2 = d.commit(sampleProject, diffToOps(sampleProject, dup), undefined, 0);
|
||||
const r2 = d.commit(sampleProject, projectDiffOps(sampleProject, dup), undefined, 0);
|
||||
expect(r2).toEqual({ problems: [`Doppelte ids in „walls".`] });
|
||||
const inf = { ...sampleProject, referenceElevationMasl: -Infinity } as Project;
|
||||
const r3 = d.commit(sampleProject, diffToOps(sampleProject, inf), undefined, 0);
|
||||
const r3 = d.commit(sampleProject, projectDiffOps(sampleProject, inf), undefined, 0);
|
||||
expect(r3).toEqual({ problems: [`Feld „referenceElevationMasl": -Infinity ist nicht endlich.`] });
|
||||
expect(d.historyState().undo).toBe(0);
|
||||
expect(JSON.parse(d.json())).toEqual(plain(sampleProject));
|
||||
@@ -156,7 +157,7 @@ describe("Undo/Redo im Kern-Dokument", () => {
|
||||
for (let i = 0; i < n; i++) {
|
||||
const k = (i * 7) % walls.length;
|
||||
const next = { ...cur, walls: cur.walls.map((w, j) => (j === k ? { ...w, height: 2 + i / 1000 } : w)) };
|
||||
const r = d.commit(cur, diffToOps(cur, next), undefined, i * 1000);
|
||||
const r = d.commit(cur, projectDiffOps(cur, next), undefined, i * 1000);
|
||||
if ("project" in r) cur = r.project;
|
||||
}
|
||||
const commitMs = (performance.now() - t) / n;
|
||||
|
||||
+65
-15
@@ -1,14 +1,19 @@
|
||||
// Projekt-Dokument im Rust-Kern ([K4], Stufe S1; S3: Prüfung und Undo/Redo im Kern, s. `commit`).
|
||||
// Spiegelt das TS-Projekt über Ops nach Rust (`document.rs`). Befehle liefern vorerst noch
|
||||
// Projekt → Projekt (`setProject` → `diffToOps`); Rust hält
|
||||
// den Stand, auf dem die Ableitungen später direkt rechnen, ohne dass TS das Projekt je Aufruf
|
||||
// flach neu sammeln muss. Bei jedem Widerspruch (abgelehnte Ops, Fehler) wird das Dokument aus dem
|
||||
// vollen Projekt neu geöffnet — der Spiegel heilt sich selbst.
|
||||
// Projekt-Dokument im Rust-Kern ([K4], Stufe S1; S3: Prüfung und Undo/Redo im Kern, s. `commit`;
|
||||
// S4: Laden/Speichern der Projektdatei, s. `loadFile`/`serialize`). Änderungen kommen als Ops
|
||||
// (`commit`), ein anderes Projekt als Ganzes (`load`, `loadFile` — leert den Verlauf). TS hält die
|
||||
// Leseansicht (`current`). Das gemeinsame Abfrage-Dokument (`documentFor`) folgt fremden Projekten
|
||||
// feldweise (`sync`); bei jedem Widerspruch wird es aus dem vollen Projekt neu geöffnet.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import { applyOps, diffToOps, opsToJson } from "./ops";
|
||||
import { applyOps, opsToJson } from "./ops";
|
||||
import type { CoreOp } from "./ops";
|
||||
import { fieldOps } from "./opsBuild";
|
||||
|
||||
/** Ergebnis des Ladens einer Projektdatei ({@link ProjectDocument.loadFile}). */
|
||||
export type LoadFileResult =
|
||||
| { ok: true; project: Project; warnings: string[]; migratedFrom: number | null }
|
||||
| { ok: false; error: string };
|
||||
|
||||
/** Abfragen des Kerns (`queries.rs`). */
|
||||
export type QueryName =
|
||||
@@ -38,7 +43,10 @@ export type QueryName =
|
||||
| "planDomains"
|
||||
| "ifcExportData"
|
||||
| "meshExportData"
|
||||
| "modelJson";
|
||||
| "modelJson"
|
||||
| "groupMembership"
|
||||
| "containingGroup"
|
||||
| "expandToGroups";
|
||||
|
||||
export class ProjectDocument {
|
||||
private handle = 0;
|
||||
@@ -63,10 +71,19 @@ export class ProjectDocument {
|
||||
else if (this.limits) core().doc_history_limits(this.handle, this.limits[0], this.limits[1]);
|
||||
}
|
||||
|
||||
/** Bringt das Dokument auf den Stand `next` (über die Differenz als Ops). */
|
||||
/**
|
||||
* Bringt das Abfrage-Dokument auf den Stand `next` (ohne Verlauf): nur die Felder, deren Referenz
|
||||
* sich geändert hat, je über {@link fieldOps} (Listen elementweise) — unveränderte Teile kosten
|
||||
* nichts. Kein Weg für Benutzer-Änderungen (die gehen als Ops über {@link commit}).
|
||||
*/
|
||||
sync(next: Project): void {
|
||||
if (next === this.mirror) return;
|
||||
const ops = diffToOps(this.mirror, next);
|
||||
const a = this.mirror as unknown as Record<string, unknown>;
|
||||
const b = next as unknown as Record<string, unknown>;
|
||||
const ops: CoreOp[] = [];
|
||||
for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
|
||||
if (a[key] !== b[key]) ops.push(...fieldOps(this.mirror, key as keyof Project, b[key] as never));
|
||||
}
|
||||
this.mirror = next;
|
||||
if (ops.length === 0) return;
|
||||
if (!this.handle) {
|
||||
@@ -106,7 +123,33 @@ export class ProjectDocument {
|
||||
return core().doc_query_bin(this.handle, name, Float64Array.from(args), text);
|
||||
}
|
||||
|
||||
/** Datei-Text des Projekts (Formatversion vorn, Einrückung 2). */
|
||||
/**
|
||||
* Projekt laden (Neu, Musterhaus, Abgleich nach einer Änderung vorbei an den Ops): ersetzt den
|
||||
* ganzen Inhalt im Kern und leert den Verlauf. `project` wird die Leseansicht (Identität bleibt).
|
||||
*/
|
||||
load(project: Project): void {
|
||||
this.mirror = project;
|
||||
if (!this.handle || !core().doc_load_json(this.handle, JSON.stringify(project))) this.reopen(project);
|
||||
}
|
||||
|
||||
/**
|
||||
* Projektdatei laden (Öffnen, Vorlage, Wiederherstellen; [K4] S4): der Kern liest den Text, migriert
|
||||
* ältere Formate, prüft und ergänzt (`project_format.rs`) und lädt das Ergebnis direkt ins Dokument
|
||||
* (Verlauf leer). Die Leseansicht kommt als JSON des Dokuments zurück. Bei Fehler bleibt alles, wie es war.
|
||||
*/
|
||||
loadFile(text: string, now = Date.now()): LoadFileResult {
|
||||
if (!this.handle) this.reopen({} as Project);
|
||||
if (!this.handle) return { ok: false, error: "Projekt-Dokument im Kern nicht offen." };
|
||||
const r = JSON.parse(core().doc_load_file(this.handle, text, now)) as
|
||||
| { ok: true; warnings: string[]; migratedFrom: number | null }
|
||||
| { ok: false; error: string };
|
||||
if (!r.ok) return r;
|
||||
const project = JSON.parse(core().doc_json(this.handle)) as Project;
|
||||
this.mirror = project;
|
||||
return { ok: true, project, warnings: r.warnings, migratedFrom: r.migratedFrom };
|
||||
}
|
||||
|
||||
/** Datei-Text des Projekts (Formatversion vorn, Einrückung 2, Zeichen für Zeichen wie `JSON.stringify`). */
|
||||
serialize(): string {
|
||||
return this.handle ? core().doc_serialize(this.handle) : "";
|
||||
}
|
||||
@@ -138,13 +181,11 @@ export class ProjectDocument {
|
||||
|
||||
/**
|
||||
* Stellt sicher, dass das Dokument `base` spiegelt. Wurde das Projekt vorbei an den Ops
|
||||
* geändert (Laden in Tests, fremder Stand), passt der Verlauf nicht mehr: er wird geleert.
|
||||
* geändert (fremder Stand), passt der Verlauf nicht mehr: `base` wird als Ganzes geladen.
|
||||
*/
|
||||
private ensure(base: Project): void {
|
||||
if (base === this.mirror && this.handle) return;
|
||||
this.sync(base);
|
||||
if (!this.handle) this.reopen(base);
|
||||
if (this.handle) core().doc_history_clear(this.handle);
|
||||
this.load(base);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -228,6 +269,15 @@ export class ProjectDocument {
|
||||
}
|
||||
|
||||
let shared: ProjectDocument | null = null;
|
||||
|
||||
/**
|
||||
* Das gemeinsame Abfrage-Dokument (ohne Verlauf), z. B. für das CLI: eine dort geladene Datei
|
||||
* ({@link ProjectDocument.loadFile}) ist sofort das Dokument der Abfragen auf ihrem Projekt.
|
||||
*/
|
||||
export function sharedDocument(): ProjectDocument {
|
||||
if (!shared) shared = new ProjectDocument({} as Project);
|
||||
return shared;
|
||||
}
|
||||
/** Dokument des Stores (mit Verlauf); Abfragen auf dessen aktuellem Projekt laufen direkt darüber. */
|
||||
let primary: ProjectDocument | null = null;
|
||||
|
||||
|
||||
+4
-2
@@ -19,7 +19,7 @@ export { exportProjectStep } from "../export/exportStep";
|
||||
export { planToSvgString } from "../export/planToSvgString";
|
||||
export { setWasmBytesProvider } from "../engine/wasmSource";
|
||||
export { initCore, coreReady } from "../engine/coreWasm";
|
||||
export { applyOps, diffToOps, validateProject, validateOps } from "./ops";
|
||||
export { applyOps, validateProject, validateOps } from "./ops";
|
||||
export type { CoreOp } from "./ops";
|
||||
export type { Project, DrawingLevel } from "../model/types";
|
||||
export { computeKennzahlen, checkRoomProgram, solidVolume } from "../analysis/kennzahlen";
|
||||
@@ -49,5 +49,7 @@ export { readPdfVectorPage, pdfPageToImport, pdfPageInfo, pdfMetersPerPt, isPdfF
|
||||
export type { PdfVectorPage, PdfVectorPath, PdfVectorText } from "../io/pdfVector";
|
||||
export { readMesh, meshObjectsToImportedMeshes, formatMeshReport, isMeshFile, MESH_UNITS, MESH_UNIT_SCALE } from "../io/meshImport";
|
||||
export type { MeshObject, MeshImportReport, MeshUnit, MeshUp, MeshPlacement } from "../io/meshImport";
|
||||
export { addItems, fieldOps, findItem, isOpsMutation, itemsOf, opsMutation, patchItem, patchItems, removeItems, replaceItem, replaceWithMany, setField, setFieldIfChanged } from "./opsBuild";
|
||||
export { addItems, fieldOps, findItem, itemsOf, opsMutation, patchItem, patchItems, removeItems, replaceItem, replaceWithMany, setField, setFieldIfChanged } from "./opsBuild";
|
||||
export type { EntityCollection, EntityOf, ProjectMutation } from "./opsBuild";
|
||||
export { EMPTY_MEMBERSHIP, containingGroupId, expandToGroups, isInsideActiveGroup, transitiveMembership } from "../model/groups";
|
||||
export type { GroupMembership, MemberKind } from "../model/groups";
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { applyOps, diffToOps, validateProject } from "./ops";
|
||||
import { applyOps, validateProject } from "./ops";
|
||||
import { projectDiffOps } from "./projectDiff.testutil";
|
||||
import type { CoreOp } from "./ops";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Project } from "../model/types";
|
||||
@@ -29,20 +30,20 @@ function mutate(p: Project, seed: number): Project {
|
||||
|
||||
describe("CoreOps", () => {
|
||||
it("keine Änderung: keine Ops", () => {
|
||||
expect(diffToOps(sampleProject, sampleProject)).toEqual([]);
|
||||
expect(projectDiffOps(sampleProject, sampleProject)).toEqual([]);
|
||||
});
|
||||
|
||||
it("Roundtrip: apply(JSON(diff)) ergibt das Zielprojekt, für viele zufällige Änderungen", () => {
|
||||
for (let seed = 1; seed <= 200; seed++) {
|
||||
const next = mutate(sampleProject, seed);
|
||||
const ops = roundtrip(diffToOps(sampleProject, next));
|
||||
const ops = roundtrip(projectDiffOps(sampleProject, next));
|
||||
expect(applyOps(sampleProject, ops)).toEqual(next);
|
||||
}
|
||||
});
|
||||
|
||||
it("unveränderte Elemente behalten ihre Objekt-Identität", () => {
|
||||
const next = { ...sampleProject, walls: [...sampleProject.walls, { ...sampleProject.walls[0], id: "x-neu" }] };
|
||||
const out = applyOps(sampleProject, diffToOps(sampleProject, next));
|
||||
const out = applyOps(sampleProject, projectDiffOps(sampleProject, next));
|
||||
expect(out.walls[0]).toBe(sampleProject.walls[0]);
|
||||
expect(out.walls).toHaveLength(sampleProject.walls.length + 1);
|
||||
});
|
||||
@@ -63,7 +64,7 @@ describe("CoreOps", () => {
|
||||
it("Feld entfernen und Listen ohne ids als ganzes Feld", () => {
|
||||
const withAnchor = { ...sampleProject, referenceElevationMasl: 400 } as Project;
|
||||
const next = { ...withAnchor, referenceElevationMasl: undefined } as Project;
|
||||
const ops = diffToOps(withAnchor, next);
|
||||
const ops = projectDiffOps(withAnchor, next);
|
||||
expect(ops).toEqual([{ kind: "setField", key: "referenceElevationMasl" }]);
|
||||
expect("referenceElevationMasl" in applyOps(withAnchor, ops)).toBe(false);
|
||||
});
|
||||
|
||||
+6
-77
@@ -2,16 +2,14 @@
|
||||
// lessons-bimcraft [6]/[8], Grundlage für [7] und [16]).
|
||||
//
|
||||
// Die interaktive Befehlslogik (Schritte, Prompts, Vorschau, Panels, Griffe) bleibt in der Hülle
|
||||
// und liefert weiterhin Projekt → Projekt-Funktionen. `setProject` übersetzt jede Änderung
|
||||
// über {@link diffToOps} in eine Folge von {@link CoreOp}s und wendet SIE mit {@link applyOps}
|
||||
// an — das Projekt ändert sich ausschliesslich durch Ops. Ops sind JSON-serialisierbar
|
||||
// (Undo-Verlauf [84], Makros [85], MCP [9], später ein Rust-Kern).
|
||||
// und beschreibt jede Änderung als Folge von {@link CoreOp}s (Bauhelfer `opsBuild.ts`) — das
|
||||
// Projekt ändert sich ausschliesslich durch Ops. Ops sind JSON-serialisierbar (Undo-Verlauf [84],
|
||||
// Makros [85], MCP [9]). Ein anderes Projekt als Ganzes lädt der Kern (`ProjectDocument.load`/`loadFile`).
|
||||
//
|
||||
// [K4] S3: Prüfung (`validateOps`/`validateProject`), Anwendung mit Verlauf und Undo/Redo liegen im
|
||||
// Rust-Kern (`src-tauri/core/src/ops.rs`, `document.rs`). Hier bleiben `diffToOps` (Adapter für die
|
||||
// Befehle, die noch Projekt → Projekt liefern) und `applyOps` als Nachführung der TS-Leseansicht:
|
||||
// TS wendet genau die Ops an, die der Kern angenommen oder für Undo/Redo geliefert hat —
|
||||
// unveränderte Elemente behalten so ihre Objekt-Identität (Caches in Plan/3D).
|
||||
// Rust-Kern (`src-tauri/core/src/ops.rs`, `document.rs`). Hier bleibt `applyOps` als Nachführung der
|
||||
// TS-Leseansicht: TS wendet genau die Ops an, die der Kern angenommen oder für Undo/Redo geliefert
|
||||
// hat — unveränderte Elemente behalten so ihre Objekt-Identität (Caches in Plan/3D).
|
||||
//
|
||||
// Granularität (bewusst grob, aber stabil):
|
||||
// • Listen aus Elementen mit `id` (walls, ceilings, drawings2d, …): `add` / `replace` / `remove`
|
||||
@@ -37,75 +35,6 @@ export type CoreOp =
|
||||
* das Feld neu eingefügt wird (vom Kern-Undo gesetzt, damit die Feld-Reihenfolge exakt zurückkommt). */
|
||||
| { kind: "setField"; key: string; value?: unknown; at?: number };
|
||||
|
||||
const isEntityList = (v: unknown): v is Entity[] =>
|
||||
Array.isArray(v) && v.length > 0 && v.every((x) => x !== null && typeof x === "object" && typeof (x as Entity).id === "string");
|
||||
|
||||
/** Ob `v` eine (auch leere) Liste ist, deren Elemente — falls vorhanden — alle `id`s tragen. */
|
||||
const isIdList = (v: unknown): v is Entity[] => Array.isArray(v) && (v.length === 0 || isEntityList(v));
|
||||
|
||||
/** Eindeutige ids? (Voraussetzung für die Element-Ops.) */
|
||||
function uniqueIds(list: Entity[]): boolean {
|
||||
const seen = new Set<string>();
|
||||
for (const e of list) {
|
||||
if (seen.has(e.id)) return false;
|
||||
seen.add(e.id);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Berechnet die Ops, die `prev` in `next` überführen. `applyOps(prev, diffToOps(prev, next))`
|
||||
* ist inhaltlich gleich `next` (Test), Elemente aus `next` behalten ihre Identität.
|
||||
*/
|
||||
export function diffToOps(prev: Project, next: Project): CoreOp[] {
|
||||
if (prev === next) return [];
|
||||
const ops: CoreOp[] = [];
|
||||
const a = prev as unknown as Record<string, unknown>;
|
||||
const b = next as unknown as Record<string, unknown>;
|
||||
const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
|
||||
for (const key of keys) {
|
||||
const va = a[key];
|
||||
const vb = b[key];
|
||||
if (va === vb) continue;
|
||||
if (isIdList(va) && isIdList(vb) && uniqueIds(va) && uniqueIds(vb)) {
|
||||
diffList(key, va, vb, ops);
|
||||
} else {
|
||||
ops.push(vb === undefined ? { kind: "setField", key } : { kind: "setField", key, value: vb });
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
function diffList(collection: string, va: Entity[], vb: Entity[], ops: CoreOp[]): void {
|
||||
const inB = new Set(vb.map((e) => e.id));
|
||||
const mapA = new Map(va.map((e) => [e.id, e]));
|
||||
const removed = va.filter((e) => !inB.has(e.id)).map((e) => e.id);
|
||||
if (removed.length) ops.push({ kind: "remove", collection, ids: removed });
|
||||
// Geänderte Elemente (gleiche id, andere Referenz).
|
||||
for (const e of vb) {
|
||||
const old = mapA.get(e.id);
|
||||
if (old !== undefined && old !== e) ops.push({ kind: "replace", collection, entity: e });
|
||||
}
|
||||
// Reihenfolge der behaltenen Elemente in vb.
|
||||
const kept = va.filter((e) => inB.has(e.id)).map((e) => e.id);
|
||||
const keptSet = new Set(kept);
|
||||
const keptInB = vb.map((e) => e.id).filter((id) => keptSet.has(id));
|
||||
if (keptInB.some((id, idx) => id !== kept[idx])) ops.push({ kind: "reorder", collection, ids: keptInB });
|
||||
// Neue Elemente: zusammenhängende Läufe, von links nach rechts direkt an ihrer Zielposition
|
||||
// in `vb` eingefügt (frühere Läufe stehen dann schon, die Position stimmt).
|
||||
let i = 0;
|
||||
while (i < vb.length) {
|
||||
if (keptSet.has(vb[i].id)) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
const at = i;
|
||||
const run: Entity[] = [];
|
||||
while (i < vb.length && !keptSet.has(vb[i].id)) run.push(vb[i++]);
|
||||
ops.push({ kind: "add", collection, items: run, at });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wendet eine Op-Folge rein an (kein Zugriff auf Store/UI). Unberührte Listen und Elemente behalten
|
||||
* ihre Identität. Innerhalb eines Aufrufs wird jede Liste höchstens einmal kopiert und für
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
// Op-Bauhelfer ([K4] S3): Ergebnis = das bisherige Projekt → Projekt-Muster (`map`/`filter`/Anhängen)
|
||||
// über `diffToOps`, auf Zufallsprojekten; unveränderte Elemente bleiben identisch.
|
||||
// über `projectDiffOps`, auf Zufallsprojekten; unveränderte Elemente bleiben identisch.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { applyOps, diffToOps } from "./ops";
|
||||
import { applyOps } from "./ops";
|
||||
import { projectDiffOps } from "./projectDiff.testutil";
|
||||
import {
|
||||
addItems,
|
||||
fieldOps,
|
||||
findItem,
|
||||
isOpsMutation,
|
||||
opsMutation,
|
||||
patchItem,
|
||||
patchItems,
|
||||
@@ -32,7 +32,7 @@ function project(seed: number): Project {
|
||||
}
|
||||
|
||||
/** Alter Weg: Projekt → Projekt, dann über die Differenz. */
|
||||
const viaDiff = (p: Project, next: Project): Project => applyOps(p, diffToOps(p, next));
|
||||
const viaDiff = (p: Project, next: Project): Project => applyOps(p, projectDiffOps(p, next));
|
||||
|
||||
describe("Op-Bauhelfer", () => {
|
||||
it("patchItem = map über die Liste (Teilobjekt und Funktion), Zufall", () => {
|
||||
@@ -119,18 +119,16 @@ describe("Op-Bauhelfer", () => {
|
||||
const levels = p.drawingLevels.filter(() => r() < 0.8).map((z) => (r() < 0.3 ? { ...z, visible: !z.visible } : z));
|
||||
if (r() < 0.3) levels.reverse();
|
||||
const next = { ...p, drawingLevels: levels };
|
||||
expect(fieldOps(p, "drawingLevels", levels)).toEqual(diffToOps(p, next));
|
||||
expect(fieldOps(p, "drawingLevels", levels)).toEqual(projectDiffOps(p, next));
|
||||
expect(applyOps(p, fieldOps(p, "drawingLevels", levels))).toEqual(next);
|
||||
}
|
||||
expect(fieldOps(sampleProject, "layers", sampleProject.layers)).toEqual([]);
|
||||
expect(fieldOps(sampleProject, "geoAnchor", undefined)).toEqual(diffToOps(sampleProject, { ...sampleProject, geoAnchor: undefined }));
|
||||
expect(fieldOps(sampleProject, "geoAnchor", undefined)).toEqual(projectDiffOps(sampleProject, { ...sampleProject, geoAnchor: undefined }));
|
||||
});
|
||||
|
||||
it("opsMutation: wirkt wie eine Projekt → Projekt-Funktion und trägt die Ops mit", () => {
|
||||
const id = sampleProject.walls[0].id;
|
||||
const m = opsMutation((p) => patchItem(p, "walls", id, { height: 4.2 }));
|
||||
expect(isOpsMutation(m)).toBe(true);
|
||||
expect(isOpsMutation((p: Project) => p)).toBe(false);
|
||||
expect(m(sampleProject).walls[0].height).toBe(4.2);
|
||||
expect(m.toOps(sampleProject)).toHaveLength(1);
|
||||
});
|
||||
|
||||
+61
-16
@@ -1,6 +1,6 @@
|
||||
// Op-Bauhelfer ([K4] S3, zweite Etappe): Aktionen beschreiben ihre Änderung direkt als
|
||||
// {@link CoreOp}s statt als Projekt → Projekt-Funktion, die `setProject` erst per `diffToOps` über
|
||||
// alle Listen zurückübersetzen muss (bei 3000 Wänden ≈ 2,4 ms je Mausschritt). Die Helfer lesen
|
||||
// {@link CoreOp}s statt als Projekt → Projekt-Funktion (früher übersetzte `setProject` sie per
|
||||
// Projekt-Differenz zurück: bei 3000 Wänden ≈ 2,4 ms je Mausschritt; die Differenz ist gelöscht). Die Helfer lesen
|
||||
// nur das betroffene Element; unveränderte Elemente bleiben unberührt (Identität in der
|
||||
// TS-Leseansicht, `applyOps`).
|
||||
//
|
||||
@@ -9,7 +9,7 @@
|
||||
// {@link opsMutation} die Ops mit — `setProject` nimmt dann die Ops ohne Differenz.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { applyOps, diffToOps } from "./ops";
|
||||
import { applyOps } from "./ops";
|
||||
import type { CoreOp } from "./ops";
|
||||
|
||||
/** Projekt-Felder, die Listen von Elementen mit `id` sind (walls, drawings2d, rooms, …). */
|
||||
@@ -173,28 +173,73 @@ export type ProjectMutation = ((p: Project) => Project) & { readonly toOps: (p:
|
||||
|
||||
/**
|
||||
* Verpackt einen Op-Bauer als Projekt → Projekt-Funktion (für Schnittstellen wie
|
||||
* `CommandResult.commit`). Aufgerufen liefert sie `applyOps(p, build(p))`; `setProject` erkennt
|
||||
* sie an `toOps` und übergibt die Ops ohne `diffToOps` an den Kern.
|
||||
* `CommandResult.commit`). Aufgerufen liefert sie `applyOps(p, build(p))`; `setProject` übergibt
|
||||
* ihre `toOps` an den Kern.
|
||||
*/
|
||||
export function opsMutation(build: (p: Project) => CoreOp[]): ProjectMutation {
|
||||
const fn = (p: Project): Project => applyOps(p, build(p));
|
||||
return Object.assign(fn, { toOps: build });
|
||||
}
|
||||
|
||||
/** Ob `fn` ihre Ops mitträgt. */
|
||||
export function isOpsMutation(fn: unknown): fn is ProjectMutation {
|
||||
return typeof fn === "function" && typeof (fn as Partial<ProjectMutation>).toOps === "function";
|
||||
}
|
||||
|
||||
/**
|
||||
* Ops, die das Feld `key` auf `value` bringen — für KLEINE Listen, die eine Hilfsfunktion als Ganzes
|
||||
* neu liefert (Ebenen nach `recomputeFloorElevations`, Kategorien-Baum …): Differenz nur über
|
||||
* dieses eine Feld (Elemente mit id einzeln, sonst `setField`). Grosse Listen (Wände, 2D) gehören
|
||||
* über {@link patchItem}/{@link patchItems}/{@link addItems}/{@link removeItems}.
|
||||
* dieses eine Feld (Elemente mit id einzeln: `remove`/`replace`/`reorder`/`add`, sonst `setField`).
|
||||
* `applyOps(p, fieldOps(p, key, v))[key]` ist inhaltlich `v`, Elemente aus `v` behalten ihre Identität.
|
||||
* Grosse Listen (Wände, 2D) gehören über {@link patchItem}/{@link patchItems}/{@link addItems}/{@link removeItems}.
|
||||
*/
|
||||
export function fieldOps<K extends keyof Project>(p: Project, key: K, value: Project[K] | undefined): CoreOp[] {
|
||||
if (p[key] === value) return [];
|
||||
const before = { [key]: p[key] } as unknown as Project;
|
||||
const after = (value === undefined ? {} : { [key]: value }) as unknown as Project;
|
||||
return diffToOps(before, after);
|
||||
const va = p[key] as unknown;
|
||||
const vb = value as unknown;
|
||||
if (va === vb) return [];
|
||||
if (isIdList(va) && isIdList(vb) && uniqueIds(va) && uniqueIds(vb)) return diffList(key, va, vb);
|
||||
return [vb === undefined ? { kind: "setField", key } : { kind: "setField", key, value: vb }];
|
||||
}
|
||||
|
||||
const isEntityList = (v: unknown): v is AnyEntity[] =>
|
||||
Array.isArray(v) && v.length > 0 && v.every((x) => x !== null && typeof x === "object" && typeof (x as AnyEntity).id === "string");
|
||||
|
||||
/** Ob `v` eine (auch leere) Liste ist, deren Elemente — falls vorhanden — alle `id`s tragen. */
|
||||
const isIdList = (v: unknown): v is AnyEntity[] => Array.isArray(v) && (v.length === 0 || isEntityList(v));
|
||||
|
||||
/** Eindeutige ids? (Voraussetzung für die Element-Ops.) */
|
||||
function uniqueIds(list: AnyEntity[]): boolean {
|
||||
const seen = new Set<string>();
|
||||
for (const e of list) {
|
||||
if (seen.has(e.id)) return false;
|
||||
seen.add(e.id);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function diffList(collection: string, va: AnyEntity[], vb: AnyEntity[]): CoreOp[] {
|
||||
const ops: CoreOp[] = [];
|
||||
const inB = new Set(vb.map((e) => e.id));
|
||||
const mapA = new Map(va.map((e) => [e.id, e]));
|
||||
const removed = va.filter((e) => !inB.has(e.id)).map((e) => e.id);
|
||||
if (removed.length) ops.push({ kind: "remove", collection, ids: removed });
|
||||
// Geänderte Elemente (gleiche id, andere Referenz).
|
||||
for (const e of vb) {
|
||||
const old = mapA.get(e.id);
|
||||
if (old !== undefined && old !== e) ops.push({ kind: "replace", collection, entity: e });
|
||||
}
|
||||
// Reihenfolge der behaltenen Elemente in vb.
|
||||
const kept = va.filter((e) => inB.has(e.id)).map((e) => e.id);
|
||||
const keptSet = new Set(kept);
|
||||
const keptInB = vb.map((e) => e.id).filter((id) => keptSet.has(id));
|
||||
if (keptInB.some((id, idx) => id !== kept[idx])) ops.push({ kind: "reorder", collection, ids: keptInB });
|
||||
// Neue Elemente: zusammenhängende Läufe, von links nach rechts direkt an ihrer Zielposition
|
||||
// in `vb` eingefügt (frühere Läufe stehen dann schon, die Position stimmt).
|
||||
let i = 0;
|
||||
while (i < vb.length) {
|
||||
if (keptSet.has(vb[i].id)) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
const at = i;
|
||||
const run: AnyEntity[] = [];
|
||||
while (i < vb.length && !keptSet.has(vb[i].id)) run.push(vb[i++]);
|
||||
ops.push({ kind: "add", collection, items: run, at });
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// NUR für Tests: Ops, die `prev` in `next` überführen (je Feld `fieldOps`, Listen elementweise).
|
||||
// Die App erzeugt Änderungen direkt als Ops ([K4] S3, `opsBuild.ts`) und lädt ganze Projekte über
|
||||
// den Kern (`loadProject`/`openProjectFile`, S4); eine Projekt-Differenz gibt es dort nicht mehr. Die
|
||||
// Tests brauchen sie, um beliebige Zufallsänderungen als Ops an den Kern zu geben.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import type { CoreOp } from "./ops";
|
||||
import { fieldOps } from "./opsBuild";
|
||||
|
||||
export function projectDiffOps(prev: Project, next: Project): CoreOp[] {
|
||||
if (prev === next) return [];
|
||||
const a = prev as unknown as Record<string, unknown>;
|
||||
const b = next as unknown as Record<string, unknown>;
|
||||
const ops: CoreOp[] = [];
|
||||
for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
|
||||
if (a[key] !== b[key]) ops.push(...fieldOps(prev, key as keyof Project, b[key] as never));
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
@@ -6,7 +6,8 @@ import "../engine/fileioWasm.setup";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { applyOps, diffToOps, validateProject } from "../core/ops";
|
||||
import { applyOps, validateProject } from "../core/ops";
|
||||
import { projectDiffOps } from "../core/projectDiff.testutil";
|
||||
import { exportIfcSpf } from "../export/exportIfc";
|
||||
import { emptyProject, sampleProject } from "../model/sampleProject";
|
||||
import type { Column, Opening, Project, Vec2, Wall } from "../model/types";
|
||||
@@ -143,7 +144,7 @@ describe("IFC-Import als Bauteile: Rundreise Demo-Haus", () => {
|
||||
|
||||
it("über Ops angewandt und gespeichert/geladen bleibt alles gleich", async () => {
|
||||
const { project: next } = await importInto(emptyProject, sampleProject);
|
||||
const applied = applyOps(emptyProject, diffToOps(emptyProject, next));
|
||||
const applied = applyOps(emptyProject, projectDiffOps(emptyProject, next));
|
||||
expect(applied.walls).toEqual(next.walls);
|
||||
expect(applied.openings).toEqual(next.openings);
|
||||
const back = parseProjectFile(serializeProject(applied));
|
||||
|
||||
+29
-23
@@ -5,10 +5,14 @@
|
||||
// konnte, kommt wie beim Mesh-Import als Kontext-Mesh (`ifcImport.ts`).
|
||||
//
|
||||
// Keine Geometrie-Rechnung hier: TS ordnet nur zu (Geschoss nach Höhe, Typ nach Schichten) und setzt
|
||||
// die Objekte zusammen. Das Projekt wird nicht verändert — der Aufrufer übernimmt das Ergebnis über
|
||||
// `setProject` (App) bzw. `diffToOps`/`applyOps` (CLI), also über Ops.
|
||||
// die Objekte zusammen. Das Projekt wird nicht verändert — das Ergebnis sind Ops ([K4] S3), die der
|
||||
// Aufrufer übernimmt (App: Store `applyChange`, ein Undo-Schritt; CLI: `applyOps`).
|
||||
|
||||
import { ensureContextCategories } from "../model/contextCategories";
|
||||
import { applyOps } from "../core/ops";
|
||||
import type { CoreOp } from "../core/ops";
|
||||
import { addItems, fieldOps } from "../core/opsBuild";
|
||||
import type { EntityOf } from "../core/opsBuild";
|
||||
import type {
|
||||
Ceiling,
|
||||
CeilingType,
|
||||
@@ -287,8 +291,8 @@ function flatCategories(list: LayerCategory[], out: LayerCategory[] = []): Layer
|
||||
}
|
||||
|
||||
/**
|
||||
* Setzt die erkannten Bauteile und die übrigen Kontext-Meshes ins Projekt (neues Objekt, das alte
|
||||
* bleibt unverändert). Geschosse werden nach Höhe wiederverwendet (±5 mm) oder angelegt, Wand- und
|
||||
* Setzt die erkannten Bauteile und die übrigen Kontext-Meshes ins Projekt: `ops` (für den Store),
|
||||
* `project` = `applyOps(project, ops)` (neues Objekt, das alte bleibt unverändert). Geschosse werden nach Höhe wiederverwendet (±5 mm) oder angelegt, Wand- und
|
||||
* Deckentypen nach Schichten (Material + Dicke) wiederverwendet oder angelegt, Materialien nach Namen.
|
||||
*/
|
||||
export function ifcElementsToProject(
|
||||
@@ -296,7 +300,7 @@ export function ifcElementsToProject(
|
||||
products: IfcProduct[],
|
||||
elements: IfcElementsData,
|
||||
opts: IfcElementsOptions,
|
||||
): { project: Project; summary: IfcElementsSummary } {
|
||||
): { ops: CoreOp[]; project: Project; summary: IfcElementsSummary } {
|
||||
const stamp = Date.now().toString(36);
|
||||
const newId = (kind: string) => `ifc-${kind}-${stamp}-${counter++}`;
|
||||
const summary: IfcElementsSummary = {
|
||||
@@ -559,25 +563,27 @@ export function ifcElementsToProject(
|
||||
withClass(elements.walls) + withClass(elements.openings.filter((o) => o.kind !== "hole")) + withClass(elements.slabs) + withClass(elements.columns) + withClass(elements.spaces) +
|
||||
products.filter((p) => p.classifications?.length).length;
|
||||
|
||||
const next: Project = {
|
||||
...project,
|
||||
drawingLevels: levels,
|
||||
components,
|
||||
wallTypes,
|
||||
...(ceilingTypes.length || project.ceilingTypes ? { ceilingTypes } : {}),
|
||||
walls: [...project.walls, ...walls],
|
||||
openings: [...(project.openings ?? []), ...openings],
|
||||
ceilings: [...(project.ceilings ?? []), ...ceilings],
|
||||
columns: [...(project.columns ?? []), ...columns],
|
||||
rooms: [...(project.rooms ?? []), ...rooms],
|
||||
// Fehlende Listen werden (wie früher beim Ersetzen des Projekts) leer angelegt.
|
||||
const list = <K extends "openings" | "ceilings" | "columns" | "rooms">(key: K, items: EntityOf<K>[]): CoreOp[] =>
|
||||
project[key] ? addItems(key, items) : fieldOps(project, key, items as Project[K]);
|
||||
const ops: CoreOp[] = [
|
||||
...fieldOps(project, "drawingLevels", levels),
|
||||
...fieldOps(project, "components", components),
|
||||
...fieldOps(project, "wallTypes", wallTypes),
|
||||
...(ceilingTypes.length || project.ceilingTypes ? fieldOps(project, "ceilingTypes", ceilingTypes) : []),
|
||||
...addItems("walls", walls),
|
||||
...list("openings", openings),
|
||||
...list("ceilings", ceilings),
|
||||
...list("columns", columns),
|
||||
...list("rooms", rooms),
|
||||
...(meshes.length
|
||||
? {
|
||||
context: [...(project.context ?? []), ...meshes],
|
||||
layers: ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : []))),
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
return { project: next, summary };
|
||||
? [
|
||||
...(project.context ? addItems("context", meshes) : fieldOps(project, "context", meshes)),
|
||||
...fieldOps(project, "layers", ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : [])))),
|
||||
]
|
||||
: []),
|
||||
];
|
||||
return { ops, project: applyOps(project, ops), summary };
|
||||
}
|
||||
|
||||
/** Meldung zum Bauteil-Import; `tr` übersetzt (Kern kennt kein i18n). */
|
||||
|
||||
@@ -71,3 +71,49 @@ describe("Migration 1 → 2: Legacy-Türen werden Öffnungen", () => {
|
||||
expect(r.project.openings!.some((o) => o.id === `${existing}-t` && o.kind === "door")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Laden und Speichern im Kern ([K4] S4)", () => {
|
||||
// Früher: TS `JSON.parse` → Prüfung/Migration → `JSON.stringify({ formatVersion, ...rest }, null, 2)`.
|
||||
// Heute liest, migriert und schreibt der Kern; die Datei muss Zeichen für Zeichen gleich bleiben
|
||||
// (Zahlen wie JS `String(n)`, Index-Schlüssel wie ein JS-Objekt vorn).
|
||||
const reference = (p: object): string => JSON.stringify({ formatVersion: PROJECT_FORMAT_VERSION, ...p }, null, 2);
|
||||
const TRICKY = [0.000005, 1.5e-7, 1e21, 2 ** 60, 2 ** 53 + 2, -0, 0.1 + 0.2, 1e16, 2.7755575615628914e-17, -1e-6];
|
||||
|
||||
it("Speichern nach Öffnen = JSON.stringify der Leseansicht (Beispiel, knifflige Zahlen, Index-Schlüssel)", () => {
|
||||
const odd = {
|
||||
...structuredClone(sampleProject),
|
||||
walls: sampleProject.walls.map((w, i) => ({ ...w, height: TRICKY[i % TRICKY.length] })),
|
||||
zukunft: { b: 1, "21": "x\u0001\n😀", "10": [1.0, 2.5e-7], "007": null, "4294967295": 0 },
|
||||
};
|
||||
const texts = [JSON.stringify(sampleProject), JSON.stringify(odd), JSON.stringify(odd, null, 2).replace(/: 2,/g, ": 2.0,")];
|
||||
for (const text of texts) {
|
||||
const r = parseProjectFile(text);
|
||||
expect(r.ok).toBe(true);
|
||||
if (!r.ok) continue;
|
||||
const saved = serializeProject(r.project);
|
||||
expect(saved).toBe(reference(r.project));
|
||||
const { formatVersion: _v, ...raw } = JSON.parse(text) as Record<string, unknown>;
|
||||
expect(saved).toBe(reference(raw));
|
||||
}
|
||||
});
|
||||
|
||||
it("Index-Schlüssel stehen vorn, aufsteigend (wie JSON.parse in JS)", () => {
|
||||
const text = `{"walls":[],"layers":[],"drawingLevels":[],"m":{"x":1,"10":2,"2":3,"01":4}}`;
|
||||
const r = parseProjectFile(text);
|
||||
expect(r.ok && Object.keys((r.project as unknown as { m: object }).m)).toEqual(["2", "10", "x", "01"]);
|
||||
expect(r.ok && serializeProject(r.project)).toBe(r.ok && reference(r.project));
|
||||
});
|
||||
|
||||
it("migrierte Datei wird im neuen Format gespeichert", () => {
|
||||
const old = { ...structuredClone(sampleProject), formatVersion: 1, doors: [{ id: "TX", hostWallId: "W1", position: 0.5, width: 0.9, height: 2.1 }] };
|
||||
const r = parseProjectFile(JSON.stringify(old));
|
||||
expect(r.ok).toBe(true);
|
||||
if (!r.ok) return;
|
||||
const saved = serializeProject(r.project);
|
||||
expect(saved).toBe(reference(r.project));
|
||||
expect(JSON.parse(saved).doors).toBeUndefined();
|
||||
const again = parseProjectFile(saved);
|
||||
expect(again.ok && again.migratedFrom).toBeNull();
|
||||
expect(again.ok && serializeProject(again.project)).toBe(saved);
|
||||
});
|
||||
});
|
||||
+12
-13
@@ -1,5 +1,7 @@
|
||||
// Projektdatei-Format (`.obp`/`.obpt`/Alt-`.json`): Versionierung, Migration und EIN Parser für alle
|
||||
// Ladestellen. Gerechnet wird im Rust-Kern (`src-tauri/core/src/project_format.rs`, [K4]).
|
||||
// Ladestellen. Gerechnet wird im Rust-Kern (`src-tauri/core/src/project_format.rs`, [K4] S4): der Kern
|
||||
// liest den Text, migriert und lädt das Ergebnis direkt in ein Kern-Dokument; Speichern schreibt der
|
||||
// Kern aus dem Dokument (Zeichen für Zeichen wie `JSON.stringify(…, null, 2)`).
|
||||
//
|
||||
// Regeln:
|
||||
// • Jede gespeicherte Datei trägt `formatVersion` (s. {@link PROJECT_FORMAT_VERSION}).
|
||||
@@ -9,26 +11,23 @@
|
||||
// • Tolerant lesen: fehlende Listen werden leer ergänzt, unbekannte Felder bleiben erhalten und
|
||||
// werden gemeldet (nicht gelöscht).
|
||||
// • Was kein Dossier-Projekt ist, ist ein Fehler mit Meldung — nie ein stilles `console.warn`.
|
||||
//
|
||||
// Im Store öffnet `openProjectFile` (projectSlice) die Datei im Store-Dokument (mit Verlauf); diese
|
||||
// Fassade lädt ins gemeinsame Abfrage-Dokument (CLI, MCP, Tests) — die Abfragen auf dem gelesenen
|
||||
// Projekt laufen danach ohne erneute Übergabe.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import { documentFor } from "../core/document";
|
||||
import { documentFor, sharedDocument } from "../core/document";
|
||||
import type { LoadFileResult } from "../core/document";
|
||||
|
||||
/** Aktuelle Version des Dateiformats (muss `PROJECT_FORMAT_VERSION` im Kern entsprechen — Test). */
|
||||
export const PROJECT_FORMAT_VERSION = 2;
|
||||
|
||||
export type ParseProjectResult =
|
||||
| { ok: true; project: Project; warnings: string[]; migratedFrom: number | null }
|
||||
| { ok: false; error: string };
|
||||
export type ParseProjectResult = LoadFileResult;
|
||||
|
||||
/** Liest eine Projektdatei (Text) tolerant ein, migriert und prüft sie. */
|
||||
/** Liest eine Projektdatei (Text) tolerant ein, migriert und prüft sie (Kern, gemeinsames Dokument). */
|
||||
export function parseProjectFile(text: string): ParseProjectResult {
|
||||
return JSON.parse(core().project_parse(text, Date.now())) as ParseProjectResult;
|
||||
}
|
||||
|
||||
/** Wie {@link parseProjectFile}, für ein bereits geparstes Objekt. */
|
||||
export function parseProjectObject(raw: unknown): ParseProjectResult {
|
||||
return parseProjectFile(JSON.stringify(raw ?? null));
|
||||
return sharedDocument().loadFile(text);
|
||||
}
|
||||
|
||||
/** Serialisiert ein Projekt für die Datei (mit aktueller Formatversion vorne). */
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
// Gruppen-Logik im Rust-Kern ([K4] S3, `src-tauri/core/src/groups.rs`): transitive Mitgliedschaft,
|
||||
// die im Isolations-Kontext sichtbare Gruppe eines Elements, Auswahl um Gruppen erweitern. Dünne
|
||||
// Fassade über Kern-Abfragen auf dem Dokument des Projekts (`documentFor`); die Op-Bauer und das
|
||||
// Dimmen der Plan-Primitive bleiben in `state/groupActions.ts`.
|
||||
|
||||
import type { Project } from "./types";
|
||||
import { documentFor } from "../core/document";
|
||||
|
||||
/** Mitglieds-IDs je Elementart — dieselbe Form wie `Group`, ohne `id`/`name`/`groupIds`. */
|
||||
export interface GroupMembership {
|
||||
wallIds: string[];
|
||||
drawingIds: string[];
|
||||
ceilingIds: string[];
|
||||
roomIds: string[];
|
||||
stairIds: string[];
|
||||
columnIds: string[];
|
||||
roofIds: string[];
|
||||
openingIds: string[];
|
||||
}
|
||||
|
||||
export type MemberKind = keyof GroupMembership;
|
||||
|
||||
export const EMPTY_MEMBERSHIP: GroupMembership = {
|
||||
wallIds: [],
|
||||
drawingIds: [],
|
||||
ceilingIds: [],
|
||||
roomIds: [],
|
||||
stairIds: [],
|
||||
columnIds: [],
|
||||
roofIds: [],
|
||||
openingIds: [],
|
||||
};
|
||||
|
||||
/** Letzte transitive Mitgliedschaft (Projekt + Gruppe): Klick-/Rahmen-Filter fragen je Element. */
|
||||
let memo: { project: Project; groupId: string; m: GroupMembership; sets: Map<MemberKind, Set<string>> } | null = null;
|
||||
|
||||
function cached(project: Project, groupId: string) {
|
||||
if (memo && memo.project === project && memo.groupId === groupId) return memo;
|
||||
const m = documentFor(project).query<GroupMembership>("groupMembership", [], groupId);
|
||||
memo = { project, groupId, m, sets: new Map() };
|
||||
return memo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transitive Mitgliedschaft einer Gruppe: löst verschachtelte Gruppen (`groupIds`) rekursiv auf und
|
||||
* vereinigt alle Mitglieds-IDs (Zyklenschutz). Unbekannte Gruppe = leer.
|
||||
*/
|
||||
export function transitiveMembership(project: Project, groupId: string): GroupMembership {
|
||||
return cached(project, groupId).m;
|
||||
}
|
||||
|
||||
/**
|
||||
* Die „sichtbare" Gruppe, die ein Element enthält, relativ zum Isolations-Kontext `groupPath`
|
||||
* (leer = nicht isoliert): ohne Isolation unter den obersten Gruppen, isoliert nur unter den
|
||||
* DIREKTEN Untergruppen der aktiven Gruppe (direkte Mitglieder der aktiven Gruppe zählen nicht).
|
||||
* `null` = keine.
|
||||
*/
|
||||
export function containingGroupId(project: Project, kind: MemberKind, id: string, groupPath: string[]): string | null {
|
||||
if (!project.groups?.length) return null;
|
||||
return documentFor(project).query<string | null>("containingGroup", [], JSON.stringify({ kind, id, path: groupPath }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ob ein Element im Isolations-Kontext editierbar ist: ohne aktive Gruppe immer, isoliert nur, wenn
|
||||
* es TRANSITIV zur aktiven (innersten) Gruppe gehört.
|
||||
*/
|
||||
export function isInsideActiveGroup(project: Project, kind: MemberKind, id: string, groupPath: string[]): boolean {
|
||||
if (groupPath.length === 0) return true;
|
||||
const c = cached(project, groupPath[groupPath.length - 1]);
|
||||
let set = c.sets.get(kind);
|
||||
if (!set) {
|
||||
set = new Set(c.m[kind]);
|
||||
c.sets.set(kind, set);
|
||||
}
|
||||
return set.has(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Erweitert eine Treffer-Mitgliedschaft (Einzelklick oder Rahmen) um Gruppen: jede id einer im
|
||||
* Kontext sichtbaren Gruppe wird durch deren transitive Mitgliedschaft ersetzt, ids ohne Gruppe
|
||||
* bleiben einzeln; dazu die getroffenen Gruppen-ids.
|
||||
*/
|
||||
export function expandToGroups(
|
||||
project: Project,
|
||||
raw: GroupMembership,
|
||||
groupPath: string[],
|
||||
): { expanded: GroupMembership; groupIds: string[] } {
|
||||
if (!project.groups?.length) {
|
||||
// Ohne Gruppen: nur vereinigen (wie der Kern, ohne Übergabe).
|
||||
const expanded = { ...EMPTY_MEMBERSHIP };
|
||||
for (const k of Object.keys(EMPTY_MEMBERSHIP) as MemberKind[]) expanded[k] = [...new Set(raw[k])];
|
||||
return { expanded, groupIds: [] };
|
||||
}
|
||||
return documentFor(project).query("expandToGroups", [], JSON.stringify({ raw, path: groupPath }));
|
||||
}
|
||||
@@ -22,7 +22,7 @@ function bigProject(n: number): Project {
|
||||
|
||||
describe("Messung Store-Aktionen, 3000 Wände", () => {
|
||||
it("Griff ziehen, Auswahl verschieben, Eigenschaft tippen", () => {
|
||||
st().setProject(bigProject(3000));
|
||||
st().loadProject(bigProject(3000));
|
||||
st().clearHistory();
|
||||
const depth0 = st().undoDepth;
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// [K4] S3 zweite Etappe: Store-Aktionen erzeugen Ops direkt (`applyChange`, `opsMutation`) statt
|
||||
// Projekt → Projekt + `diffToOps`. Geprüft: Ops gehen unverändert an den Kern (Verlauf, Prüfung),
|
||||
// Projekt → Projekt + Projekt-Differenz (gelöscht). Geprüft: Ops gehen unverändert an den Kern (Verlauf, Prüfung),
|
||||
// Leseansicht und Kern-Dokument bleiben gleich — auch über Zufallsfolgen der umgestellten
|
||||
// Aktionen mit Undo bis zum Anfang und Redo bis zum Ende.
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
@@ -40,7 +40,7 @@ function expectMirror(): void {
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
st().setProject(structuredClone(sampleProject));
|
||||
st().loadProject(structuredClone(sampleProject));
|
||||
st().clearHistory();
|
||||
});
|
||||
|
||||
|
||||
+12
-5
@@ -17,18 +17,25 @@ const UNSAVED = "unsaved";
|
||||
/** Schlüssel der Wiederherstellungskopie für eine Datei (oder ein ungespeichertes Projekt). */
|
||||
export const autosaveKey = (path: string | null): string => PREFIX + (path ?? UNSAVED);
|
||||
|
||||
export const writeAutosave = (path: string | null, project: Project): Promise<void> =>
|
||||
saveProject(autosaveKey(path), project);
|
||||
/** Sichert den Datei-Text des Projekts (`serializeProject`, wie beim Speichern; [K4] S4). */
|
||||
export const writeAutosave = (path: string | null, text: string): Promise<void> =>
|
||||
saveProject(autosaveKey(path), text);
|
||||
|
||||
export const readAutosave = (path: string | null): Promise<{ project: Project; savedAt: number } | null> =>
|
||||
loadProjectRecord(autosaveKey(path));
|
||||
/** Liest die Kopie als Datei-Text (ältere Kopien als Objekt werden zu Text) — Wiederherstellen lädt sie
|
||||
* wie eine Datei (`openProjectFile`: Migration, Prüfung). */
|
||||
export const readAutosave = async (path: string | null): Promise<{ text: string; savedAt: number } | null> => {
|
||||
const r = await loadProjectRecord(autosaveKey(path));
|
||||
if (!r) return null;
|
||||
return { text: typeof r.project === "string" ? r.project : JSON.stringify(r.project), savedAt: r.savedAt };
|
||||
};
|
||||
|
||||
export const clearAutosave = (path: string | null): Promise<void> => deleteProject(autosaveKey(path));
|
||||
|
||||
/** Eine angebotene Wiederherstellung. */
|
||||
export interface AutosaveRecovery {
|
||||
path: string | null;
|
||||
project: Project;
|
||||
/** Datei-Text der Kopie. */
|
||||
text: string;
|
||||
savedAt: number;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,14 +8,12 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
activeGroupOps,
|
||||
addNewElementsToActiveGroup,
|
||||
applyGroupDimming,
|
||||
applyGroupDimmingToPlan,
|
||||
containingGroupId,
|
||||
expandToGroups,
|
||||
groupSelection,
|
||||
isInsideActiveGroup,
|
||||
topLevelGroups,
|
||||
transitiveMembership,
|
||||
ungroup,
|
||||
} from "./groupActions";
|
||||
@@ -95,15 +93,11 @@ describe("transitiveMembership", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("topLevelGroups / containingGroupId", () => {
|
||||
describe("containingGroupId (Kern)", () => {
|
||||
const inner: Group = { id: "g1", wallIds: ["w1"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: [] };
|
||||
const outer: Group = { id: "g2", wallIds: ["w2"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: ["g1"] };
|
||||
const p = project([inner, outer]);
|
||||
|
||||
it("topLevelGroups schliesst verschachtelte Untergruppen aus", () => {
|
||||
expect(topLevelGroups(p).map((g) => g.id)).toEqual(["g2"]);
|
||||
});
|
||||
|
||||
it("ohne Isolation (groupPath leer): findet nur die ÄUSSERE Gruppe für ein Element in g1", () => {
|
||||
expect(containingGroupId(p, "wallIds", "w1", [])).toBe("g2");
|
||||
});
|
||||
@@ -220,36 +214,36 @@ describe("applyGroupDimmingToPlan", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("addNewElementsToActiveGroup", () => {
|
||||
describe("activeGroupOps ([K4] S3: neue Elemente in die aktive Gruppe, als Ops)", () => {
|
||||
const g1: Group = { id: "g1", wallIds: ["w1"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: [] };
|
||||
const line = (id: string) =>
|
||||
({ id, type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } } }) as Project["drawings2d"][number];
|
||||
/** Wendet `ops` plus die Gruppen-Ops an (wie `EngineHost.commit` in App.tsx). */
|
||||
const commit = (before: Project, ops: CoreOp[], path: string[]) => applyOps(before, [...ops, ...activeGroupOps(before, ops, path)]);
|
||||
|
||||
it("neu gezeichnetes Element wird Mitglied der aktiven (innersten) Gruppe", () => {
|
||||
const before = project([g1]);
|
||||
const after: Project = { ...before, drawings2d: [line("d1")] };
|
||||
const result = addNewElementsToActiveGroup(before, after, ["g1"]);
|
||||
const result = commit(project([g1]), addItems("drawings2d", [line("d1")]), ["g1"]);
|
||||
const g = result.groups!.find((x) => x.id === "g1")!;
|
||||
expect(g.drawingIds).toEqual(["d1"]);
|
||||
expect(g.wallIds).toEqual(["w1"]); // bestehende Mitgliedschaft bleibt
|
||||
});
|
||||
|
||||
it("ohne aktive Gruppe (groupPath leer) bleibt das Projekt unverändert", () => {
|
||||
const before = project([g1]);
|
||||
const after: Project = { ...before, drawings2d: [line("d1")] };
|
||||
const result = addNewElementsToActiveGroup(before, after, []);
|
||||
expect(result).toBe(after); // unverändert (Referenzgleichheit)
|
||||
it("ohne aktive Gruppe (groupPath leer) keine zusätzlichen Ops", () => {
|
||||
expect(activeGroupOps(project([g1]), addItems("drawings2d", [line("d1")]), [])).toEqual([]);
|
||||
});
|
||||
|
||||
it("keine Änderung (before === after) ist ein No-op", () => {
|
||||
const p = project([g1]);
|
||||
expect(addNewElementsToActiveGroup(p, p, ["g1"])).toBe(p);
|
||||
it("ohne neue Elemente (nur Ersetzen) keine zusätzlichen Ops", () => {
|
||||
const p: Project = { ...project([g1]), drawings2d: [line("d0")] };
|
||||
expect(activeGroupOps(p, [replaceItem("drawings2d", { ...line("d0"), color: "#f00" })], ["g1"])).toEqual([]);
|
||||
expect(activeGroupOps(p, [], ["g1"])).toEqual([]);
|
||||
});
|
||||
|
||||
it("unbekannte aktive Gruppe: keine zusätzlichen Ops", () => {
|
||||
expect(activeGroupOps(project([g1]), addItems("drawings2d", [line("d1")]), ["gx"])).toEqual([]);
|
||||
});
|
||||
|
||||
it("mehrere neue Elemente auf einmal (z. B. Feld/Array) werden alle Mitglied", () => {
|
||||
const before = project([g1]);
|
||||
const after: Project = { ...before, drawings2d: [line("d1"), line("d2"), line("d3")] };
|
||||
const result = addNewElementsToActiveGroup(before, after, ["g1"]);
|
||||
const result = commit(project([g1]), addItems("drawings2d", [line("d1"), line("d2"), line("d3")]), ["g1"]);
|
||||
const g = result.groups!.find((x) => x.id === "g1")!;
|
||||
expect(g.drawingIds.sort()).toEqual(["d1", "d2", "d3"]);
|
||||
});
|
||||
@@ -257,39 +251,12 @@ describe("addNewElementsToActiveGroup", () => {
|
||||
it("verschachtelt: neues Element landet in der INNERSTEN (aktiven) Gruppe, nicht der äusseren", () => {
|
||||
const inner: Group = { id: "g1", wallIds: [], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: [] };
|
||||
const outer: Group = { id: "g2", wallIds: [], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: ["g1"] };
|
||||
const before = project([inner, outer]);
|
||||
const after: Project = { ...before, drawings2d: [line("d1")] };
|
||||
const result = addNewElementsToActiveGroup(before, after, ["g2", "g1"]);
|
||||
const result = commit(project([inner, outer]), addItems("drawings2d", [line("d1")]), ["g2", "g1"]);
|
||||
expect(result.groups!.find((x) => x.id === "g1")!.drawingIds).toEqual(["d1"]);
|
||||
expect(result.groups!.find((x) => x.id === "g2")!.drawingIds).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("activeGroupOps ([K4] S3: Ops statt Differenz)", () => {
|
||||
const mk = (id: string): Group => ({ id, wallIds: ["w1"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: [] });
|
||||
const line = (id: string) =>
|
||||
({ id, type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } } }) as Project["drawings2d"][number];
|
||||
const wall = (id: string) => ({ id, start: { x: 0, y: 0 }, end: { x: 1, y: 0 } }) as unknown as Project["walls"][number];
|
||||
|
||||
it("gleiches Ergebnis wie addNewElementsToActiveGroup, Zufall", () => {
|
||||
let x = 11;
|
||||
const r = () => ((x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296);
|
||||
for (let n = 0; n < 200; n++) {
|
||||
const before: Project = { ...project([mk("g1"), mk("g2")]), drawings2d: [line("d0")], walls: [wall("w0")] };
|
||||
const ops: CoreOp[] = [];
|
||||
const k = Math.floor(r() * 4);
|
||||
if (k >= 1) ops.push(...addItems("drawings2d", [line(`a${n}`), line(`b${n}`)], r() < 0.5 ? 0 : undefined));
|
||||
if (k >= 2) ops.push(...addItems("walls", [wall(`w${n}x`)]));
|
||||
if (k >= 3) ops.push(replaceItem("drawings2d", { ...line("d0"), color: "#f00" }));
|
||||
const path = r() < 0.2 ? [] : r() < 0.5 ? ["g1"] : ["g2", "g1", "gx"];
|
||||
const after = applyOps(before, ops);
|
||||
const legacy = addNewElementsToActiveGroup(before, after, path);
|
||||
const viaOps = applyOps(before, [...ops, ...activeGroupOps(before, ops, path)]);
|
||||
expect(viaOps).toEqual(legacy);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("ungroup", () => {
|
||||
it("löst genau EIN Level auf; Untergruppen bleiben als eigene Gruppen bestehen", () => {
|
||||
const inner: Group = { id: "g1", wallIds: ["w1"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: [] };
|
||||
|
||||
+14
-195
@@ -1,7 +1,7 @@
|
||||
// Gruppen (Vectorworks-artig, s. `model/types.ts::Group`): reine Funktionen
|
||||
// über Mitgliedschaft/Verschachtelung + Erzeugen/Auflösen. Keine React-/Store-
|
||||
// Abhängigkeit — testbar ohne Mock, wird von `useGroupHandlers.ts` (Klick-/
|
||||
// Tastatur-Verdrahtung) und `PlanView.tsx` (Dimm-Rendering) konsumiert.
|
||||
// Gruppen (Vectorworks-artig, s. `model/types.ts::Group`): Erzeugen/Auflösen und Zuordnen als Ops,
|
||||
// Dimmen der Plan-Primitive bei Isolation. Die Mitgliedschafts-Logik (transitiv, sichtbare Gruppe,
|
||||
// Auswahl erweitern) rechnet der Rust-Kern (`src-tauri/core/src/groups.rs`, Fassade `model/groups.ts`,
|
||||
// [K4] S3); hier re-exportiert. Keine React-/Store-Abhängigkeit.
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
@@ -13,31 +13,11 @@ import { applyOps } from "../core";
|
||||
import type { CoreOp } from "../core";
|
||||
import { addItems, itemsOf, patchItem, removeItems } from "../core";
|
||||
import type { EntityCollection } from "../core";
|
||||
import { EMPTY_MEMBERSHIP, transitiveMembership } from "../core";
|
||||
import type { GroupMembership, MemberKind } from "../core";
|
||||
|
||||
/** Mitglieds-IDs je Elementart — dieselbe Form wie `Group`, ohne `id`/`name`/`groupIds`. */
|
||||
export interface GroupMembership {
|
||||
wallIds: string[];
|
||||
drawingIds: string[];
|
||||
ceilingIds: string[];
|
||||
roomIds: string[];
|
||||
stairIds: string[];
|
||||
columnIds: string[];
|
||||
roofIds: string[];
|
||||
openingIds: string[];
|
||||
}
|
||||
|
||||
export type MemberKind = keyof GroupMembership;
|
||||
|
||||
export const EMPTY_MEMBERSHIP: GroupMembership = {
|
||||
wallIds: [],
|
||||
drawingIds: [],
|
||||
ceilingIds: [],
|
||||
roomIds: [],
|
||||
stairIds: [],
|
||||
columnIds: [],
|
||||
roofIds: [],
|
||||
openingIds: [],
|
||||
};
|
||||
export type { GroupMembership, MemberKind } from "../core";
|
||||
export { EMPTY_MEMBERSHIP, containingGroupId, expandToGroups, isInsideActiveGroup, transitiveMembership } from "../core";
|
||||
|
||||
const KEYS: MemberKind[] = [
|
||||
"wallIds",
|
||||
@@ -50,135 +30,13 @@ const KEYS: MemberKind[] = [
|
||||
"openingIds",
|
||||
];
|
||||
|
||||
/** Vereinigung je Art (erste Vorkommen in Reihenfolge) — für Auswahl-Mengen in der Hülle. */
|
||||
export function mergeMembership(a: GroupMembership, b: GroupMembership): GroupMembership {
|
||||
const out = { ...a };
|
||||
for (const k of KEYS) out[k] = [...new Set([...a[k], ...b[k]])];
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transitive Mitgliedschaft einer Gruppe: löst verschachtelte Gruppen
|
||||
* (`groupIds`) rekursiv auf und vereinigt alle Mitglieds-IDs. Zyklenschutz
|
||||
* über `seen` (sollte nie vorkommen — `groupSelection` verhindert das beim
|
||||
* Erzeugen —, ist aber billig und schützt gegen manuell kaputte Projekte).
|
||||
*/
|
||||
export function transitiveMembership(
|
||||
project: Project,
|
||||
groupId: string,
|
||||
seen: Set<string> = new Set(),
|
||||
): GroupMembership {
|
||||
if (seen.has(groupId)) return EMPTY_MEMBERSHIP;
|
||||
seen.add(groupId);
|
||||
const g = (project.groups ?? []).find((x) => x.id === groupId);
|
||||
if (!g) return EMPTY_MEMBERSHIP;
|
||||
let out: GroupMembership = {
|
||||
wallIds: [...g.wallIds],
|
||||
drawingIds: [...g.drawingIds],
|
||||
ceilingIds: [...g.ceilingIds],
|
||||
roomIds: [...g.roomIds],
|
||||
stairIds: [...g.stairIds],
|
||||
columnIds: [...g.columnIds],
|
||||
roofIds: [...g.roofIds],
|
||||
openingIds: [...g.openingIds],
|
||||
};
|
||||
for (const sub of g.groupIds) out = mergeMembership(out, transitiveMembership(project, sub, seen));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** IDs aller Gruppen, die als Untergruppe in irgendeiner ANDEREN Gruppe stehen. */
|
||||
function nestedGroupIds(project: Project): Set<string> {
|
||||
const s = new Set<string>();
|
||||
for (const g of project.groups ?? []) for (const id of g.groupIds) s.add(id);
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Top-Level-Gruppen (nicht Untergruppe einer anderen Gruppe) — Kandidaten ausserhalb jeder Isolation. */
|
||||
export function topLevelGroups(project: Project): Group[] {
|
||||
const nested = nestedGroupIds(project);
|
||||
return (project.groups ?? []).filter((g) => !nested.has(g.id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Die „sichtbare" Gruppe, die ein Element enthält, relativ zum aktuellen
|
||||
* Isolations-Kontext `groupPath` (leer = nicht isoliert):
|
||||
* • nicht isoliert: sucht unter den TOP-LEVEL-Gruppen (verschachtelte
|
||||
* Untergruppen sind dabei „unsichtbar", man sieht nur die äusserste Hülle).
|
||||
* • isoliert (aktive Gruppe = letztes Element von `groupPath`): sucht NUR
|
||||
* unter den DIREKTEN Untergruppen der aktiven Gruppe — direkte Mitglieder
|
||||
* der aktiven Gruppe selbst zählen NICHT als „von einer Gruppe enthalten"
|
||||
* (die sind ja gerade einzeln bearbeitbar, weil man in der Gruppe ist).
|
||||
* `null` = das Element gehört zu keiner (in diesem Kontext sichtbaren) Gruppe.
|
||||
*/
|
||||
export function containingGroupId(
|
||||
project: Project,
|
||||
kind: MemberKind,
|
||||
id: string,
|
||||
groupPath: string[],
|
||||
): string | null {
|
||||
let candidates: Group[];
|
||||
if (groupPath.length === 0) {
|
||||
candidates = topLevelGroups(project);
|
||||
} else {
|
||||
const active = (project.groups ?? []).find((g) => g.id === groupPath[groupPath.length - 1]);
|
||||
if (!active) return null;
|
||||
candidates = active.groupIds
|
||||
.map((gid) => (project.groups ?? []).find((g) => g.id === gid))
|
||||
.filter((g): g is Group => !!g);
|
||||
}
|
||||
for (const g of candidates) {
|
||||
if (transitiveMembership(project, g.id)[kind].includes(id)) return g.id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ob ein Element im aktuellen Isolations-Kontext editierbar ist: ohne aktive
|
||||
* Gruppe (`groupPath` leer) immer `true`; isoliert nur, wenn das Element
|
||||
* TRANSITIV zur aktiven (innersten) Gruppe gehört — alles andere ist „grau
|
||||
* und gesperrt", analog zum bestehenden Ebenen-Sperren-Modus.
|
||||
*/
|
||||
export function isInsideActiveGroup(
|
||||
project: Project,
|
||||
kind: MemberKind,
|
||||
id: string,
|
||||
groupPath: string[],
|
||||
): boolean {
|
||||
if (groupPath.length === 0) return true;
|
||||
const active = groupPath[groupPath.length - 1];
|
||||
return transitiveMembership(project, active)[kind].includes(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Erweitert eine rohe Treffer-Mitgliedschaft (aus Einzelklick ODER Marquee,
|
||||
* beliebig viele IDs je Art) um Gruppen: jede ID, die zu einer im aktuellen
|
||||
* Isolations-Kontext (`groupPath`) SICHTBAREN Gruppe gehört (s.
|
||||
* `containingGroupId`), wird durch die TRANSITIVE Mitgliedschaft dieser
|
||||
* Gruppe ersetzt; IDs ohne Gruppe bleiben einzeln. Liefert zusätzlich die
|
||||
* Menge der dabei „getroffenen" Gruppen-IDs (für `selectedGroupIds`/die
|
||||
* Bounding-Box-Anzeige). Deckt Einzelklick (eine ID) UND Marquee (viele IDs
|
||||
* über mehrere Arten) mit derselben Logik ab.
|
||||
*/
|
||||
export function expandToGroups(
|
||||
project: Project,
|
||||
raw: GroupMembership,
|
||||
groupPath: string[],
|
||||
): { expanded: GroupMembership; groupIds: string[] } {
|
||||
let expanded: GroupMembership = { ...EMPTY_MEMBERSHIP };
|
||||
const groupIds = new Set<string>();
|
||||
for (const k of KEYS) {
|
||||
for (const id of raw[k]) {
|
||||
const gid = containingGroupId(project, k, id, groupPath);
|
||||
if (gid) {
|
||||
groupIds.add(gid);
|
||||
expanded = mergeMembership(expanded, transitiveMembership(project, gid));
|
||||
} else {
|
||||
expanded = mergeMembership(expanded, { ...EMPTY_MEMBERSHIP, [k]: [id] });
|
||||
}
|
||||
}
|
||||
}
|
||||
return { expanded, groupIds: [...groupIds] };
|
||||
}
|
||||
|
||||
/** Primitiv-ID-Feld → zugehörige `MemberKind` (Reihenfolge irrelevant). */
|
||||
const ID_FIELD_TO_KIND: [string, MemberKind][] = [
|
||||
["wallId", "wallIds"],
|
||||
@@ -255,47 +113,6 @@ export function applyGroupDimmingToPlan(plan: Plan, project: Project, groupPath:
|
||||
return { ...plan, primitives, underlay };
|
||||
}
|
||||
|
||||
/** IDs, die in `after` neu hinzugekommen sind (in `before` noch nicht vorhanden). */
|
||||
function newIds(before: { id: string }[], after: { id: string }[]): string[] {
|
||||
const beforeIds = new Set(before.map((x) => x.id));
|
||||
return after.filter((x) => !beforeIds.has(x.id)).map((x) => x.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeichnet man WÄHREND man eine Gruppe betreten hat (Isolation) ein neues
|
||||
* Element, wird es automatisch Mitglied dieser (innersten) Gruppe — man
|
||||
* zeichnet ja SICHTLICH „in" ihr (Nutzer-Wunsch, Vectorworks-Verhalten).
|
||||
* Vergleicht `before`/`after` je Elementart auf neu hinzugekommene IDs (Diff
|
||||
* über die commit-Mutation) und hängt sie an die aktive Gruppe an. `before`
|
||||
* === `after` (keine Änderung) oder `groupPath` leer → `after` unverändert.
|
||||
*/
|
||||
export function addNewElementsToActiveGroup(
|
||||
before: Project,
|
||||
after: Project,
|
||||
groupPath: string[],
|
||||
): Project {
|
||||
if (groupPath.length === 0 || before === after) return after;
|
||||
const activeId = groupPath[groupPath.length - 1];
|
||||
const g = (after.groups ?? []).find((x) => x.id === activeId);
|
||||
if (!g) return after;
|
||||
const added: GroupMembership = {
|
||||
wallIds: newIds(before.walls, after.walls),
|
||||
drawingIds: newIds(before.drawings2d, after.drawings2d),
|
||||
ceilingIds: newIds(before.ceilings ?? [], after.ceilings ?? []),
|
||||
roomIds: newIds(before.rooms ?? [], after.rooms ?? []),
|
||||
stairIds: newIds(before.stairs ?? [], after.stairs ?? []),
|
||||
columnIds: newIds(before.columns ?? [], after.columns ?? []),
|
||||
roofIds: newIds(before.roofs ?? [], after.roofs ?? []),
|
||||
openingIds: newIds(before.openings ?? [], after.openings ?? []),
|
||||
};
|
||||
if (KEYS.every((k) => added[k].length === 0)) return after;
|
||||
const merged: Group = { ...g, ...mergeMembership(g, added) };
|
||||
return {
|
||||
...after,
|
||||
groups: (after.groups ?? []).map((x) => (x.id === activeId ? merged : x)),
|
||||
};
|
||||
}
|
||||
|
||||
/** Liste je Mitgliedsart. */
|
||||
const COLLECTION_OF: Record<MemberKind, EntityCollection> = {
|
||||
wallIds: "walls",
|
||||
@@ -309,9 +126,11 @@ const COLLECTION_OF: Record<MemberKind, EntityCollection> = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Wie {@link addNewElementsToActiveGroup}, für eine Änderung als Ops ([K4] S3): die zusätzlichen
|
||||
* Ops, die die neu eingefügten Elemente (`add`-Ops) der aktiven Gruppe zuschlagen — ohne Differenz
|
||||
* über alle Listen. Leer ohne aktive Gruppe oder ohne neue Elemente.
|
||||
* Zeichnet man WÄHREND man eine Gruppe betreten hat (Isolation) ein neues Element, wird es
|
||||
* automatisch Mitglied dieser (innersten) Gruppe — man zeichnet ja SICHTLICH „in" ihr
|
||||
* (Nutzer-Wunsch, Vectorworks-Verhalten). Für eine Änderung als Ops ([K4] S3): die zusätzlichen
|
||||
* Ops, die die neu eingefügten Elemente (`add`-Ops) der aktiven Gruppe zuschlagen. Leer ohne
|
||||
* aktive Gruppe oder ohne neue Elemente.
|
||||
*/
|
||||
export function activeGroupOps(before: Project, ops: readonly CoreOp[], groupPath: string[]): CoreOp[] {
|
||||
if (groupPath.length === 0) return [];
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { getState, setState } from "./appStore";
|
||||
import { emptyProject } from "../model/sampleProject";
|
||||
import { setField } from "../core";
|
||||
|
||||
beforeEach(() => {
|
||||
setState({ project: emptyProject, undoDepth: 0, redoDepth: 0, canUndo: false, canRedo: false });
|
||||
@@ -11,7 +12,7 @@ beforeEach(() => {
|
||||
|
||||
describe("Undo/Redo über den Anfang hinaus", () => {
|
||||
it("drei Schritte, mehrmals ganz zurück und vor", () => {
|
||||
for (const name of ["A", "B", "C"]) getState().setProject((p) => ({ ...p, name }));
|
||||
for (const name of ["A", "B", "C"]) getState().applyChange([setField("name", name)]);
|
||||
expect(getState().project.name).toBe("C");
|
||||
for (let round = 0; round < 3; round++) {
|
||||
for (let k = 0; k < 6; k++) getState().undo();
|
||||
|
||||
+44
-42
@@ -8,12 +8,13 @@
|
||||
// laufen. Die Slice tippt daher nur ihre eigenen Felder; `get()` liefert
|
||||
// RootState (siehe appStore.ts), wir greifen punktuell auf View-Felder zu.
|
||||
|
||||
import { applyOps, diffToOps } from "../core/ops";
|
||||
import { applyOps } from "../core/ops";
|
||||
import type { CoreOp } from "../core/ops";
|
||||
import type { ProjectMutation } from "../core";
|
||||
import type { LoadFileResult } from "../core/document";
|
||||
import {
|
||||
addItems,
|
||||
fieldOps,
|
||||
isOpsMutation,
|
||||
patchItem,
|
||||
patchItems,
|
||||
removeItems,
|
||||
@@ -75,21 +76,32 @@ export interface ProjectSlice {
|
||||
|
||||
// ── Projekt direkt setzen (für Werkzeuge/Transformationen aus App) ────────
|
||||
/**
|
||||
* Ersetzt das Projekt (Teil-/Updater wie React-setState). `coalesceKey`:
|
||||
* NUR für bekannte Hochfrequenz-Aktionen (Griff-Ziehen, Inline-Text-Tippen)
|
||||
* — verschmilzt aufeinanderfolgende Aufrufe mit demselben Key innerhalb
|
||||
* `COALESCE_WINDOW_MS` zu EINEM Undo-Schritt, s. Kommentar bei der
|
||||
* Implementierung unten.
|
||||
* Änderung als Projekt → Projekt-Funktion MIT mitgeführten Ops (`opsMutation`, Schnittstellen wie
|
||||
* `CommandResult.commit`); der Kern bekommt die Ops ([K4] S3 — keine Projekt-Differenz mehr).
|
||||
* `coalesceKey`: NUR für bekannte Hochfrequenz-Aktionen (Griff-Ziehen, Inline-Text-Tippen) —
|
||||
* gleicher Key im Zeitfenster = EIN Undo-Schritt. Ein anderes Projekt als Ganzes:
|
||||
* {@link loadProject}/{@link openProjectFile}.
|
||||
*/
|
||||
setProject: (next: Project | ((p: Project) => Project), coalesceKey?: string) => void;
|
||||
setProject: (next: ProjectMutation, coalesceKey?: string) => void;
|
||||
/**
|
||||
* Änderung direkt als Ops ([K4] S3): `ops` oder ein Op-Bauer auf dem aktuellen Projekt
|
||||
* (`core/opsBuild.ts`). Geht ohne `diffToOps` an den Kern (Prüfung, Verlauf); sonst wie
|
||||
* (`core/opsBuild.ts`). Geht direkt an den Kern (Prüfung, Verlauf); sonst wie
|
||||
* {@link setProject} (gleicher `coalesceKey` im Zeitfenster = ein Undo-Schritt).
|
||||
*/
|
||||
applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[]), coalesceKey?: string) => void;
|
||||
/** Die zuletzt angewendeten Ops (JSON-serialisierbar), jüngste zuletzt. */
|
||||
recentOps: () => CoreOp[][];
|
||||
/**
|
||||
* Ein anderes Projekt übernehmen (Neu, Musterhaus; [K4] S4): lädt es als Ganzes ins Kern-Dokument
|
||||
* und leert den Verlauf (Rückgängig führt nicht ins vorherige Projekt).
|
||||
*/
|
||||
loadProject: (next: Project) => void;
|
||||
/**
|
||||
* Projektdatei (Text) öffnen (Öffnen, Vorlage, Wiederherstellen): der Kern liest, migriert, prüft
|
||||
* und lädt sie direkt (`ProjectDocument.loadFile`), der Verlauf wird geleert. Bei Fehler bleibt
|
||||
* das Projekt unverändert.
|
||||
*/
|
||||
openProjectFile: (text: string) => LoadFileResult;
|
||||
|
||||
// ── Zeichnungsebenen (Levels/Geschosse) ──────────────────────────────────
|
||||
toggleLevelVisible: (id: string) => void;
|
||||
@@ -485,32 +497,12 @@ export function createProjectSlice(
|
||||
return { project: res.project, ...historyPatch(doc) };
|
||||
};
|
||||
|
||||
// Bequemer immutabler Projekt-Updater (wie setProject in App). Zweiter,
|
||||
// optionaler Parameter `coalesceKey`: NUR von den paar bekannten
|
||||
// Hochfrequenz-Aktionen (Grip-Drag & Co., s. u.) gesetzt — alle anderen
|
||||
// Aktionen rufen ohne Key auf und pushen damit IMMER diskret (kein
|
||||
// Koaleszieren zwischen unterschiedlichen Aktionen möglich, auch nicht bei
|
||||
// zufällig identischem Timing in Tests).
|
||||
// [K4] S3: Projekt → Projekt-Funktionen gehen über `diffToOps` (Adapter für die Aktionen, die noch
|
||||
// nicht umgestellt sind); Funktionen aus `opsMutation` tragen ihre Ops mit und sparen die Differenz.
|
||||
const setProject = (
|
||||
next: Project | ((p: Project) => Project),
|
||||
coalesceKey?: string,
|
||||
) =>
|
||||
set((s) => {
|
||||
if (isOpsMutation(next)) return commitOps(s, next.toOps(s.project), coalesceKey);
|
||||
const wanted =
|
||||
typeof next === "function" ? (next as (p: Project) => Project)(s.project) : next;
|
||||
// No-Op-Schutz: echte Immutable-Updates liefern bei tatsächlicher
|
||||
// Änderung immer eine NEUE Referenz — bleibt sie gleich, gab es keine
|
||||
// Änderung, also kein History-Eintrag (und `set` selbst benachrichtigt
|
||||
// dann ebenfalls nicht, da der Patch leer ist).
|
||||
if (wanted === s.project) return {};
|
||||
// Das Projekt ändert sich NUR über Ops (core/ops.ts): die gewünschte Änderung wird in
|
||||
// eine Op-Folge übersetzt; der Kern prüft (NaN, doppelte ids), wendet an und zeichnet den
|
||||
// Undo-Schritt auf.
|
||||
return commitOps(s, diffToOps(s.project, wanted), coalesceKey);
|
||||
});
|
||||
// Änderung mit mitgeführten Ops (`opsMutation`). Zweiter, optionaler Parameter `coalesceKey`: NUR
|
||||
// von den paar bekannten Hochfrequenz-Aktionen (Grip-Drag & Co.) gesetzt — alle anderen Aktionen
|
||||
// rufen ohne Key auf und pushen damit IMMER diskret. Das Projekt ändert sich NUR über Ops: der Kern
|
||||
// prüft (NaN, doppelte ids), wendet an und zeichnet den Undo-Schritt auf ([K4] S3).
|
||||
const setProject = (next: ProjectMutation, coalesceKey?: string) =>
|
||||
set((s) => commitOps(s, next.toOps(s.project), coalesceKey));
|
||||
|
||||
// Änderung direkt als Ops (ohne Differenz), s. `ProjectSlice.applyChange`.
|
||||
const applyChange = (
|
||||
@@ -531,6 +523,19 @@ export function createProjectSlice(
|
||||
applyChange,
|
||||
recentOps: () => opLog.slice(),
|
||||
|
||||
loadProject: (next) => {
|
||||
const doc = storeDocument(get().project);
|
||||
doc.load(next);
|
||||
set({ project: next, ...historyPatch(doc) });
|
||||
},
|
||||
|
||||
openProjectFile: (text) => {
|
||||
const doc = storeDocument(get().project);
|
||||
const r = doc.loadFile(text);
|
||||
if (r.ok) set({ project: r.project, ...historyPatch(doc) });
|
||||
return r;
|
||||
},
|
||||
|
||||
// ── Zeichnungsebenen ───────────────────────────────────────────────────
|
||||
toggleLevelVisible: (id) =>
|
||||
applyChange((p) => patchItem(p, "drawingLevels", id, (z) => ({ ...z, visible: !z.visible }))),
|
||||
@@ -1894,18 +1899,16 @@ export function drawingVertices(
|
||||
* Bild-/PDF-Import). Direkt selektiert zurückgegeben, damit Griffe/Objekt-Info
|
||||
* sofort zum Verschieben/Skalieren bereitstehen.
|
||||
*/
|
||||
export function addImageDrawing2d(
|
||||
project: Project,
|
||||
export function imageDrawing2d(
|
||||
levelId: string,
|
||||
categoryCode: string,
|
||||
src: string,
|
||||
at: Vec2,
|
||||
widthM: number,
|
||||
heightM: number,
|
||||
): { project: Project; id: string } {
|
||||
const id = uniqueId("dr2d");
|
||||
const d: Drawing2D = {
|
||||
id,
|
||||
): Drawing2D {
|
||||
return {
|
||||
id: uniqueId("dr2d"),
|
||||
type: "drawing2d",
|
||||
levelId,
|
||||
categoryCode,
|
||||
@@ -1916,7 +1919,6 @@ export function addImageDrawing2d(
|
||||
src,
|
||||
},
|
||||
};
|
||||
return { project: { ...project, drawings2d: [...project.drawings2d, d] }, id };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -23,9 +23,13 @@ const DB_VERSION = 1;
|
||||
interface ProjectRecord {
|
||||
name: string;
|
||||
savedAt: number;
|
||||
project: Project;
|
||||
/** Projekt als Objekt oder als Datei-Text (Autosave, `serializeProject`). */
|
||||
project: StoredProject;
|
||||
}
|
||||
|
||||
/** Gespeicherter Inhalt: Projekt-Objekt oder Datei-Text. */
|
||||
export type StoredProject = Project | string;
|
||||
|
||||
/** `true`, sobald die Fehlmeldung „IndexedDB nicht verfügbar" geloggt wurde (nur einmal). */
|
||||
let warnedUnavailable = false;
|
||||
|
||||
@@ -88,7 +92,7 @@ function openDb(): Promise<IDBDatabase> {
|
||||
* Speichert ein Projekt unter `name` (überschreibt einen vorhandenen
|
||||
* Datensatz gleichen Namens). Ohne IndexedDB: no-op (wirft nicht).
|
||||
*/
|
||||
export async function saveProject(name: string, project: Project): Promise<void> {
|
||||
export async function saveProject(name: string, project: StoredProject): Promise<void> {
|
||||
if (!name) return;
|
||||
if (!isAvailable()) {
|
||||
warnUnavailableOnce();
|
||||
@@ -114,7 +118,7 @@ export async function saveProject(name: string, project: Project): Promise<void>
|
||||
* Lädt ein Projekt nach Namen. Liefert `null`, wenn es nicht existiert, die
|
||||
* Umgebung IndexedDB nicht unterstützt oder der Zugriff fehlschlägt.
|
||||
*/
|
||||
export async function loadProject(name: string): Promise<Project | null> {
|
||||
export async function loadProject(name: string): Promise<StoredProject | null> {
|
||||
if (!name) return null;
|
||||
if (!isAvailable()) {
|
||||
warnUnavailableOnce();
|
||||
@@ -135,7 +139,7 @@ export async function loadProject(name: string): Promise<Project | null> {
|
||||
}
|
||||
|
||||
/** Wie {@link loadProject}, mit Speicherzeitpunkt (ms seit Epoche). */
|
||||
export async function loadProjectRecord(name: string): Promise<{ project: Project; savedAt: number } | null> {
|
||||
export async function loadProjectRecord(name: string): Promise<{ project: StoredProject; savedAt: number } | null> {
|
||||
if (!name || !isAvailable()) return null;
|
||||
try {
|
||||
const db = await openDb();
|
||||
|
||||
@@ -14,7 +14,7 @@ beforeEach(() => {
|
||||
components: sampleProject.components.map((c, i) => (i === 0 ? { ...c, colorPenId: "p1" } : c)),
|
||||
walls: sampleProject.walls.map((w, i) => (i === 0 ? { ...w, colorPenId: "p1" } : w)),
|
||||
};
|
||||
st().setProject(p);
|
||||
st().loadProject(p);
|
||||
st().clearHistory();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
// setProject läuft über Ops (core/ops.ts): das Ergebnis muss dem gewünschten Projekt gleichen,
|
||||
// ungültige Änderungen werden zurückgerollt, Ops werden protokolliert und sind JSON-fähig.
|
||||
// setProject läuft über Ops (core/ops.ts, `opsMutation`): das Ergebnis muss dem gewünschten Projekt
|
||||
// gleichen, ungültige Änderungen werden zurückgerollt, Ops werden protokolliert und sind JSON-fähig.
|
||||
// Laden ([K4] S4): `loadProject`/`openProjectFile` ersetzen das Projekt im Kern und leeren den Verlauf.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getState } from "./appStore";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { emptyProject, sampleProject } from "../model/sampleProject";
|
||||
import { addItems, opsMutation, patchItem, serializeProject } from "../core";
|
||||
|
||||
const st = () => getState();
|
||||
|
||||
describe("setProject über CoreOps", () => {
|
||||
it("Änderung kommt unverändert an, Op wird protokolliert (JSON-fähig), Undo stellt zurück", () => {
|
||||
st().setProject(structuredClone(sampleProject));
|
||||
st().loadProject(structuredClone(sampleProject));
|
||||
const before = st().project;
|
||||
const w = before.walls[0];
|
||||
const wanted = { ...before, walls: [{ ...w, height: (w.height ?? 2.6) + 1 }, ...before.walls.slice(1)] };
|
||||
st().setProject(wanted);
|
||||
st().setProject(opsMutation((p) => patchItem(p, "walls", w.id, { height: (w.height ?? 2.6) + 1 })));
|
||||
expect(st().project).toEqual(wanted);
|
||||
const ops = st().recentOps();
|
||||
expect(ops.length).toBeGreaterThan(0);
|
||||
@@ -26,15 +28,56 @@ describe("setProject über CoreOps", () => {
|
||||
it("NaN-Änderung wird verworfen, Projekt bleibt, Undo-Stapel unverändert", () => {
|
||||
const before = st().project;
|
||||
const depth = st().undoDepth;
|
||||
const w = before.walls[0];
|
||||
st().setProject({ ...before, walls: [{ ...w, height: NaN }, ...before.walls.slice(1)] });
|
||||
st().setProject(opsMutation((p) => patchItem(p, "walls", p.walls[0].id, { height: NaN })));
|
||||
expect(st().project).toBe(before);
|
||||
expect(st().undoDepth).toBe(depth);
|
||||
});
|
||||
|
||||
it("doppelte ids beim Einfügen werden verworfen", () => {
|
||||
const before = st().project;
|
||||
st().setProject({ ...before, walls: [...before.walls, { ...before.walls[0] }] });
|
||||
st().setProject(opsMutation((p) => addItems("walls", [{ ...p.walls[0] }])));
|
||||
expect(st().project).toBe(before);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Projekt laden ([K4] S4)", () => {
|
||||
it("loadProject: Projekt als Ganzes, Verlauf leer, Leseansicht = übergebenes Objekt", () => {
|
||||
st().loadProject(structuredClone(sampleProject));
|
||||
st().setProject(opsMutation((p) => patchItem(p, "walls", p.walls[0].id, { height: 9 })));
|
||||
expect(st().canUndo).toBe(true);
|
||||
const next = structuredClone(emptyProject);
|
||||
st().loadProject(next);
|
||||
expect(st().project).toBe(next);
|
||||
expect(st().undoDepth).toBe(0);
|
||||
st().undo();
|
||||
expect(st().project).toBe(next);
|
||||
// Kern-Dokument = Leseansicht (Speichern aus dem Kern).
|
||||
expect(JSON.parse(serializeProject(st().project))).toEqual({ ...next, formatVersion: 2 });
|
||||
});
|
||||
|
||||
it("openProjectFile: Kern liest, migriert und lädt direkt; Verlauf leer; kaputte Datei ändert nichts", () => {
|
||||
st().loadProject(structuredClone(sampleProject));
|
||||
st().setProject(opsMutation((p) => patchItem(p, "walls", p.walls[0].id, { height: 9 })));
|
||||
const before = st().project;
|
||||
const bad = st().openProjectFile("{kaputt");
|
||||
expect(bad.ok).toBe(false);
|
||||
expect(st().project).toBe(before);
|
||||
expect(st().undoDepth).toBe(1);
|
||||
|
||||
const doors = [{ id: "TX", hostWallId: sampleProject.walls[0].id, position: 0.5, width: 0.9, height: 2.1 }];
|
||||
const old = { ...structuredClone(sampleProject), formatVersion: 1, doors };
|
||||
const r = st().openProjectFile(JSON.stringify(old));
|
||||
expect(r.ok && r.migratedFrom).toBe(1);
|
||||
expect(st().undoDepth).toBe(0);
|
||||
expect(st().redoDepth).toBe(0);
|
||||
expect(st().project.formatVersion).toBe(2);
|
||||
expect(st().project.openings?.some((o) => o.id === "TX" && o.kind === "door")).toBe(true);
|
||||
expect("doors" in st().project).toBe(false);
|
||||
// Danach normal weiterarbeiten: ein Schritt, Undo zurück auf den geladenen Stand.
|
||||
const loaded = st().project;
|
||||
st().setProject(opsMutation((p) => patchItem(p, "walls", p.walls[0].id, { height: 7 })));
|
||||
st().undo();
|
||||
expect(st().project).toEqual(loaded);
|
||||
expect(serializeProject(st().project)).toBe(JSON.stringify({ formatVersion: 2, ...loaded }, null, 2));
|
||||
});
|
||||
});
|
||||
@@ -9,12 +9,14 @@
|
||||
|
||||
import type { DragEvent } from "react";
|
||||
import { useRef } from "react";
|
||||
import { addImageDrawing2d } from "./projectSlice";
|
||||
import { imageDrawing2d } from "./projectSlice";
|
||||
import { addItems } from "../core";
|
||||
import type { CoreOp } from "../core/ops";
|
||||
import type { NotifyKind } from "./notifySlice";
|
||||
import { defaultImageSizeM, readImageFile } from "../io/imageAsset";
|
||||
import { rasterizePdfPages } from "../io/pdfImport";
|
||||
import { t } from "../i18n";
|
||||
import type { Project, Vec2 } from "../model/types";
|
||||
import type { Vec2 } from "../model/types";
|
||||
|
||||
/**
|
||||
* „Bild einfügen" (Werkzeug „image"): kein Klick-Platzieren (Datei-Auswahl ist
|
||||
@@ -23,10 +25,10 @@ import type { Project, Vec2 } from "../model/types";
|
||||
* (Griffe/Objekt-Info stehen direkt zum Verschieben/Skalieren bereit).
|
||||
*/
|
||||
export function useImageImportHandling(opts: {
|
||||
project: Project;
|
||||
activeLevelId: string;
|
||||
activeCategoryCode: string;
|
||||
setProject: (next: Project | ((p: Project) => Project)) => void;
|
||||
/** Änderung als Ops (Store `applyChange`): alle Bilder eines Einfügens = ein Undo-Schritt. */
|
||||
applyChange: (ops: readonly CoreOp[]) => void;
|
||||
notify: (message: string, kind?: NotifyKind) => void;
|
||||
setSelectedDrawingId: (id: string | null) => void;
|
||||
setSelectedWallIds: (ids: string[]) => void;
|
||||
@@ -44,10 +46,9 @@ export function useImageImportHandling(opts: {
|
||||
onImageOrPdfFileChosen: (file: File) => void;
|
||||
} {
|
||||
const {
|
||||
project,
|
||||
activeLevelId,
|
||||
activeCategoryCode,
|
||||
setProject,
|
||||
applyChange,
|
||||
notify,
|
||||
setSelectedDrawingId,
|
||||
setSelectedWallIds,
|
||||
@@ -65,17 +66,14 @@ export function useImageImportHandling(opts: {
|
||||
const insertImageDrawings = (
|
||||
assets: { src: string; naturalWidth: number; naturalHeight: number }[],
|
||||
) => {
|
||||
let cur = project;
|
||||
let lastId: string | null = null;
|
||||
assets.forEach((a, i) => {
|
||||
const drawings = assets.map((a, i) => {
|
||||
const { widthM, heightM } = defaultImageSizeM(a.naturalWidth, a.naturalHeight);
|
||||
const cascade = i * 0.3;
|
||||
const at: Vec2 = { x: -widthM / 2 + cascade, y: -heightM / 2 - cascade };
|
||||
const r = addImageDrawing2d(cur, activeLevelId, activeCategoryCode, a.src, at, widthM, heightM);
|
||||
cur = r.project;
|
||||
lastId = r.id;
|
||||
return imageDrawing2d(activeLevelId, activeCategoryCode, a.src, at, widthM, heightM);
|
||||
});
|
||||
setProject(cur);
|
||||
applyChange(addItems("drawings2d", drawings));
|
||||
const lastId = drawings.length ? drawings[drawings.length - 1].id : null;
|
||||
if (lastId) {
|
||||
setSelectedDrawingId(lastId);
|
||||
setSelectedWallIds([]);
|
||||
|
||||
@@ -18,7 +18,7 @@ import type { CopyMode, TransformOp } from "../tools/transform";
|
||||
import type { CommandEngine } from "../commands/engine";
|
||||
import type { CommandLineHandle } from "../ui/CommandLine";
|
||||
import type { Drawing2D, Project, Vec2 } from "../model/types";
|
||||
import type { CoreOp } from "../core";
|
||||
import type { CoreOp, ProjectMutation } from "../core";
|
||||
import { differenceDrawings, intersectionDrawings, unionDrawings } from "../editors/booleanOps";
|
||||
import type { BooleanResult } from "../editors/booleanOps";
|
||||
import { groupSelection, mergeMembership, ungroup, EMPTY_MEMBERSHIP } from "./groupActions";
|
||||
@@ -236,7 +236,7 @@ export function useActiveToolKeys(
|
||||
toolStateRef: MutableRefObject<ToolState>,
|
||||
setDraft: (draft: ToolDraft | null) => void,
|
||||
setActiveTool: (id: ToolId) => void,
|
||||
setProject: (next: Project | ((p: Project) => Project)) => void,
|
||||
setProject: (next: ProjectMutation) => void,
|
||||
): void {
|
||||
useEffect(() => {
|
||||
if (activeTool === "select") return;
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
import { opsMutation, patchItem, removeItems } from "../core";
|
||||
import type { Project, Vec2 } from "../model/types";
|
||||
import type { CategoryDisplayResolver } from "../core";
|
||||
import type { CategoryDisplayResolver, ProjectMutation } from "../core";
|
||||
import type { DisplayResolver } from "../viewport/Viewport3D";
|
||||
import type { PlanSelection, MarqueeSelection } from "../views/plan/PlanView";
|
||||
import type { Pick3dHit } from "../viewport/Wasm3DViewport";
|
||||
@@ -42,7 +42,7 @@ export function useMouseSelectionHandlers(opts: {
|
||||
/** `coalesceKey`: s. `projectSlice.ts` `setProject` — von `commitTextEdit`
|
||||
* genutzt, damit EIN Tipp-Vorgang EINEN Undo-Schritt erzeugt (wie beim
|
||||
* Griff-Ziehen), statt bei jedem Tastendruck einen neuen zu pushen. */
|
||||
setProject: (updater: (p: Project) => Project, coalesceKey?: string) => void;
|
||||
setProject: (updater: ProjectMutation, coalesceKey?: string) => void;
|
||||
activeLevelId: string;
|
||||
visibleCodes: Set<string>;
|
||||
categoryDisplay: CategoryDisplayResolver & DisplayResolver;
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
import { applyFillMode } from "./fillMode";
|
||||
import { addItems, fieldOps, opsMutation, patchItem, patchItems, removeItems, removeRoofHole, setFieldIfChanged, setRoofEdge } from "../core";
|
||||
import type { CoreOp } from "../core";
|
||||
import type { CoreOp, ProjectMutation } from "../core";
|
||||
import { useMemo, type RefObject } from "react";
|
||||
import type { DrawingLevel, Layout, Project } from "../model/types";
|
||||
import { resolvePenColor } from "../model/penSets";
|
||||
@@ -107,7 +107,7 @@ function captureCameraState(
|
||||
|
||||
export function usePanelHostBase(opts: {
|
||||
project: Project;
|
||||
setProject: (updater: (p: Project) => Project) => void;
|
||||
setProject: (updater: ProjectMutation) => void;
|
||||
/** Änderung direkt als Ops ([K4] S3), s. `ProjectSlice.applyChange`. */
|
||||
applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[]), coalesceKey?: string) => void;
|
||||
activeLevelId: string;
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
import { getState, useStore } from "./appStore";
|
||||
import type { NotifyKind } from "./notifySlice";
|
||||
import { parseProjectFile, parseProjectObject, serializeProject } from "../io/projectFormat";
|
||||
import { serializeProject } from "../io/projectFormat";
|
||||
import { AUTOSAVE_INTERVAL_MS, clearAutosave, createAutosaveTracker, readAutosave, writeAutosave } from "./autosave";
|
||||
import type { AutosaveRecovery } from "./autosave";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
@@ -44,6 +44,8 @@ import type { LockInfo } from "../native/projectFile";
|
||||
import { addRecentProject, removeRecentProject } from "./recentProjects";
|
||||
import { emptyProject, sampleProject } from "../model/sampleProject";
|
||||
import { flattenCategories } from "../model/types";
|
||||
import { addItems, fieldOps } from "../core";
|
||||
import type { CoreOp } from "../core/ops";
|
||||
import type { ContextObject, Drawing2D, Project, Vec2 } from "../model/types";
|
||||
import type { PlanViewHandle } from "../views/plan/PlanView";
|
||||
|
||||
@@ -140,11 +142,12 @@ const errorText = (err: unknown): string => (err instanceof Error ? err.message
|
||||
|
||||
|
||||
/**
|
||||
* Liest Projekt-Text über den gemeinsamen Format-Parser (Version, Migration, Toleranz) und
|
||||
* meldet Fehler sichtbar statt nur in der Konsole. `null` = nicht ladbar.
|
||||
* Öffnet Projekt-Text im Kern (`openProjectFile`: Version, Migration, Toleranz; direkt ins
|
||||
* Kern-Dokument, Verlauf leer) und meldet Fehler sichtbar statt nur in der Konsole. `null` = nicht
|
||||
* ladbar (das bisherige Projekt bleibt).
|
||||
*/
|
||||
function readProjectOrReport(content: string, notify: (msg: string, kind?: NotifyKind) => void): Project | null {
|
||||
const r = parseProjectFile(content);
|
||||
function openProjectOrReport(content: string, notify: (msg: string, kind?: NotifyKind) => void): Project | null {
|
||||
const r = getState().openProjectFile(content);
|
||||
if (!r.ok) {
|
||||
notify(`${t("project.open.failed")} ${r.error}`, "error");
|
||||
return null;
|
||||
@@ -155,7 +158,7 @@ function readProjectOrReport(content: string, notify: (msg: string, kind?: Notif
|
||||
|
||||
export function useProjectFileActions(
|
||||
project: Project,
|
||||
setProject: (next: Project | ((p: Project) => Project)) => void,
|
||||
applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[])) => void,
|
||||
setImportState: (next: ImportDialogState) => void,
|
||||
setExportSaveFormat: (format: ExportSaveFormat | null) => void,
|
||||
activeCategoryCode: string,
|
||||
@@ -172,13 +175,9 @@ export function useProjectFileActions(
|
||||
const projectFileInputRef = useRef<HTMLInputElement>(null);
|
||||
// Meldungen als Toast (window.alert ist im Tauri-WKWebView wirkungslos).
|
||||
const notify = useStore((s) => s.notify);
|
||||
// Ein anderes Projekt übernehmen (Neu, Vorlage, Öffnen, Wiederherstellen): ersetzt das Projekt und
|
||||
// leert den Undo-Verlauf — sonst führte Rückgängig über das Laden hinaus ins vorherige Projekt, und
|
||||
// jede Änderung dort verwarf den Redo-Stapel.
|
||||
const replaceProject = (next: Project) => {
|
||||
setProject(next);
|
||||
getState().clearHistory();
|
||||
};
|
||||
// Ein anderes Projekt übernehmen (Neu, Vorlage, Öffnen, Wiederherstellen) lädt es im Kern als Ganzes
|
||||
// (`loadProject`/`openProjectFile`, [K4] S4) und leert den Undo-Verlauf — sonst führte Rückgängig über
|
||||
// das Laden hinaus ins vorherige Projekt, und jede Änderung dort verwarf den Redo-Stapel.
|
||||
// Verstecktes Datei-Input für „Neu aus Vorlage" (Datei wählen) — derselbe
|
||||
// Browser-Fallback wie `projectFileInputRef`, nur mit `.obpt`-Filter.
|
||||
const projectTemplateFileInputRef = useRef<HTMLInputElement>(null);
|
||||
@@ -231,22 +230,20 @@ export function useProjectFileActions(
|
||||
const id = window.setInterval(() => {
|
||||
const p = projectRef.current;
|
||||
if (!autosaveTracker.shouldWrite(p, lastSavedProjectRef.current)) return;
|
||||
void writeAutosave(openedProjectPathRef.current, p);
|
||||
void writeAutosave(openedProjectPathRef.current, serializeProject(p));
|
||||
}, AUTOSAVE_INTERVAL_MS);
|
||||
return () => window.clearInterval(id);
|
||||
}, []);
|
||||
const offerRecovery = (path: string | null) => {
|
||||
void readAutosave(path).then((r) => {
|
||||
if (r) setRecovery({ path, project: r.project, savedAt: r.savedAt });
|
||||
if (r) setRecovery({ path, text: r.text, savedAt: r.savedAt });
|
||||
});
|
||||
};
|
||||
// Start: Kopie eines nie gespeicherten Projekts aus der letzten Sitzung?
|
||||
useEffect(() => offerRecovery(null), []);
|
||||
const onRecoverRestore = () => {
|
||||
if (!recovery) return;
|
||||
const parsed = parseProjectObject(recovery.project);
|
||||
if (parsed.ok) replaceProject(parsed.project); // bleibt „ungespeichert" bis zum Speichern
|
||||
else notify(`${t("project.open.failed")} ${parsed.error}`, "error");
|
||||
openProjectOrReport(recovery.text, notify); // bleibt „ungespeichert" bis zum Speichern
|
||||
setRecovery(null);
|
||||
};
|
||||
const onRecoverDiscard = () => {
|
||||
@@ -450,29 +447,23 @@ export function useProjectFileActions(
|
||||
// `guardDiscard`: bei ungespeicherten Änderungen erst der Dialog, s. o.
|
||||
const onNewProject = () => guardDiscard(() => {
|
||||
releaseCurrentProjectLock();
|
||||
replaceProject(emptyProject);
|
||||
getState().loadProject(emptyProject);
|
||||
lastSavedProjectRef.current = emptyProject;
|
||||
});
|
||||
|
||||
// Übernimmt ein neues, noch UNGESPEICHERTES Projekt aus Vorlagen-Inhalt
|
||||
// (Musterhaus ODER eine gewählte `.obpt`-Datei): grobe Form-Prüfung wie beim
|
||||
// normalen Öffnen, aber bewusst OHNE Pfad/Lock zu setzen — die Vorlage
|
||||
// bleibt unangetastet, das nächste „Speichern" fragt nach einem neuen Ort.
|
||||
// Ersetzt ebenfalls das bisherige Projekt → über `guardDiscard`.
|
||||
const applyTemplateContent = (content: string): boolean => {
|
||||
try {
|
||||
const parsed = readProjectOrReport(content, notify);
|
||||
if (!parsed) return false;
|
||||
guardDiscard(() => {
|
||||
releaseCurrentProjectLock();
|
||||
replaceProject(parsed);
|
||||
lastSavedProjectRef.current = parsed;
|
||||
});
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error("Vorlage konnte nicht geladen werden:", err);
|
||||
return false;
|
||||
}
|
||||
// (eine gewählte `.obpt`-Datei): Prüfung wie beim normalen Öffnen, aber
|
||||
// bewusst OHNE Pfad/Lock zu setzen — die Vorlage bleibt unangetastet, das
|
||||
// nächste „Speichern" fragt nach einem neuen Ort. Ersetzt ebenfalls das
|
||||
// bisherige Projekt → über `guardDiscard` (der Kern lädt erst danach; eine
|
||||
// kaputte Datei lässt das bisherige Projekt stehen).
|
||||
const applyTemplateContent = (content: string): void => {
|
||||
guardDiscard(() => {
|
||||
const loaded = openProjectOrReport(content, notify);
|
||||
if (!loaded) return;
|
||||
releaseCurrentProjectLock();
|
||||
lastSavedProjectRef.current = loaded;
|
||||
});
|
||||
};
|
||||
// „Neu aus Vorlage: Musterhaus" — das eingebaute Demo-Haus (model/sampleProject.ts)
|
||||
// als Start eines neuen Projekts. `structuredClone`, damit spätere Bearbeitung
|
||||
@@ -481,7 +472,7 @@ export function useProjectFileActions(
|
||||
const onNewProjectFromSample = () => guardDiscard(() => {
|
||||
releaseCurrentProjectLock();
|
||||
const next = structuredClone(sampleProject);
|
||||
replaceProject(next);
|
||||
getState().loadProject(next);
|
||||
lastSavedProjectRef.current = next;
|
||||
});
|
||||
// „Neu aus Vorlage: Datei wählen…" — native `.obpt`-Dialog unter Tauri, sonst
|
||||
@@ -521,24 +512,19 @@ export function useProjectFileActions(
|
||||
// die Form, gibt einen evtl. vorher gehaltenen Lock frei und merkt sich Pfad
|
||||
// + ob WIR den Schreib-Lock für die neue Datei halten.
|
||||
const applyOpenedProjectFile = (path: string, content: string, lockOwned: boolean) => {
|
||||
try {
|
||||
const parsed = readProjectOrReport(content, notify);
|
||||
if (!parsed) {
|
||||
guardDiscard(() => {
|
||||
const loaded = openProjectOrReport(content, notify);
|
||||
if (!loaded) {
|
||||
if (lockOwned) void releaseProjectLock(path);
|
||||
return;
|
||||
}
|
||||
guardDiscard(() => {
|
||||
releaseCurrentProjectLock();
|
||||
replaceProject(parsed);
|
||||
lastSavedProjectRef.current = parsed;
|
||||
openedProjectPathRef.current = path;
|
||||
projectLockOwnedRef.current = lockOwned;
|
||||
addRecentProject(path, parsed.name || "modell");
|
||||
offerRecovery(path);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("Projekt-Import fehlgeschlagen:", err);
|
||||
}
|
||||
releaseCurrentProjectLock();
|
||||
lastSavedProjectRef.current = loaded;
|
||||
openedProjectPathRef.current = path;
|
||||
projectLockOwnedRef.current = lockOwned;
|
||||
addRecentProject(path, loaded.name || "modell");
|
||||
offerRecovery(path);
|
||||
});
|
||||
};
|
||||
// Öffnen unter Tauri: nativer Dialog (echter Pfad) → Lock versuchen. Klappt
|
||||
// er → Projekt übernehmen. Schon gesperrt → Konflikt-Dialog (kein
|
||||
@@ -652,19 +638,15 @@ export function useProjectFileActions(
|
||||
const onProjectFileChosen = (file: File) => {
|
||||
const r = new FileReader();
|
||||
r.onload = () => {
|
||||
try {
|
||||
const parsed = readProjectOrReport(String(r.result ?? ""), notify);
|
||||
if (!parsed) return;
|
||||
// Browser-Pfad hat keinen echten Dateipfad → kein Lock für die neue
|
||||
// Datei, aber ein evtl. vorher (unter Tauri) gehaltener Lock wird frei.
|
||||
guardDiscard(() => {
|
||||
releaseCurrentProjectLock();
|
||||
replaceProject(parsed);
|
||||
lastSavedProjectRef.current = parsed;
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("Projekt-Import fehlgeschlagen:", err);
|
||||
}
|
||||
const content = String(r.result ?? "");
|
||||
// Browser-Pfad hat keinen echten Dateipfad → kein Lock für die neue
|
||||
// Datei, aber ein evtl. vorher (unter Tauri) gehaltener Lock wird frei.
|
||||
guardDiscard(() => {
|
||||
const loaded = openProjectOrReport(content, notify);
|
||||
if (!loaded) return;
|
||||
releaseCurrentProjectLock();
|
||||
lastSavedProjectRef.current = loaded;
|
||||
});
|
||||
};
|
||||
r.readAsText(file);
|
||||
};
|
||||
@@ -675,10 +657,15 @@ export function useProjectFileActions(
|
||||
// Bestätigte Import-Entscheidung ausführen: ggf. neue Zeichnung anlegen, die
|
||||
// 2D-Konturen als Drawing2D anhängen, optional die Meshes als Kontext
|
||||
// übernehmen. Reihenfolge: erst Ebene (echte ID), dann Drawings/Kontext.
|
||||
// Alles als Ops in EINER Gruppe ([K4] S3): ein Import = ein Undo-Schritt.
|
||||
const runImport = (decision: ImportDecision) => {
|
||||
// Hinweis bleibt, bis PlanView den neuen Plan gezeichnet hat (endBusyAfterPaint):
|
||||
// der Aufbau nach dem Einhängen blockiert noch einmal mehrere Sekunden.
|
||||
beginBusy(t("busy.import"));
|
||||
getState().groupChanges(() => runImportSteps(decision));
|
||||
setImportState(null);
|
||||
};
|
||||
const runImportSteps = (decision: ImportDecision) => {
|
||||
const levelId =
|
||||
decision.target.kind === "new"
|
||||
? addDrawingLevel(decision.target.name)
|
||||
@@ -699,17 +686,14 @@ export function useProjectFileActions(
|
||||
codeByLayer = plan.codeByLayer;
|
||||
if (plan.parent) {
|
||||
const parent = plan.parent;
|
||||
setProject((p) => ({ ...p, layers: [...p.layers, parent] }));
|
||||
applyChange((p) => fieldOps(p, "layers", [...p.layers, parent]));
|
||||
}
|
||||
}
|
||||
// PDF-Strichmuster ([76]): passenden Linienstil nehmen oder Strichmuster-Stil anlegen (vor den Zeichnungen).
|
||||
const dashPlan = planDashLineStyles(decision.parsed.layerDashes, project.lineStyles);
|
||||
if (dashPlan.created.length) {
|
||||
const created = dashPlan.created;
|
||||
setProject((p) => ({
|
||||
...p,
|
||||
lineStyles: [...p.lineStyles, ...created.filter((c) => !p.lineStyles.some((l) => l.id === c.id))],
|
||||
}));
|
||||
applyChange((p) => addItems("lineStyles", created.filter((c) => !p.lineStyles.some((l) => l.id === c.id))));
|
||||
}
|
||||
let drawings = buildDrawings(
|
||||
decision,
|
||||
@@ -737,7 +721,6 @@ export function useProjectFileActions(
|
||||
}
|
||||
// Auf die Ziel-Ebene wechseln, damit die importierte Geometrie sichtbar ist.
|
||||
setActiveLevelId(levelId);
|
||||
setImportState(null);
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
+3
-2
@@ -6,6 +6,7 @@
|
||||
// bleibt abgeleitet. Bezeichner englisch, UI-Text via t().
|
||||
|
||||
import type { DrawingLevel, Project, Vec2 } from "../model/types";
|
||||
import type { ProjectMutation } from "../core";
|
||||
|
||||
/** Werkzeug-Identität. */
|
||||
export type ToolId =
|
||||
@@ -274,8 +275,8 @@ export interface ToolDraft {
|
||||
export interface ToolResult {
|
||||
/** Neuer Vorschau-Zustand; null = nichts zu zeigen. */
|
||||
draft: ToolDraft | null;
|
||||
/** Bei Abschluss: Mutation, die App über setProject anwendet. */
|
||||
commit?: (p: Project) => Project;
|
||||
/** Bei Abschluss: Änderung mit mitgeführten Ops (`opsMutation`), die App über setProject anwendet. */
|
||||
commit?: ProjectMutation;
|
||||
/** true → Werkzeug ist fertig und kehrt in seinen Ruhezustand zurück. */
|
||||
done?: boolean;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user