[K4] Ebenen-/Geschoss-Logik im Kern: Kategorien-Baum, Import-Kategorien, Auswahl-Codes, recomputeFloorElevations
layers.rs/levels.rs (Rechnung auf serde_json::Value), zustandslose Bindungen, TS-Fassade model/layers.ts; TS-Rechnung in types.ts, projectSlice, selectionLayers, selectionInfo, dxfToDrawings, contextCategories gelöscht. Duplikat einer Unterkategorie geht nicht mehr verloren.
This commit is contained in:
21 files changed
+857
-338
No files matched your search
@@ -379,7 +379,7 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
Import (DXF-Layer/Linienstile in `runImport`, Bilder einfügen in `useImportHandling`, IFC-Bauteile in `App.tsx` `runIfcImport`),
|
||||
das Ressourcen-Fenster (Fremd-Synchronisation) und das CLI (`cli/main.ts`: ganze Dateien, Projekt → Projekt-Hilfen); dazu der
|
||||
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
|
||||
Offen: 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,
|
||||
@@ -402,9 +402,23 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
`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].
|
||||
Gruppe), 16000 Vergleiche gleich der alten TS-Fassung.
|
||||
**Ebenen- und Geschoss-Logik im Kern (29.10.):** `layers.rs` (Kategorien-Baum: abflachen, suchen, sichtbare Codes,
|
||||
umschalten, Sichtbarkeit nach Codes, ändern, Unterkategorie, Duplikat, löschen, `nextFreeCode`, Isolieren/Ausblenden der
|
||||
Auswahl, Import-Kategorien `planImportCategories`, Kategorie-Codes der Auswahl über die Abfrage `selectionCategoryCodes`),
|
||||
`levels.rs` (`recomputeFloorElevations`); Rechnung auf `serde_json::Value` (verlustfrei), zustandslose Bindungen
|
||||
`layers_call`/`levels_recompute_elevations` (`web/layers.rs`), TS-Fassade `model/layers.ts` (abgeflachter Baum je Baum-Array
|
||||
gemerkt: `getLayerCategory` je Bauteil bleibt billig). `model/types.ts` re-exportiert die alten Namen; die TS-Rechnung in
|
||||
`types.ts`, `projectSlice.ts` (Baum-Helfer), `selectionLayers.ts`, `selectionInfo.ts`, `dxfToDrawings.ts`,
|
||||
`contextCategories.ts` ist gelöscht. `sampleProject` trägt die gestapelten Höhen ausgeschrieben (das Modul wird vor dem
|
||||
Laden des Kerns ausgewertet; Test dagegen). Gleichheit (einmalig, Test gelöscht): 4000 Zufallsbäume (doppelte Codes,
|
||||
nichtnumerische/negative Codes, fehlende Kinder) × 14 Rechnungen, 3000 Geschoss-Listen, 1500 Import-Pläne,
|
||||
600 Auswahl-Abfragen gleich der alten TS-Fassung. Einzige Abweichung, gewollt: Das Duplikat einer Unterkategorie
|
||||
(`insertAfterCode`) ging in TS verloren (die Ebene mit dem Ziel wurde übersprungen), jetzt steht es hinter dem Original.
|
||||
Offen: vertikale Ausdehnungen (`model/wall.ts`: `wallVerticalExtent` …, Kern hat `model/helpers.rs` schon — Aufrufer in
|
||||
`toSection`/`voids`/`geometry/opening`/Viewport fallen mit dem Plan-Port bzw. brauchen eine Abfrage je Bauteil),
|
||||
Stift-Referenzen im Kategorien-Baum beim Löschen eines Stifts (`projectSlice`, Stiftsatz-Logik), Layout-/Ordnerbäume
|
||||
(`layoutModel.ts`), Parametrik-Regeln (`parametricWalls.ts`), Stiftsätze (`penSets.ts`); 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
|
||||
|
||||
@@ -0,0 +1,449 @@
|
||||
//! Ebenen/Kategorien-Baum ([K4] S3, vorher `model/types.ts`, `state/projectSlice.ts`,
|
||||
//! `state/selectionLayers.ts`, `io/dxfToDrawings.ts`): Abflachen, Nachschlagen, Sichtbarkeit,
|
||||
//! Isolieren, Baum-Umbauten (Umschalten, Ändern, Unterkategorie, Duplikat, Löschen) und freie Codes.
|
||||
//! Die Rechnung läuft auf `serde_json::Value` (verlustfrei: unbekannte Felder und Reihenfolge der Schlüssel
|
||||
//! bleiben), Reihenfolgen und Sonderfälle wie in der TS-Fassung (doppelte Codes: es greifen alle Treffer
|
||||
//! bzw. der erste, fehlende Felder = JS-`undefined`).
|
||||
|
||||
use crate::model::Project;
|
||||
use serde_json::{Map, Value};
|
||||
use std::collections::HashSet;
|
||||
|
||||
type Tree = Vec<Value>;
|
||||
|
||||
/// JS-Wahrheitswert eines JSON-Werts (`if (c.visible)`).
|
||||
fn truthy(v: Option<&Value>) -> bool {
|
||||
match v {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0 && !f.is_nan()),
|
||||
Some(Value::String(s)) => !s.is_empty(),
|
||||
Some(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn code_of(c: &Value) -> Option<&str> {
|
||||
c.get("code").and_then(Value::as_str)
|
||||
}
|
||||
|
||||
fn children(c: &Value) -> Option<&Tree> {
|
||||
c.get("children").and_then(Value::as_array)
|
||||
}
|
||||
|
||||
/// Kopie von `c` mit gesetztem Schlüssel (`{...c, key: v}`: vorhandener Schlüssel behält seine Stelle).
|
||||
fn with(c: &Value, key: &str, v: Value) -> Value {
|
||||
let mut m: Map<String, Value> = c.as_object().cloned().unwrap_or_default();
|
||||
m.insert(key.to_string(), v);
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
/// Flacht den Baum (Tiefensuche, Eltern vor Kindern) ab (`flattenCategories`).
|
||||
pub fn flatten(cats: &[Value]) -> Vec<&Value> {
|
||||
fn walk<'a>(list: &'a [Value], out: &mut Vec<&'a Value>) {
|
||||
for c in list {
|
||||
out.push(c);
|
||||
if let Some(ch) = children(c) {
|
||||
walk(ch, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(cats, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Erste Kategorie mit `code` im Baum (`findCategory`, `getLayerCategory`).
|
||||
pub fn find<'a>(cats: &'a [Value], code: &str) -> Option<&'a Value> {
|
||||
flatten(cats).into_iter().find(|c| code_of(c) == Some(code))
|
||||
}
|
||||
|
||||
/// Codes aller sichtbaren Kategorien in Baumreihenfolge (`collectVisibleCodes`, ohne Doppelungen).
|
||||
pub fn visible_codes(cats: &[Value]) -> Vec<String> {
|
||||
let mut seen = HashSet::new();
|
||||
flatten(cats)
|
||||
.into_iter()
|
||||
.filter(|c| truthy(c.get("visible")))
|
||||
.filter_map(|c| code_of(c).map(str::to_string))
|
||||
.filter(|c| seen.insert(c.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Wendet `f` auf jede Kategorie an (Kinder zuerst); `None` = nichts geändert (`mapCategories`).
|
||||
fn map_cats(cats: &[Value], f: &dyn Fn(&Value) -> Option<Value>) -> Option<Tree> {
|
||||
let mut changed = false;
|
||||
let next: Tree = cats
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let base = match children(c).and_then(|ch| map_cats(ch, f)) {
|
||||
Some(ch) => {
|
||||
changed = true;
|
||||
with(c, "children", Value::Array(ch))
|
||||
}
|
||||
None => c.clone(),
|
||||
};
|
||||
match f(&base) {
|
||||
Some(out) => {
|
||||
changed = true;
|
||||
out
|
||||
}
|
||||
None => base,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
changed.then_some(next)
|
||||
}
|
||||
|
||||
/// `visible` genau für `codes` setzen; `None` = nichts zu tun (`setCategoriesVisible`).
|
||||
pub fn set_visible(cats: &[Value], codes: &HashSet<String>, visible: bool) -> Option<Tree> {
|
||||
map_cats(cats, &|c| {
|
||||
let hit = code_of(c).is_some_and(|k| codes.contains(k));
|
||||
(hit && c.get("visible") != Some(&Value::Bool(visible))).then(|| with(c, "visible", Value::Bool(visible)))
|
||||
})
|
||||
}
|
||||
|
||||
/// Nur `codes` sichtbar, alle übrigen aus; `None` = nichts zu tun (`isolateCategories`).
|
||||
pub fn isolate(cats: &[Value], codes: &HashSet<String>) -> Option<Tree> {
|
||||
map_cats(cats, &|c| {
|
||||
let want = code_of(c).is_some_and(|k| codes.contains(k));
|
||||
(c.get("visible") != Some(&Value::Bool(want))).then(|| with(c, "visible", Value::Bool(want)))
|
||||
})
|
||||
}
|
||||
|
||||
/// Anzeigenamen zu den Codes; unbekannter Code → der Code selbst (`categoryNames`).
|
||||
pub fn names(cats: &[Value], codes: &[String]) -> Vec<String> {
|
||||
let all = flatten(cats);
|
||||
codes
|
||||
.iter()
|
||||
.map(|code| {
|
||||
all.iter()
|
||||
.find(|c| code_of(c) == Some(code))
|
||||
.and_then(|c| c.get("name").and_then(Value::as_str))
|
||||
.map_or_else(|| code.clone(), str::to_string)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Sichtbarkeit der Kategorie `code` umschalten; trifft jede Kategorie mit dem Code, ohne unter einem
|
||||
/// Treffer weiterzusuchen (`toggleCategoryByCode`).
|
||||
pub fn toggle(cats: &[Value], code: &str) -> Tree {
|
||||
cats.iter()
|
||||
.map(|c| {
|
||||
if code_of(c) == Some(code) {
|
||||
return with(c, "visible", Value::Bool(!truthy(c.get("visible"))));
|
||||
}
|
||||
match children(c) {
|
||||
Some(ch) => with(c, "children", Value::Array(toggle(ch, code))),
|
||||
None => c.clone(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `visible`-Flags gemäß `codes` (Code → sichtbar) setzen, unbekannte Codes ignorieren (`applyVisibilityByCode`).
|
||||
pub fn apply_visibility(cats: &[Value], codes: &Map<String, Value>) -> Tree {
|
||||
cats.iter()
|
||||
.map(|c| {
|
||||
let next = match code_of(c).and_then(|k| codes.get(k)) {
|
||||
Some(v) => with(c, "visible", v.clone()),
|
||||
None => c.clone(),
|
||||
};
|
||||
match children(&next) {
|
||||
Some(ch) => with(&next, "children", Value::Array(apply_visibility(ch, codes))),
|
||||
None => next,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Kategorie `code` ändern (`{...c, ...patch}`; ein `null` im Patch entfernt das Feld = JS-`undefined`).
|
||||
pub fn patch(cats: &[Value], code: &str, patch_obj: &Map<String, Value>) -> Tree {
|
||||
cats.iter()
|
||||
.map(|c| {
|
||||
if code_of(c) == Some(code) {
|
||||
let mut m = c.as_object().cloned().unwrap_or_default();
|
||||
for (k, v) in patch_obj {
|
||||
if v.is_null() {
|
||||
m.shift_remove(k);
|
||||
} else {
|
||||
m.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
return Value::Object(m);
|
||||
}
|
||||
match children(c) {
|
||||
Some(ch) => with(c, "children", Value::Array(patch(ch, code, patch_obj))),
|
||||
None => c.clone(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `child` als letztes Kind der Kategorie `parent_code` anhängen (`addChildByCode`).
|
||||
pub fn add_child(cats: &[Value], parent_code: &str, child: &Value) -> Tree {
|
||||
cats.iter()
|
||||
.map(|c| {
|
||||
if code_of(c) == Some(parent_code) {
|
||||
let mut ch = children(c).cloned().unwrap_or_default();
|
||||
ch.push(child.clone());
|
||||
return with(c, "children", Value::Array(ch));
|
||||
}
|
||||
match children(c) {
|
||||
Some(ch) => with(c, "children", Value::Array(add_child(ch, parent_code, child))),
|
||||
None => c.clone(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `clone` direkt nach der Kategorie `code` auf derselben Ebene einfügen (`insertAfterCode`). Anders als die
|
||||
/// TS-Fassung (sie übersprang genau die Ebene, die das Ziel enthält, und verlor so das Duplikat einer
|
||||
/// Unterkategorie) wird in jede Kinderliste hinabgestiegen.
|
||||
pub fn insert_after(cats: &[Value], code: &str, clone: &Value) -> Tree {
|
||||
let mut out = Vec::with_capacity(cats.len() + 1);
|
||||
for c in cats {
|
||||
let next = match children(c) {
|
||||
Some(ch) => with(c, "children", Value::Array(insert_after(ch, code, clone))),
|
||||
None => c.clone(),
|
||||
};
|
||||
out.push(next);
|
||||
if code_of(c) == Some(code) {
|
||||
out.push(clone.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Kategorie `code` samt Kindern entfernen (`removeByCode`).
|
||||
pub fn remove(cats: &[Value], code: &str) -> Tree {
|
||||
cats.iter()
|
||||
.filter(|c| code_of(c) != Some(code))
|
||||
.map(|c| match children(c) {
|
||||
Some(ch) => with(c, "children", Value::Array(remove(ch, code))),
|
||||
None => c.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// JS-`parseInt(s, 10)`: führende Leerzeichen, Vorzeichen, Ziffern bis zum ersten Fremdzeichen; sonst `None` (NaN).
|
||||
pub fn js_parse_int(s: &str) -> Option<f64> {
|
||||
let t = s.trim_start_matches(|c: char| c.is_whitespace() || c == '\u{feff}');
|
||||
let (neg, rest) = match t.strip_prefix('-') {
|
||||
Some(r) => (true, r),
|
||||
None => (false, t.strip_prefix('+').unwrap_or(t)),
|
||||
};
|
||||
let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
|
||||
if digits.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let v: f64 = digits.parse().ok()?;
|
||||
Some(if neg { -v } else { v })
|
||||
}
|
||||
|
||||
/// Zweistellig aufgefüllte Zahl (`String(i).padStart(2, "0")`).
|
||||
fn pad2(i: f64) -> String {
|
||||
let s = format!("{i}");
|
||||
if s.len() < 2 {
|
||||
format!("0{s}")
|
||||
} else {
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
/// Alle Codes des Baums als Menge.
|
||||
fn used_codes(cats: &[Value]) -> HashSet<String> {
|
||||
flatten(cats).into_iter().filter_map(|c| code_of(c).map(str::to_string)).collect()
|
||||
}
|
||||
|
||||
/// Höchster numerischer Code (`Math.max(...nums)`), `None` ohne numerische Codes.
|
||||
fn max_numeric(used: &HashSet<String>) -> Option<f64> {
|
||||
used.iter().filter_map(|c| js_parse_int(c)).fold(None, |m, n| Some(m.map_or(n, |m: f64| m.max(n))))
|
||||
}
|
||||
|
||||
/// Nächster freier zweistelliger Code über den ganzen Baum (`nextFreeCode`); ab 999 `now_ms` als Text.
|
||||
pub fn next_free_code(cats: &[Value], now_ms: f64) -> String {
|
||||
let used = used_codes(cats);
|
||||
let start = max_numeric(&used).unwrap_or(0.0);
|
||||
let mut i = start + 1.0;
|
||||
while i < 1000.0 {
|
||||
let c = pad2(i);
|
||||
if !used.contains(&c) {
|
||||
return c;
|
||||
}
|
||||
i += 1.0;
|
||||
}
|
||||
format!("{}", now_ms.trunc())
|
||||
}
|
||||
|
||||
/// Kategorien für Import-Layer ohne gleichnamige Kategorie (`planImportCategories`): die neuen
|
||||
/// Unterkategorien, der Code der (noch anzulegenden) Elternkategorie — leer, wenn keine neue Kategorie
|
||||
/// nötig ist — und das Mapping Layer-Name → Code für alle Layer.
|
||||
pub struct ImportPlan {
|
||||
pub children: Vec<Value>,
|
||||
pub parent_code: String,
|
||||
pub code_by_layer: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
pub fn plan_import(layer_names: &[String], existing: &[Value], colors: &Map<String, Value>, weights: &Map<String, Value>) -> ImportPlan {
|
||||
let mut used = used_codes(existing);
|
||||
// Namensvergleich ohne Gross-/Kleinschreibung; spätere gleichnamige Kategorien überschreiben frühere.
|
||||
let mut by_name: std::collections::HashMap<String, String> = std::collections::HashMap::new();
|
||||
for c in flatten(existing) {
|
||||
if let (Some(code), Some(name)) = (code_of(c), c.get("name").and_then(Value::as_str)) {
|
||||
by_name.insert(name.to_lowercase(), code.to_string());
|
||||
}
|
||||
}
|
||||
let mut next = max_numeric(&used).map_or(0.0, |m| m.max(0.0)) + 1.0;
|
||||
let mut allocate = |used: &mut HashSet<String>| -> String {
|
||||
while used.contains(&pad2(next)) {
|
||||
next += 1.0;
|
||||
}
|
||||
let code = pad2(next);
|
||||
next += 1.0;
|
||||
used.insert(code.clone());
|
||||
code
|
||||
};
|
||||
let mut code_by_layer: Vec<(String, String)> = Vec::new();
|
||||
let mut children = Vec::new();
|
||||
for name in layer_names {
|
||||
let key = name.to_lowercase();
|
||||
if let Some(known) = by_name.get(&key) {
|
||||
code_by_layer.push((name.clone(), known.clone()));
|
||||
continue;
|
||||
}
|
||||
let code = allocate(&mut used);
|
||||
by_name.insert(key, code.clone());
|
||||
code_by_layer.push((name.clone(), code.clone()));
|
||||
let color = colors.get(name).filter(|v| !v.is_null()).cloned().unwrap_or_else(|| Value::String("#707078".into()));
|
||||
let lw = weights.get(name).filter(|v| !v.is_null()).cloned().unwrap_or_else(|| serde_json::json!(0.18));
|
||||
children.push(serde_json::json!({"code": code, "name": name, "color": color, "lw": lw, "visible": true, "locked": false}));
|
||||
}
|
||||
let parent_code = if children.is_empty() { String::new() } else { allocate(&mut used) };
|
||||
ImportPlan { children, parent_code, code_by_layer }
|
||||
}
|
||||
|
||||
/// Auswahl nach Elementart (`SelectionMembers`: ids je Art).
|
||||
#[derive(serde::Deserialize, Default)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct SelectionMembers {
|
||||
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>,
|
||||
}
|
||||
|
||||
/// Kategorie-Codes aller gewählten Objekte (eindeutig, in Fundreihenfolge; leere Codes zählen nicht).
|
||||
pub fn selection_category_codes(p: &Project, sel: &SelectionMembers) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
let mut seen: HashSet<String> = HashSet::new();
|
||||
let mut scan = |ids: &[String], items: &mut dyn Iterator<Item = (&str, &str)>| {
|
||||
if ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
let wanted: HashSet<&str> = ids.iter().map(String::as_str).collect();
|
||||
for (id, code) in items {
|
||||
if !code.is_empty() && wanted.contains(id) && seen.insert(code.to_string()) {
|
||||
out.push(code.to_string());
|
||||
}
|
||||
}
|
||||
};
|
||||
scan(&sel.wall_ids, &mut p.walls.iter().map(|o| (o.id.as_str(), o.category_code.as_str())));
|
||||
scan(&sel.drawing_ids, &mut p.drawings2d.iter().map(|o| (o.id.as_str(), o.category_code.as_str())));
|
||||
scan(&sel.ceiling_ids, &mut p.ceilings.iter().flatten().map(|o| (o.id.as_str(), o.category_code.as_str())));
|
||||
scan(&sel.room_ids, &mut p.rooms.iter().flatten().map(|o| (o.id.as_str(), o.category_code.as_str())));
|
||||
scan(&sel.stair_ids, &mut p.stairs.iter().flatten().map(|o| (o.id.as_str(), o.category_code.as_str())));
|
||||
scan(&sel.column_ids, &mut p.columns.iter().flatten().map(|o| (o.id.as_str(), o.category_code.as_str())));
|
||||
scan(&sel.roof_ids, &mut p.roofs.iter().flatten().map(|o| (o.id.as_str(), o.category_code.as_str())));
|
||||
scan(&sel.opening_ids, &mut p.openings.iter().flatten().map(|o| (o.id.as_str(), o.category_code.as_str())));
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn cat(code: &str, name: &str, visible: bool, ch: Option<Vec<Value>>) -> Value {
|
||||
let mut v = json!({"code": code, "name": name, "color": "#000", "lw": 0.2, "visible": visible, "locked": false});
|
||||
if let Some(ch) = ch {
|
||||
v["children"] = Value::Array(ch);
|
||||
}
|
||||
v
|
||||
}
|
||||
fn tree() -> Tree {
|
||||
vec![cat("20", "Wände", true, None), cat("05", "Import", true, Some(vec![cat("100", "01421", true, None), cat("101", "01847", true, None)]))]
|
||||
}
|
||||
fn set(codes: &[&str]) -> HashSet<String> {
|
||||
codes.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
fn vis(t: &[Value]) -> Vec<(String, bool)> {
|
||||
flatten(t).iter().map(|c| (code_of(c).unwrap().to_string(), c["visible"].as_bool().unwrap())).collect()
|
||||
}
|
||||
fn codes_of(t: &[Value]) -> Vec<String> {
|
||||
flatten(t).iter().map(|c| code_of(c).unwrap().to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn abflachen_und_finden() {
|
||||
let t = tree();
|
||||
assert_eq!(codes_of(&t), ["20", "05", "100", "101"]);
|
||||
assert_eq!(find(&t, "101").unwrap()["name"], "01847");
|
||||
assert!(find(&t, "999").is_none());
|
||||
assert_eq!(visible_codes(&t), ["20", "05", "100", "101"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sichtbarkeit_isolieren_und_unveraendert() {
|
||||
let t = tree();
|
||||
let n = set_visible(&t, &set(&["100"]), false).unwrap();
|
||||
assert_eq!(vis(&n), [("20".into(), true), ("05".into(), true), ("100".into(), false), ("101".into(), true)]);
|
||||
assert!(set_visible(&t, &set(&["100"]), true).is_none());
|
||||
let iso = isolate(&t, &set(&["101"])).unwrap();
|
||||
assert_eq!(vis(&iso), [("20".into(), false), ("05".into(), false), ("100".into(), false), ("101".into(), true)]);
|
||||
assert_eq!(names(&t, &["100".into(), "20".into(), "999".into()]), ["01421", "Wände", "999"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn umbauten() {
|
||||
let t = tree();
|
||||
assert_eq!(vis(&toggle(&t, "100"))[2], ("100".into(), false));
|
||||
let av = apply_visibility(&t, json!({"20": false, "101": false, "zz": true}).as_object().unwrap());
|
||||
assert_eq!(vis(&av), [("20".into(), false), ("05".into(), true), ("100".into(), true), ("101".into(), false)]);
|
||||
let p = patch(&t, "101", json!({"name": "X", "color": null}).as_object().unwrap());
|
||||
assert_eq!(find(&p, "101").unwrap()["name"], "X");
|
||||
assert!(find(&p, "101").unwrap().get("color").is_none());
|
||||
let ac = add_child(&t, "20", &cat("21", "k", true, None));
|
||||
assert_eq!(find(&ac, "20").unwrap()["children"][0]["code"], "21");
|
||||
assert_eq!(codes_of(&insert_after(&t, "100", &cat("102", "c", true, None))), ["20", "05", "100", "102", "101"]);
|
||||
assert_eq!(codes_of(&remove(&t, "05")), ["20"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freie_codes() {
|
||||
assert_eq!(js_parse_int(" 12abc"), Some(12.0));
|
||||
assert_eq!(js_parse_int("x1"), None);
|
||||
assert_eq!(js_parse_int("-3"), Some(-3.0));
|
||||
assert_eq!(next_free_code(&[], 5.0), "01");
|
||||
assert_eq!(next_free_code(&tree(), 5.0), "102");
|
||||
assert_eq!(next_free_code(&[cat("999", "x", true, None)], 1234.9), "1234");
|
||||
assert_eq!(next_free_code(&[cat("-5", "x", true, None), cat("ab", "y", true, None)], 0.0), "-4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_plan() {
|
||||
let t = vec![cat("05", "Import", true, None), cat("20", "Wände", true, None)];
|
||||
let weights = json!({"Neu": 0.5});
|
||||
let plan = plan_import(&["Wände".into(), "Neu".into(), "NEU".into()], &t, &Map::new(), weights.as_object().unwrap());
|
||||
assert_eq!(plan.children.len(), 1);
|
||||
assert_eq!(plan.children[0]["code"], "21");
|
||||
assert_eq!(plan.children[0]["lw"], 0.5);
|
||||
assert_eq!(plan.parent_code, "22");
|
||||
assert_eq!(plan.code_by_layer, [("Wände".into(), "20".into()), ("Neu".into(), "21".into()), ("NEU".into(), "21".into())]);
|
||||
let none = plan_import(&["wände".into()], &t, &Map::new(), &Map::new());
|
||||
assert!(none.children.is_empty());
|
||||
assert!(none.parent_code.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
//! Zeichnungsebenen ([K4] S3, vorher `model/types.ts`): Geschosshöhen stapeln.
|
||||
//! Rechnung auf `serde_json::Value` (verlustfrei: unbekannte Felder bleiben).
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// `recomputeFloorElevations`: Das erste Geschoss beginnt bei 0, jedes weitere bei `baseElevation +
|
||||
/// floorHeight` des vorigen (fehlende Höhe = 0). Nicht-Geschoss-Ebenen verlieren `baseElevation`.
|
||||
pub fn recompute_floor_elevations(levels: &[Value]) -> Vec<Value> {
|
||||
let mut next_base = 0.0_f64;
|
||||
levels
|
||||
.iter()
|
||||
.map(|level| {
|
||||
let mut m = level.as_object().cloned().unwrap_or_default();
|
||||
if level.get("kind").and_then(Value::as_str) != Some("floor") {
|
||||
m.shift_remove("baseElevation");
|
||||
return Value::Object(m);
|
||||
}
|
||||
let base = next_base;
|
||||
next_base = base + level.get("floorHeight").and_then(Value::as_f64).unwrap_or(0.0);
|
||||
m.insert("baseElevation".into(), serde_json::Number::from_f64(base).map_or(Value::Null, Value::Number));
|
||||
Value::Object(m)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn stapelt_geschosse() {
|
||||
let l = vec![
|
||||
json!({"id": "a", "kind": "floor", "floorHeight": 2.6, "baseElevation": 9.0}),
|
||||
json!({"id": "s", "kind": "section", "baseElevation": 1.0}),
|
||||
json!({"id": "b", "kind": "floor"}),
|
||||
json!({"id": "c", "kind": "floor", "floorHeight": 3.0}),
|
||||
];
|
||||
let r = recompute_floor_elevations(&l);
|
||||
assert_eq!(r[0]["baseElevation"], 0.0);
|
||||
assert!(r[1].get("baseElevation").is_none());
|
||||
assert_eq!(r[2]["baseElevation"], 2.6);
|
||||
assert_eq!(r[3]["baseElevation"], 2.6);
|
||||
assert_eq!(l[0]["baseElevation"], 9.0); // Eingabe unverändert
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,8 @@ pub mod ifc_stairs;
|
||||
pub mod ifc_data;
|
||||
pub mod mesh_data;
|
||||
pub mod groups;
|
||||
pub mod layers;
|
||||
pub mod levels;
|
||||
|
||||
#[cfg(feature = "web")]
|
||||
mod web;
|
||||
@@ -52,6 +52,11 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
|
||||
let (expanded, group_ids) = crate::groups::expand_to_groups(p, &a.raw, &a.path);
|
||||
json(&serde_json::json!({"expanded": expanded, "groupIds": group_ids}))
|
||||
}
|
||||
// Ebenen ([K4] S3, `layers.rs`): Kategorie-Codes der Auswahl (`text` = JSON der ids je Art).
|
||||
("selectionCategoryCodes", _) => {
|
||||
let sel: crate::layers::SelectionMembers = serde_json::from_str(text).map_err(|e| format!("selectionCategoryCodes: {e}"))?;
|
||||
json(&crate::layers::selection_category_codes(p, &sel))
|
||||
}
|
||||
_ => Err(format!("Unbekannte Abfrage: {name}")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
//! Bindungen der Ebenen-/Geschoss-Logik (`crate::layers`, `crate::levels`): zustandslos, JSON hinein,
|
||||
//! JSON hinaus. Kaputte Eingaben ergeben einen leeren Text (nie ein Panic).
|
||||
|
||||
use crate::layers;
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::collections::HashSet;
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
fn list(json: &str) -> Option<Vec<Value>> {
|
||||
match serde_json::from_str::<Value>(json).ok()? {
|
||||
Value::Array(a) => Some(a),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn strings(v: &Value) -> Vec<String> {
|
||||
v.as_array().map(|a| a.iter().filter_map(|s| s.as_str().map(str::to_string)).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn obj(v: &Value) -> Map<String, Value> {
|
||||
v.as_object().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
fn text(v: &Value) -> &str {
|
||||
v.as_str().unwrap_or("")
|
||||
}
|
||||
|
||||
/// Rechnung `name` auf dem Kategorie-Baum `layers_json` (Liste); `arg_json`: je nach Rechnung ein Text,
|
||||
/// eine Liste oder ein Objekt. Antwort als JSON, bei Unsinn (kein Baum, unbekannter Name) leerer Text.
|
||||
#[wasm_bindgen]
|
||||
pub fn layers_call(name: &str, layers_json: &str, arg_json: &str, now_ms: f64) -> String {
|
||||
let Some(cats) = list(layers_json) else { return String::new() };
|
||||
let arg: Value = if arg_json.is_empty() { Value::Null } else { serde_json::from_str(arg_json).unwrap_or(Value::Null) };
|
||||
let out: Value = match name {
|
||||
"flatten" => Value::Array(layers::flatten(&cats).into_iter().cloned().collect()),
|
||||
"find" => layers::find(&cats, text(&arg)).cloned().unwrap_or(Value::Null),
|
||||
"visibleCodes" => json!(layers::visible_codes(&cats)),
|
||||
"setVisible" => {
|
||||
let codes: HashSet<String> = strings(&arg["codes"]).into_iter().collect();
|
||||
layers::set_visible(&cats, &codes, arg["visible"].as_bool().unwrap_or(false)).map_or(Value::Null, Value::Array)
|
||||
}
|
||||
"isolate" => {
|
||||
let codes: HashSet<String> = strings(&arg).into_iter().collect();
|
||||
layers::isolate(&cats, &codes).map_or(Value::Null, Value::Array)
|
||||
}
|
||||
"names" => json!(layers::names(&cats, &strings(&arg))),
|
||||
"toggle" => Value::Array(layers::toggle(&cats, text(&arg))),
|
||||
"applyVisibility" => Value::Array(layers::apply_visibility(&cats, &obj(&arg))),
|
||||
"patch" => Value::Array(layers::patch(&cats, text(&arg["code"]), &obj(&arg["patch"]))),
|
||||
"addChild" => Value::Array(layers::add_child(&cats, text(&arg["parent"]), &arg["child"])),
|
||||
"insertAfter" => Value::Array(layers::insert_after(&cats, text(&arg["code"]), &arg["clone"])),
|
||||
"remove" => Value::Array(layers::remove(&cats, text(&arg))),
|
||||
"nextFreeCode" => Value::String(layers::next_free_code(&cats, if now_ms.is_finite() { now_ms } else { 0.0 })),
|
||||
"planImport" => {
|
||||
let plan = layers::plan_import(&strings(&arg["names"]), &cats, &obj(&arg["colors"]), &obj(&arg["weights"]));
|
||||
json!({"children": plan.children, "parentCode": plan.parent_code, "codeByLayer": plan.code_by_layer})
|
||||
}
|
||||
_ => return String::new(),
|
||||
};
|
||||
out.to_string()
|
||||
}
|
||||
|
||||
/// `recomputeFloorElevations` auf der Ebenen-Liste (JSON); leerer Text bei Unsinn.
|
||||
#[wasm_bindgen]
|
||||
pub fn levels_recompute_elevations(levels_json: &str) -> String {
|
||||
match list(levels_json) {
|
||||
Some(l) => Value::Array(crate::levels::recompute_floor_elevations(&l)).to_string(),
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,7 @@ mod plan_svg;
|
||||
mod plan_dxf;
|
||||
mod plan_print_svg;
|
||||
mod drawings;
|
||||
mod layers;
|
||||
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
|
||||
+1
-1
@@ -206,7 +206,7 @@ import { applyDrawingStyleOps, readDrawingStyle } from "./editors/matchProps";
|
||||
|
||||
// Globaler Store (Slices: project/selection/view/layout).
|
||||
import { useStore } from "./state/appStore";
|
||||
import { categoryLabel, findCategory } from "./state/projectSlice";
|
||||
import { categoryLabel, findCategory } from "./model/layers";
|
||||
import { reconcileLayout } from "./state/layoutSlice";
|
||||
|
||||
// Panel-System.
|
||||
|
||||
@@ -45,6 +45,7 @@ export type QueryName =
|
||||
| "meshExportData"
|
||||
| "groupMembership"
|
||||
| "containingGroup"
|
||||
| "selectionCategoryCodes"
|
||||
| "expandToGroups"
|
||||
| "drawingUnderlay"
|
||||
| "drawingLines"
|
||||
|
||||
+3
-39
@@ -17,6 +17,7 @@
|
||||
|
||||
import type { Contour, ContourSet, Drawing2D, Drawing2DGeom, ImportedText, LayerCategory } from "../model/types";
|
||||
import type { ImportContour } from "./dxfParser";
|
||||
import { planImportLayers } from "../model/layers";
|
||||
|
||||
/** Wie DXF-Layer auf Kategorien abgebildet werden. */
|
||||
export type CategoryMode = "active" | "byLayer";
|
||||
@@ -158,47 +159,10 @@ export function planImportCategories(
|
||||
layerColors: Readonly<Record<string, string>> = {},
|
||||
layerLineWeights: Readonly<Record<string, number>> = {},
|
||||
): { parent: LayerCategory | null; codeByLayer: Map<string, string> } {
|
||||
const used = new Set<string>();
|
||||
const byName = new Map<string, string>();
|
||||
const walk = (list: readonly LayerCategory[]) => {
|
||||
for (const c of list) {
|
||||
used.add(c.code);
|
||||
byName.set(c.name.toLowerCase(), c.code);
|
||||
if (c.children) walk(c.children);
|
||||
}
|
||||
};
|
||||
walk(existing);
|
||||
let next = Math.max(0, ...[...used].map((c) => parseInt(c, 10)).filter((n) => !isNaN(n))) + 1;
|
||||
const allocate = (): string => {
|
||||
while (used.has(String(next).padStart(2, "0"))) next++;
|
||||
const code = String(next++).padStart(2, "0");
|
||||
used.add(code);
|
||||
return code;
|
||||
};
|
||||
|
||||
const codeByLayer = new Map<string, string>();
|
||||
const children: LayerCategory[] = [];
|
||||
for (const name of layerNames) {
|
||||
const known = byName.get(name.toLowerCase());
|
||||
if (known) {
|
||||
codeByLayer.set(name, known);
|
||||
continue;
|
||||
}
|
||||
const code = allocate();
|
||||
byName.set(name.toLowerCase(), code); // Dubletten mit anderer Schreibweise teilen sich die Kategorie
|
||||
codeByLayer.set(name, code);
|
||||
children.push({
|
||||
code,
|
||||
name,
|
||||
color: layerColors[name] ?? "#707078",
|
||||
lw: layerLineWeights[name] ?? 0.18,
|
||||
visible: true,
|
||||
locked: false,
|
||||
});
|
||||
}
|
||||
const { children, parentCode, codeByLayer } = planImportLayers(layerNames, existing, layerColors, layerLineWeights);
|
||||
if (children.length === 0) return { parent: null, codeByLayer };
|
||||
const parent: LayerCategory = {
|
||||
code: allocate(),
|
||||
code: parentCode,
|
||||
name: parentName,
|
||||
color: "#707078",
|
||||
lw: 0.18,
|
||||
|
||||
@@ -12,7 +12,7 @@ import { canSetVertexType, vertexTypeOf, type PolylineVertexType } from "../core
|
||||
import { nearestPolylineTarget, toleranceFor } from "../core";
|
||||
import type { LayerCategory, Project, Vec2 } from "../model/types";
|
||||
import { flattenCategories } from "../model/types";
|
||||
import { findCategory } from "../state/projectSlice";
|
||||
import { findCategory } from "../model/layers";
|
||||
import { MenuIcon } from "../ui/ContextMenu";
|
||||
import type { ContextMenuItem } from "../ui/ContextMenu";
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import type { GeoCategory } from "../io/geoContext";
|
||||
import { flattenCategories } from "./layers";
|
||||
import type { LayerCategory } from "./types";
|
||||
|
||||
/** Eine Kategorie-Definition (Code + Default-Name/Farbe/Strichstärke). */
|
||||
@@ -133,7 +134,7 @@ export function ensureContextCategories(
|
||||
layers: LayerCategory[],
|
||||
codes: Iterable<string>,
|
||||
): LayerCategory[] {
|
||||
const existing = new Set(collectCodes(layers));
|
||||
const existing = new Set(flattenCategories(layers).map((c) => c.code));
|
||||
const missing = new Set<string>();
|
||||
for (const code of codes) {
|
||||
if (!existing.has(code)) missing.add(code);
|
||||
@@ -163,13 +164,3 @@ export function ensureContextCategories(
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Alle Codes eines Kategorie-Baums (rekursiv über `children`). */
|
||||
function collectCodes(layers: LayerCategory[]): string[] {
|
||||
const out: string[] = [];
|
||||
for (const l of layers) {
|
||||
out.push(l.code);
|
||||
if (l.children) out.push(...collectCodes(l.children));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { sampleProject } from "./sampleProject";
|
||||
import type { DrawingLevel, LayerCategory } from "./types";
|
||||
import {
|
||||
addChildByCode,
|
||||
applyVisibilityByCode,
|
||||
categoryLabel,
|
||||
collectVisibleCodes,
|
||||
findCategory,
|
||||
flattenCategories,
|
||||
insertAfterCode,
|
||||
nextFreeCode,
|
||||
patchCategoryByCode,
|
||||
planImportLayers,
|
||||
recomputeFloorElevations,
|
||||
removeCategoryByCode,
|
||||
toggleCategoryByCode,
|
||||
} from "./layers";
|
||||
|
||||
const cat = (code: string, name: string, visible = true, children?: LayerCategory[]): LayerCategory => ({
|
||||
code, name, color: "#000", lw: 0.2, visible, locked: false, ...(children ? { children } : {}),
|
||||
});
|
||||
const tree = () => [cat("20", "Wände"), cat("05", "Import", true, [cat("100", "a"), cat("101", "b", false)])];
|
||||
const codes = (t: LayerCategory[]) => flattenCategories(t).map((c) => c.code);
|
||||
|
||||
describe("Kategorie-Baum (Kern)", () => {
|
||||
it("flach, suchen, sichtbare Codes, Beschriftung", () => {
|
||||
const t = tree();
|
||||
expect(codes(t)).toEqual(["20", "05", "100", "101"]);
|
||||
expect(findCategory(t, "101")?.name).toBe("b");
|
||||
expect(findCategory(t, "x")).toBeUndefined();
|
||||
expect([...collectVisibleCodes(t)]).toEqual(["20", "05", "100"]);
|
||||
expect(categoryLabel(t, "20")).toBe("20 Wände");
|
||||
expect(categoryLabel(t, "zz")).toBe("zz");
|
||||
});
|
||||
|
||||
it("Umschalten, Sichtbarkeit nach Codes, Ändern, Unterkategorie, Entfernen", () => {
|
||||
const t = tree();
|
||||
expect(findCategory(toggleCategoryByCode(t, "101"), "101")?.visible).toBe(true);
|
||||
expect(findCategory(applyVisibilityByCode(t, { "20": false, nix: true }), "20")?.visible).toBe(false);
|
||||
expect(findCategory(patchCategoryByCode(t, "100", { name: "neu", hatch: undefined }), "100")?.name).toBe("neu");
|
||||
expect(findCategory(addChildByCode(t, "20", cat("21", "k")), "20")?.children?.[0].code).toBe("21");
|
||||
expect(codes(removeCategoryByCode(t, "05"))).toEqual(["20"]);
|
||||
expect(t[1].children?.length).toBe(2); // Eingabe unverändert
|
||||
});
|
||||
|
||||
it("Duplikat direkt nach dem Original, auch bei Unterkategorien", () => {
|
||||
expect(codes(insertAfterCode(tree(), "20", cat("22", "c")))).toEqual(["20", "22", "05", "100", "101"]);
|
||||
expect(codes(insertAfterCode(tree(), "100", cat("102", "c")))).toEqual(["20", "05", "100", "102", "101"]);
|
||||
});
|
||||
|
||||
it("nächster freier Code", () => {
|
||||
expect(nextFreeCode([])).toBe("01");
|
||||
expect(nextFreeCode(tree())).toBe("102");
|
||||
});
|
||||
|
||||
it("Import-Layer: bestehende Namen (case-insensitiv) behalten ihren Code", () => {
|
||||
const r = planImportLayers(["wände", "Neu", "NEU"], tree(), { Neu: "#123" }, {});
|
||||
expect(r.children).toHaveLength(1);
|
||||
expect(r.children[0]).toMatchObject({ code: "102", name: "Neu", color: "#123", lw: 0.18 });
|
||||
expect(r.parentCode).toBe("103");
|
||||
expect([...r.codeByLayer]).toEqual([["wände", "20"], ["Neu", "102"], ["NEU", "102"]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Geschoss-Stapelung (Kern)", () => {
|
||||
it("stapelt floorHeight, Nicht-Geschosse verlieren baseElevation", () => {
|
||||
const l = [
|
||||
{ id: "a", name: "A", kind: "floor", visible: true, locked: false, floorHeight: 2.6, baseElevation: 9 },
|
||||
{ id: "s", name: "S", kind: "section", visible: true, locked: false, baseElevation: 1 },
|
||||
{ id: "b", name: "B", kind: "floor", visible: true, locked: false, floorHeight: 3 },
|
||||
] as DrawingLevel[];
|
||||
const r = recomputeFloorElevations(l);
|
||||
expect(r.map((x) => x.baseElevation)).toEqual([0, undefined, 2.6]);
|
||||
expect(l[0].baseElevation).toBe(9);
|
||||
});
|
||||
|
||||
it("Musterprojekt trägt die gestapelten Höhen ausgeschrieben (Modul wird vor dem Kern geladen)", () => {
|
||||
expect(recomputeFloorElevations(sampleProject.drawingLevels)).toEqual(sampleProject.drawingLevels);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
// Ebenen-/Kategorien-Baum und Geschoss-Höhen im Rust-Kern ([K4] S3, `src-tauri/core/src/layers.rs`,
|
||||
// `levels.rs`): Abflachen, Nachschlagen, Sichtbarkeit, Isolieren, Baum-Umbauten, freie Codes,
|
||||
// Import-Kategorien, Geschoss-Stapelung. Dünne Fassade über zustandslose Kern-Bindungen (JSON hinein,
|
||||
// JSON hinaus; die Bäume sind klein). Die Op-Bauer (`state/projectSlice.ts`, `state/selectionLayers.ts`)
|
||||
// bleiben in TS und rechnen über diese Funktionen. Ergebnis-Objekte sind Kopien aus dem Kern, nicht die
|
||||
// Eingabe-Objekte; „nichts zu tun" meldet der Kern, die Fassade gibt dann die Eingabe zurück.
|
||||
|
||||
import type { DrawingLevel, LayerCategory, Project } from "./types.generated";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import { documentFor } from "../core/document";
|
||||
|
||||
function call<T>(name: string, layers: readonly LayerCategory[], arg?: unknown): T {
|
||||
const out = core().layers_call(name, JSON.stringify(layers), arg === undefined ? "" : JSON.stringify(arg), Date.now());
|
||||
if (out === "") throw new Error(`Kern: Ebenen-Rechnung „${name}" fehlgeschlagen`);
|
||||
return JSON.parse(out) as T;
|
||||
}
|
||||
|
||||
interface FlatIndex {
|
||||
flat: LayerCategory[];
|
||||
byCode: Map<string, LayerCategory>;
|
||||
}
|
||||
/** Abgeflachter Baum je Baum-Array (die Arrays gelten als unveränderlich): Aufrufe je Bauteil bleiben billig. */
|
||||
const flatCache = new WeakMap<readonly LayerCategory[], FlatIndex>();
|
||||
|
||||
function indexOf(cats: readonly LayerCategory[]): FlatIndex {
|
||||
let ix = flatCache.get(cats);
|
||||
if (!ix) {
|
||||
const flat = call<LayerCategory[]>("flatten", cats);
|
||||
const byCode = new Map<string, LayerCategory>();
|
||||
for (const c of flat) if (!byCode.has(c.code)) byCode.set(c.code, c);
|
||||
ix = { flat, byCode };
|
||||
flatCache.set(cats, ix);
|
||||
}
|
||||
return ix;
|
||||
}
|
||||
|
||||
/** Flacht den Kategorie-Baum (Tiefensuche) in eine Liste ab. */
|
||||
export const flattenCategories = (cats: LayerCategory[]): LayerCategory[] => [...indexOf(cats).flat];
|
||||
|
||||
/** Findet eine Kategorie (per Code) im Baum oder `undefined` (erster Treffer). */
|
||||
export function findCategory(cats: LayerCategory[], code: string): LayerCategory | undefined {
|
||||
return indexOf(cats).byCode.get(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Liefert die LayerCategory zu einem Kategorie-Code (Baum durchsucht), oder `undefined`, falls der Code auf
|
||||
* keine Ebene verweist (verwaister `categoryCode`). Nicht-werfend, damit die Attribut-Resolve-Kette
|
||||
* (`plan/generatePlan.ts`) robust auf einen fehlenden Ebenen-Wert zurückfallen kann.
|
||||
*/
|
||||
export const getLayerCategory = (project: Project, code: string): LayerCategory | undefined => findCategory(project.layers, code);
|
||||
|
||||
/** Menge aller Codes sichtbarer Kategorien (Baum berücksichtigt). */
|
||||
export const collectVisibleCodes = (layers: LayerCategory[]): Set<string> => new Set(call<string[]>("visibleCodes", layers));
|
||||
|
||||
/** Beschriftung einer Kategorie für die Status-Leiste: „Code Name". */
|
||||
export function categoryLabel(cats: LayerCategory[], code: string): string {
|
||||
const c = findCategory(cats, code);
|
||||
return c ? `${c.code} ${c.name}` : code;
|
||||
}
|
||||
|
||||
/** Anzeigenamen der Kategorien zu den Codes (für Menü-Beschriftungen). */
|
||||
export const categoryNames = (layers: LayerCategory[], codes: readonly string[]): string[] => call<string[]>("names", layers, codes);
|
||||
|
||||
/** Setzt `visible` genau für die gegebenen Codes; nichts zu tun → dieselbe Liste. */
|
||||
export function setCategoriesVisible(layers: LayerCategory[], codes: ReadonlySet<string>, visible: boolean): LayerCategory[] {
|
||||
return call<LayerCategory[] | null>("setVisible", layers, { codes: [...codes], visible }) ?? layers;
|
||||
}
|
||||
|
||||
/** Nur die gegebenen Codes sichtbar, alle übrigen ausgeblendet; nichts zu tun → dieselbe Liste. */
|
||||
export function isolateCategories(layers: LayerCategory[], codes: ReadonlySet<string>): LayerCategory[] {
|
||||
return call<LayerCategory[] | null>("isolate", layers, [...codes]) ?? layers;
|
||||
}
|
||||
|
||||
/** Schaltet die Sichtbarkeit der Kategorie mit `code` im Baum um. */
|
||||
export const toggleCategoryByCode = (cats: LayerCategory[], code: string): LayerCategory[] => call("toggle", cats, code);
|
||||
|
||||
/** Setzt im Baum die `visible`-Flags gemäß `codes` (Code → sichtbar?); unbekannte Codes werden ignoriert. */
|
||||
export const applyVisibilityByCode = (cats: LayerCategory[], codes: Record<string, boolean>): LayerCategory[] =>
|
||||
call("applyVisibility", cats, codes);
|
||||
|
||||
/** Nächster freier zweistelliger Code über den ganzen Baum hinweg. */
|
||||
export const nextFreeCode = (cats: LayerCategory[]): string => call("nextFreeCode", cats);
|
||||
|
||||
/** Patcht die Kategorie mit `code` im Baum (`undefined`-Werte entfernen das Feld). */
|
||||
export const patchCategoryByCode = (cats: LayerCategory[], code: string, patch: Partial<LayerCategory>): LayerCategory[] =>
|
||||
call(
|
||||
"patch",
|
||||
cats,
|
||||
{ code, patch: Object.fromEntries(Object.entries(patch).map(([k, v]) => [k, v === undefined ? null : v])) },
|
||||
);
|
||||
|
||||
/** Hängt `child` als letztes Kind an die Kategorie mit `parentCode`. */
|
||||
export const addChildByCode = (cats: LayerCategory[], parentCode: string, child: LayerCategory): LayerCategory[] =>
|
||||
call("addChild", cats, { parent: parentCode, child });
|
||||
|
||||
/** Fügt `clone` direkt nach der Kategorie mit `code` auf derselben Ebene ein. */
|
||||
export const insertAfterCode = (cats: LayerCategory[], code: string, clone: LayerCategory): LayerCategory[] =>
|
||||
call("insertAfter", cats, { code, clone });
|
||||
|
||||
/** Entfernt die Kategorie mit `code` (samt Kindern) aus dem Baum. */
|
||||
export const removeCategoryByCode = (cats: LayerCategory[], code: string): LayerCategory[] => call("remove", cats, code);
|
||||
|
||||
/** Neue Kategorien für Import-Layer ohne gleichnamige Kategorie (s. `planImportCategories`, `io/dxfToDrawings.ts`). */
|
||||
export function planImportLayers(
|
||||
layerNames: readonly string[],
|
||||
existing: readonly LayerCategory[],
|
||||
colors: Readonly<Record<string, string>>,
|
||||
weights: Readonly<Record<string, number>>,
|
||||
): { children: LayerCategory[]; parentCode: string; codeByLayer: Map<string, string> } {
|
||||
const r = call<{ children: LayerCategory[]; parentCode: string; codeByLayer: [string, string][] }>("planImport", existing as LayerCategory[], {
|
||||
names: layerNames,
|
||||
colors,
|
||||
weights,
|
||||
});
|
||||
return { children: r.children, parentCode: r.parentCode, codeByLayer: new Map(r.codeByLayer) };
|
||||
}
|
||||
|
||||
/** Auswahl nach Elementart (ids je Art, wie `selectionLockMembers` in App.tsx). */
|
||||
export interface SelectionMembers {
|
||||
wallIds?: readonly string[];
|
||||
drawingIds?: readonly string[];
|
||||
ceilingIds?: readonly string[];
|
||||
roomIds?: readonly string[];
|
||||
stairIds?: readonly string[];
|
||||
columnIds?: readonly string[];
|
||||
roofIds?: readonly string[];
|
||||
openingIds?: readonly string[];
|
||||
}
|
||||
|
||||
/** Kategorie-Codes aller gewählten Objekte (eindeutig, in Fundreihenfolge). */
|
||||
export function selectionCategoryCodes(project: Project, sel: SelectionMembers): string[] {
|
||||
return documentFor(project).query<string[]>("selectionCategoryCodes", [], JSON.stringify(sel));
|
||||
}
|
||||
|
||||
/**
|
||||
* Stapelt baseElevation der Geschosse in Dokumentreihenfolge: Das erste Geschoss beginnt bei 0, jedes weitere
|
||||
* bei baseElevation + floorHeight des vorigen Geschosses. Nicht-Geschoss-Ebenen behalten baseElevation
|
||||
* undefined. Liefert eine neue Liste; die Eingabe bleibt unverändert.
|
||||
*/
|
||||
export function recomputeFloorElevations(levels: DrawingLevel[]): DrawingLevel[] {
|
||||
const out = core().levels_recompute_elevations(JSON.stringify(levels));
|
||||
if (out === "") throw new Error("Kern: Geschoss-Höhen fehlgeschlagen");
|
||||
return JSON.parse(out) as DrawingLevel[];
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { Project } from "./types";
|
||||
import { recomputeFloorElevations } from "./types";
|
||||
import { MATERIAL_LIBRARY } from "../materials/library";
|
||||
import { materialFromAsset } from "../materials/runtime";
|
||||
|
||||
@@ -341,10 +340,11 @@ export const sampleProject: Project = {
|
||||
},
|
||||
],
|
||||
// Oberste Schnitte: Geschosse + Schnitt/Ansicht + freie Zeichnung.
|
||||
// baseElevation wird über recomputeFloorElevations gestapelt: EG=0, OG=2.6.
|
||||
drawingLevels: recomputeFloorElevations([
|
||||
{ id: "eg", name: "Erdgeschoss", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0 },
|
||||
{ id: "og", name: "Obergeschoss", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0 },
|
||||
// baseElevation = gestapelt wie `recomputeFloorElevations` (Kern): EG=0, OG=2.6. Ausgeschrieben, weil dieses
|
||||
// Modul vor dem Laden des Kerns ausgewertet wird (Test: sampleProject.test.ts).
|
||||
drawingLevels: [
|
||||
{ id: "eg", name: "Erdgeschoss", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 },
|
||||
{ id: "og", name: "Obergeschoss", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 2.6 },
|
||||
{
|
||||
id: "schnitt-a",
|
||||
name: "Schnitt A",
|
||||
@@ -367,7 +367,7 @@ export const sampleProject: Project = {
|
||||
shadows: true,
|
||||
},
|
||||
{ id: "detail-1", name: "Detail 1", kind: "drawing", visible: true, locked: false },
|
||||
]),
|
||||
],
|
||||
// Grafik-Kategorie-Baum (DOSSIER-Codes 1:1).
|
||||
layers: [
|
||||
{ code: "00", name: "Raster", color: "#484850", lw: 0.13, visible: true, locked: false },
|
||||
|
||||
+3
-53
@@ -24,7 +24,6 @@ import type {
|
||||
DrawingLevel,
|
||||
HatchStyle,
|
||||
Layer,
|
||||
LayerCategory,
|
||||
LineStyle,
|
||||
Opening,
|
||||
Project,
|
||||
@@ -255,58 +254,9 @@ export const getFloor = (project: Project, id: string): DrawingLevel => {
|
||||
return g;
|
||||
};
|
||||
|
||||
/**
|
||||
* Stapelt baseElevation der Geschosse in Dokumentreihenfolge: Das erste
|
||||
* Geschoss beginnt bei 0, jedes weitere bei baseElevation + floorHeight des
|
||||
* vorigen Geschosses. Nicht-Geschoss-Ebenen behalten baseElevation undefined.
|
||||
* Liefert eine neue Liste (mit neuen Geschoss-Objekten); die Eingabe bleibt
|
||||
* unverändert.
|
||||
*/
|
||||
export const recomputeFloorElevations = (
|
||||
levels: DrawingLevel[],
|
||||
): DrawingLevel[] => {
|
||||
let nextBase = 0;
|
||||
return levels.map((level) => {
|
||||
if (level.kind !== "floor") {
|
||||
return { ...level, baseElevation: undefined };
|
||||
}
|
||||
const baseElevation = nextBase;
|
||||
nextBase = baseElevation + (level.floorHeight ?? 0);
|
||||
return { ...level, baseElevation };
|
||||
});
|
||||
};
|
||||
|
||||
/** Flacht den Kategorie-Baum (Tiefensuche) in eine Liste ab. */
|
||||
export const flattenCategories = (cats: LayerCategory[]): LayerCategory[] => {
|
||||
const out: LayerCategory[] = [];
|
||||
const walk = (list: LayerCategory[]) => {
|
||||
for (const c of list) {
|
||||
out.push(c);
|
||||
if (c.children) walk(c.children);
|
||||
}
|
||||
};
|
||||
walk(cats);
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
* Liefert die LayerCategory zu einem Kategorie-Code (Baum durchsucht), oder
|
||||
* `undefined`, falls der Code auf keine Ebene verweist (verwaister
|
||||
* `categoryCode`). Nicht-werfend, damit die Attribut-Resolve-Kette
|
||||
* (`plan/generatePlan.ts`) robust auf einen fehlenden Ebenen-Wert zurückfallen
|
||||
* kann (→ Bauteil-Fallback).
|
||||
*/
|
||||
export const getLayerCategory = (project: Project, code: string): LayerCategory | undefined =>
|
||||
flattenCategories(project.layers).find((c) => c.code === code);
|
||||
|
||||
/** Menge aller Codes sichtbarer Kategorien (Baum berücksichtigt). */
|
||||
export const collectVisibleCodes = (layers: LayerCategory[]): Set<string> => {
|
||||
const codes = new Set<string>();
|
||||
for (const c of flattenCategories(layers)) {
|
||||
if (c.visible) codes.add(c.code);
|
||||
}
|
||||
return codes;
|
||||
};
|
||||
// Ebenen-Baum und Geschoss-Stapelung liegen im Rust-Kern ([K4] S3, `model/layers.ts`); Re-Export, damit
|
||||
// die Aufrufer gleich bleiben.
|
||||
export { collectVisibleCodes, flattenCategories, getLayerCategory, recomputeFloorElevations } from "./layers";
|
||||
|
||||
/** Gesamtdicke eines Wandtyps = Summe der Schichtdicken. */
|
||||
export const wallTypeThickness = (wt: WallType): number =>
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { isTauriRuntime } from "./projectFile";
|
||||
import { findCategory } from "../state/projectSlice";
|
||||
import { findCategory } from "../model/layers";
|
||||
import type { HatchStyle, LayerCategory, Project } from "../model/types";
|
||||
import { BORDERLESS_WINDOW_CHROME } from "./windowChrome";
|
||||
|
||||
|
||||
+10
-131
@@ -25,9 +25,17 @@ import {
|
||||
import { withVertexType, type PolylineVertexType } from "../core";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import {
|
||||
addChildByCode,
|
||||
applyVisibilityByCode,
|
||||
findCategory,
|
||||
flattenCategories,
|
||||
insertAfterCode,
|
||||
nextFreeCode,
|
||||
patchCategoryByCode,
|
||||
recomputeFloorElevations,
|
||||
} from "../model/types";
|
||||
removeCategoryByCode,
|
||||
toggleCategoryByCode,
|
||||
} from "../model/layers";
|
||||
import type {
|
||||
BuiltinPaletteBank,
|
||||
ColorPen,
|
||||
@@ -741,7 +749,7 @@ export function createProjectSlice(
|
||||
get().notify(t("alert.layerInUse", { code: src.code, name: src.name }), "warning");
|
||||
return [];
|
||||
}
|
||||
return fieldOps(p, "layers", removeByCode(p.layers, code));
|
||||
return fieldOps(p, "layers", removeCategoryByCode(p.layers, code));
|
||||
}),
|
||||
|
||||
assignWallCategory: (wallId, code) =>
|
||||
@@ -2310,132 +2318,3 @@ function moveEdge(
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
// ── Immutable Tree-Helfer (verschoben aus App.tsx, 1:1) ──────────────────────
|
||||
|
||||
/** Schaltet die Sichtbarkeit der Kategorie mit `code` im Baum um (immutabel). */
|
||||
export function toggleCategoryByCode(
|
||||
cats: LayerCategory[],
|
||||
code: string,
|
||||
): LayerCategory[] {
|
||||
return cats.map((c) => {
|
||||
if (c.code === code) return { ...c, visible: !c.visible };
|
||||
if (c.children)
|
||||
return { ...c, children: toggleCategoryByCode(c.children, code) };
|
||||
return c;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Setzt im Baum die `visible`-Flags gemäß `codes` (Code → sichtbar?, immutabel).
|
||||
* Kategorien, deren Code nicht in der Map steht, bleiben unverändert; Codes der
|
||||
* Map, die es nicht mehr gibt, werden stillschweigend ignoriert.
|
||||
*/
|
||||
export function applyVisibilityByCode(
|
||||
cats: LayerCategory[],
|
||||
codes: Record<string, boolean>,
|
||||
): LayerCategory[] {
|
||||
return cats.map((c) => {
|
||||
const next = c.code in codes ? { ...c, visible: codes[c.code] } : c;
|
||||
if (next.children)
|
||||
return { ...next, children: applyVisibilityByCode(next.children, codes) };
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
/** Nächster freier zweistelliger Code über den ganzen Baum hinweg. */
|
||||
export function nextFreeCode(cats: LayerCategory[]): string {
|
||||
const used = new Set<string>();
|
||||
const walk = (list: LayerCategory[]) => {
|
||||
for (const c of list) {
|
||||
used.add(c.code);
|
||||
if (c.children) walk(c.children);
|
||||
}
|
||||
};
|
||||
walk(cats);
|
||||
const nums = [...used].map((c) => parseInt(c, 10)).filter((n) => !isNaN(n));
|
||||
const start = nums.length ? Math.max(...nums) : 0;
|
||||
for (let i = start + 1; i < 1000; i++) {
|
||||
const c = String(i).padStart(2, "0");
|
||||
if (!used.has(c)) return c;
|
||||
}
|
||||
return String(Date.now());
|
||||
}
|
||||
|
||||
/** Findet eine Kategorie (per Code) im Baum oder `undefined`. */
|
||||
export function findCategory(
|
||||
cats: LayerCategory[],
|
||||
code: string,
|
||||
): LayerCategory | undefined {
|
||||
for (const c of cats) {
|
||||
if (c.code === code) return c;
|
||||
if (c.children) {
|
||||
const hit = findCategory(c.children, code);
|
||||
if (hit) return hit;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Patcht die Kategorie mit `code` im Baum (immutabel). */
|
||||
function patchCategoryByCode(
|
||||
cats: LayerCategory[],
|
||||
code: string,
|
||||
patch: Partial<LayerCategory>,
|
||||
): LayerCategory[] {
|
||||
return cats.map((c) => {
|
||||
if (c.code === code) return { ...c, ...patch };
|
||||
if (c.children)
|
||||
return { ...c, children: patchCategoryByCode(c.children, code, patch) };
|
||||
return c;
|
||||
});
|
||||
}
|
||||
|
||||
/** Hängt `child` als letztes Kind an die Kategorie mit `parentCode` (immutabel). */
|
||||
function addChildByCode(
|
||||
cats: LayerCategory[],
|
||||
parentCode: string,
|
||||
child: LayerCategory,
|
||||
): LayerCategory[] {
|
||||
return cats.map((c) => {
|
||||
if (c.code === parentCode)
|
||||
return { ...c, children: [...(c.children ?? []), child] };
|
||||
if (c.children)
|
||||
return { ...c, children: addChildByCode(c.children, parentCode, child) };
|
||||
return c;
|
||||
});
|
||||
}
|
||||
|
||||
/** Fügt `clone` direkt nach der Kategorie mit `code` auf derselben Ebene ein. */
|
||||
function insertAfterCode(
|
||||
cats: LayerCategory[],
|
||||
code: string,
|
||||
clone: LayerCategory,
|
||||
): LayerCategory[] {
|
||||
const out: LayerCategory[] = [];
|
||||
for (const c of cats) {
|
||||
const next =
|
||||
c.children && !c.children.some((k) => k.code === code)
|
||||
? { ...c, children: insertAfterCode(c.children, code, clone) }
|
||||
: c;
|
||||
out.push(next);
|
||||
if (c.code === code) out.push(clone);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Entfernt die Kategorie mit `code` (samt Kindern) aus dem Baum (immutabel). */
|
||||
function removeByCode(cats: LayerCategory[], code: string): LayerCategory[] {
|
||||
const out: LayerCategory[] = [];
|
||||
for (const c of cats) {
|
||||
if (c.code === code) continue;
|
||||
out.push(c.children ? { ...c, children: removeByCode(c.children, code) } : c);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Beschriftung einer Kategorie für die Status-Leiste: „Code Name". */
|
||||
export function categoryLabel(cats: LayerCategory[], code: string): string {
|
||||
const c = findCategory(cats, code);
|
||||
return c ? `${c.code} ${c.name}` : code;
|
||||
}
|
||||
@@ -14,7 +14,6 @@ import { extrudedSolidSpec } from "../core";
|
||||
import type { SolidSpec } from "../engine/truckSolid";
|
||||
import {
|
||||
ceilingThickness,
|
||||
flattenCategories,
|
||||
getCeilingType,
|
||||
getComponent,
|
||||
getWallType,
|
||||
@@ -31,7 +30,6 @@ import type {
|
||||
Drawing2D,
|
||||
Drawing2DGeom,
|
||||
ExtrudedSolid,
|
||||
LayerCategory,
|
||||
Opening,
|
||||
Project,
|
||||
Roof,
|
||||
@@ -45,6 +43,7 @@ import type {
|
||||
Wall,
|
||||
WallReferenceLine,
|
||||
} from "../model/types";
|
||||
import { findCategory } from "../model/layers";
|
||||
import type { DetailLevel } from "../model/viewTypes";
|
||||
import { localToLv95 } from "../io/lv95";
|
||||
import { resolveForeground, resolveBackground, resolveHatchId, resolveStrokeWeight } from "../core";
|
||||
@@ -546,14 +545,6 @@ const WALL_FALLBACK_MM = 0.18;
|
||||
const DRAW_FALLBACK_COLOR = "#d0d0d0";
|
||||
const WALL_FALLBACK_COLOR = "#2b3039";
|
||||
|
||||
/** Kategorie (per Code) im Baum suchen — flach, da Codes baumweit eindeutig sind. */
|
||||
function findCategory(
|
||||
layers: LayerCategory[],
|
||||
code: string,
|
||||
): LayerCategory | undefined {
|
||||
return flattenCategories(layers).find((c) => c.code === code);
|
||||
}
|
||||
|
||||
/** Ob eine 2D-Form geschlossen ist (Füllung/Schraffur sinnvoll). */
|
||||
function isClosedGeom(g: Drawing2DGeom): boolean {
|
||||
return (
|
||||
|
||||
@@ -21,11 +21,11 @@ describe("Ebenen der Auswahl", () => {
|
||||
expect(selectionCategoryCodes(project, { drawingIds: ["nix"] })).toEqual([]);
|
||||
});
|
||||
|
||||
it("blendet genau die Codes aus (auch verschachtelt), unveränderte Teile bleiben dieselben Objekte", () => {
|
||||
it("blendet genau die Codes aus (auch verschachtelt), nichts zu tun liefert dieselbe Liste", () => {
|
||||
const next = setCategoriesVisible(layers, new Set(["100"]), false);
|
||||
expect(next[1].children![0].visible).toBe(false);
|
||||
expect(next[1].children![1].visible).toBe(true);
|
||||
expect(next[0]).toBe(layers[0]); // Wände unverändert (gleiches Objekt)
|
||||
expect(next[0]).toEqual(layers[0]); // Wände unverändert (Kopie aus dem Kern)
|
||||
expect(setCategoriesVisible(layers, new Set(["100"]), true)).toBe(layers); // nichts zu tun → gleiche Referenz
|
||||
});
|
||||
|
||||
|
||||
@@ -1,80 +1,11 @@
|
||||
// Ebenen (Kategorien) der aktuellen Auswahl: ausblenden bzw. isolieren
|
||||
// ("nur diese Ebene(n) zeigen"). Reine Funktionen — der Aufrufer (App) legt sie
|
||||
// über `setProject`, also EIN Undo-Schritt.
|
||||
// Ebenen (Kategorien) der aktuellen Auswahl: ausblenden bzw. isolieren ("nur diese Ebene(n) zeigen").
|
||||
// Die Rechnung liegt im Rust-Kern ([K4] S3, `core/src/layers.rs`, Fassade `model/layers.ts`); dieses Modul
|
||||
// bleibt als Einstieg für die UI. Der Aufrufer (App) legt die Ergebnisse über `applyChange`, also EIN Undo-Schritt.
|
||||
|
||||
import type { LayerCategory, Project } from "../model/types";
|
||||
import { flattenCategories } from "../model/types";
|
||||
|
||||
/** Ausgewählte Objekt-IDs je Art (wie `selectionLockMembers` in App.tsx). */
|
||||
export interface SelectionMembers {
|
||||
wallIds?: readonly string[];
|
||||
drawingIds?: readonly string[];
|
||||
ceilingIds?: readonly string[];
|
||||
roomIds?: readonly string[];
|
||||
stairIds?: readonly string[];
|
||||
columnIds?: readonly string[];
|
||||
roofIds?: readonly string[];
|
||||
openingIds?: readonly string[];
|
||||
}
|
||||
|
||||
type WithCat = { id: string; categoryCode?: string };
|
||||
|
||||
/** Kategorie-Codes aller gewählten Objekte (eindeutig, in Fundreihenfolge). */
|
||||
export function selectionCategoryCodes(project: Project, sel: SelectionMembers): string[] {
|
||||
const p = project as unknown as Record<string, readonly WithCat[] | undefined>;
|
||||
const sources: Array<[readonly string[] | undefined, readonly WithCat[]]> = [
|
||||
[sel.wallIds, p.walls ?? []],
|
||||
[sel.drawingIds, p.drawings2d ?? []],
|
||||
[sel.ceilingIds, p.ceilings ?? []],
|
||||
[sel.roomIds, p.rooms ?? []],
|
||||
[sel.stairIds, p.stairs ?? []],
|
||||
[sel.columnIds, p.columns ?? []],
|
||||
[sel.roofIds, p.roofs ?? []],
|
||||
[sel.openingIds, p.openings ?? []],
|
||||
];
|
||||
const out = new Set<string>();
|
||||
for (const [ids, objects] of sources) {
|
||||
if (!ids || ids.length === 0) continue;
|
||||
const wanted = new Set(ids);
|
||||
for (const o of objects) if (o.categoryCode && wanted.has(o.id)) out.add(o.categoryCode);
|
||||
}
|
||||
return [...out];
|
||||
}
|
||||
|
||||
function mapCategories(
|
||||
layers: LayerCategory[],
|
||||
fn: (c: LayerCategory) => LayerCategory,
|
||||
): LayerCategory[] {
|
||||
let changed = false;
|
||||
const next = layers.map((c) => {
|
||||
const children = c.children ? mapCategories(c.children, fn) : undefined;
|
||||
const base = children !== c.children ? { ...c, children } : c;
|
||||
const out = fn(base);
|
||||
if (out !== c) changed = true;
|
||||
return out;
|
||||
});
|
||||
return changed ? next : layers;
|
||||
}
|
||||
|
||||
/** Setzt `visible` genau für die gegebenen Codes; unveränderte Teilbäume bleiben dieselben Objekte. */
|
||||
export function setCategoriesVisible(
|
||||
layers: LayerCategory[],
|
||||
codes: ReadonlySet<string>,
|
||||
visible: boolean,
|
||||
): LayerCategory[] {
|
||||
return mapCategories(layers, (c) => (codes.has(c.code) && c.visible !== visible ? { ...c, visible } : c));
|
||||
}
|
||||
|
||||
/** Nur die gegebenen Codes sichtbar, alle übrigen ausgeblendet. */
|
||||
export function isolateCategories(layers: LayerCategory[], codes: ReadonlySet<string>): LayerCategory[] {
|
||||
return mapCategories(layers, (c) => {
|
||||
const want = codes.has(c.code);
|
||||
return c.visible !== want ? { ...c, visible: want } : c;
|
||||
});
|
||||
}
|
||||
|
||||
/** Anzeigenamen der Kategorien zu den Codes (für Menü-Beschriftungen). */
|
||||
export function categoryNames(layers: LayerCategory[], codes: readonly string[]): string[] {
|
||||
const all = flattenCategories(layers);
|
||||
return codes.map((code) => all.find((c) => c.code === code)?.name ?? code);
|
||||
}
|
||||
export {
|
||||
categoryNames,
|
||||
isolateCategories,
|
||||
selectionCategoryCodes,
|
||||
setCategoriesVisible,
|
||||
type SelectionMembers,
|
||||
} from "../model/layers";
|
||||
Reference in new issue
Block a user