[K4] Stiftsätze im Kern: Standardpalette, Neu-Backen der Stift-Farben, Stift löschen mit Verweisen (pens.rs)
Wurzel-Abfragen (run_root, doc_query_root, ProjectDocument.queryRoot) liefern Ops; model/penSets.ts ist Fassade, TS-Rechnung (Palette, rebakePenOps, clearCategoryPenRefs in projectSlice) gelöscht.
This commit is contained in:
14 files changed
+583
-256
No files matched your search
@@ -417,8 +417,19 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
(`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].
|
||||
Layout-/Ordnerbäume (`layoutModel.ts`), Parametrik-Regeln (`parametricWalls.ts`); Undo-Verlauf als Liste in der UI [84].
|
||||
**Stiftsätze im Kern (29.10.):** `pens.rs` (Standardpalette mit 255 Stiften, Freie-Farbe-Palette, `hsl_to_hex`, Neu-Backen
|
||||
der Stift-Farben/-Strichstärken `rebake_ops`, Standardsatz anlegen `seed_standard_ops`, Stift löschen samt Verweisen in
|
||||
Bauteilen und im Kategorien-Baum `delete_pen_ops`). Rechnung auf der rohen Projekt-Wurzel (`serde_json`, verlustfrei) und
|
||||
Ergebnis als Ops; neu: Wurzel-Abfragen (`queries::run_root`, `doc_query_root`, TS `ProjectDocument.queryRoot`) neben den
|
||||
typisierten Abfragen. `model/penSets.ts` ist Fassade (Lese-Auflösung `resolvePenColor/Weight` einzeln je Swatch bleibt in TS,
|
||||
`freeColorPalette()` statt Modul-Konstante, weil der Kern erst nach `initCore()` lesbar ist); `deletePen` in
|
||||
`projectSlice` ruft `deletePenOps`. Gleichheit (einmalig, Test gelöscht): 4000 Zufallsprojekte Neu-Backen, 1500 Standardsatz,
|
||||
3000 Stift-löschen (doppelte/fehlende Stift-ids, `constructor`/`__proto__` als Stift-id, fehlende Listen, verschachtelte
|
||||
Kategorien), 20000 `hslToHex` — Ergebnis nach `applyOps` zeichengleich (auch Schlüsselreihenfolge). Abweichungen
|
||||
(gewollt): Ebenen werden nur noch geschrieben, wenn sich etwas ändert (vorher immer ein `setField layers`), die Stifte
|
||||
des Standardsatzes als ein `setField` statt Listen-Differenz (gleiches Ergebnis), unveränderte Ebenen-Kategorien
|
||||
behalten nach dem Neu-Backen nicht mehr ihre Objekt-Identität.
|
||||
- ◐ **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
|
||||
|
||||
@@ -155,6 +155,11 @@ impl Document {
|
||||
Ok(self.typed.as_ref().expect("gerade gesetzt"))
|
||||
}
|
||||
|
||||
/// Die Projekt-Wurzel als JSON (für Abfragen, die auf dem rohen Baum rechnen, s. `queries::run_root`).
|
||||
pub fn root(&self) -> &Map<String, Value> {
|
||||
&self.root
|
||||
}
|
||||
|
||||
pub fn field(&self, key: &str) -> Option<&Value> {
|
||||
self.root.get(key)
|
||||
}
|
||||
|
||||
@@ -74,6 +74,7 @@ pub mod mesh_data;
|
||||
pub mod groups;
|
||||
pub mod layers;
|
||||
pub mod levels;
|
||||
pub mod pens;
|
||||
|
||||
#[cfg(feature = "web")]
|
||||
mod web;
|
||||
@@ -0,0 +1,406 @@
|
||||
//! Stiftsätze ([K4] S3, vorher `src/model/penSets.ts` und `clearCategoryPenRefs` in `state/projectSlice.ts`):
|
||||
//! Standardpalette, Neu-Backen der Stift-Farben (`rebake_ops`), Stift-Verweise beim Löschen eines Stifts.
|
||||
//! Die Rechnung läuft auf der Projekt-Wurzel (`serde_json::Map`; unbekannte Felder und Schlüsselreihenfolge
|
||||
//! bleiben) und liefert Ops (`{"kind":"replace"|"setField"|…}`, Form wie `core/ops.ts`), keine Kopien des
|
||||
//! Projekts. Die Auflösung eines einzelnen Stifts (`resolvePenColor` …) bleibt als Leseweg der UI in TS.
|
||||
|
||||
use crate::jsnum;
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
/// Farbe eines Stifts, der im aktiven Stiftsatz (noch) keinen Eintrag hat.
|
||||
pub const PEN_FALLBACK_COLOR: &str = "#9aa0a6";
|
||||
/// Strichstärke (mm) eines Stifts ohne Eintrag.
|
||||
pub const PEN_FALLBACK_WEIGHT: f64 = 0.18;
|
||||
|
||||
/// JS-Wahrheitswert (`if (x.colorPenId)`).
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/// Schlüssel des Stifts als Objekt-Schlüssel (JS: `pens[penId]`, eine Zahl wird zu Text).
|
||||
fn key_of(v: &Value) -> Option<String> {
|
||||
match v {
|
||||
Value::String(s) => Some(s.clone()),
|
||||
Value::Number(n) => Some(crate::js_fmt::js_number(n.as_f64()?)),
|
||||
Value::Bool(b) => Some(b.to_string()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// HSL (h in Grad, s/l in 0..1) → "#rrggbb" (`hslToHex`).
|
||||
pub fn hsl_to_hex(h: f64, s: f64, l: f64) -> String {
|
||||
let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
|
||||
let hp = (((h % 360.0) + 360.0) % 360.0) / 60.0;
|
||||
let x = c * (1.0 - ((hp % 2.0) - 1.0).abs());
|
||||
let (r1, g1, b1) = if hp < 1.0 {
|
||||
(c, x, 0.0)
|
||||
} else if hp < 2.0 {
|
||||
(x, c, 0.0)
|
||||
} else if hp < 3.0 {
|
||||
(0.0, c, x)
|
||||
} else if hp < 4.0 {
|
||||
(0.0, x, c)
|
||||
} else if hp < 5.0 {
|
||||
(x, 0.0, c)
|
||||
} else {
|
||||
(c, 0.0, x)
|
||||
};
|
||||
let m = l - c / 2.0;
|
||||
// `Math.round(..).toString(16).padStart(2, "0")`; Werte ausserhalb 0..255 (nur bei unsinnigen Eingaben)
|
||||
// schreiben wie JS mehr Stellen bzw. ein Minuszeichen.
|
||||
let hex = |v: f64| {
|
||||
let n = jsnum::round((v + m) * 255.0);
|
||||
if n.is_nan() {
|
||||
"NaN".to_string()
|
||||
} else if n < 0.0 {
|
||||
format!("-{:02x}", (-n) as u64)
|
||||
} else {
|
||||
format!("{:02x}", n as u64)
|
||||
}
|
||||
};
|
||||
format!("#{}{}{}", hex(r1), hex(g1), hex(b1))
|
||||
}
|
||||
|
||||
/// Feste Palette des Freie-Farbe-Popovers: 8 Graustufen + 8 Farbtöne × 5 Helligkeitsstufen (`FREE_COLOR_PALETTE`).
|
||||
pub fn free_color_palette() -> Vec<String> {
|
||||
let mut out = Vec::with_capacity(48);
|
||||
for i in 0..8 {
|
||||
let v = jsnum::round((i as f64 / 7.0) * 255.0) as u64;
|
||||
out.push(format!("#{}", format!("{v:02x}").repeat(3)));
|
||||
}
|
||||
for hue in 0..8 {
|
||||
for level in 0..5 {
|
||||
out.push(hsl_to_hex(hue as f64 * 45.0, 0.75, 0.75 - level as f64 * 0.14));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 255 Stifte + Stile der Standardpalette (`generateStandardPenPalette`): `(pens, styles)`.
|
||||
pub fn standard_pen_palette() -> (Vec<Value>, Map<String, Value>) {
|
||||
let mut pens = Vec::with_capacity(255);
|
||||
let mut styles = Map::new();
|
||||
let mut add = |id: u32, name: String, color: String| {
|
||||
pens.push(json!({"id": id.to_string(), "name": name}));
|
||||
styles.insert(id.to_string(), json!({"color": color, "weight": PEN_FALLBACK_WEIGHT}));
|
||||
};
|
||||
for (id, name, color) in [
|
||||
(1, "Rot", "#ff0000"),
|
||||
(2, "Gelb", "#ffff00"),
|
||||
(3, "Grün", "#00ff00"),
|
||||
(4, "Cyan", "#00ffff"),
|
||||
(5, "Blau", "#0000ff"),
|
||||
(6, "Magenta", "#ff00ff"),
|
||||
(7, "Schwarz", "#000000"),
|
||||
(8, "Dunkelgrau", "#414141"),
|
||||
(9, "Grau", "#808080"),
|
||||
] {
|
||||
add(id, name.to_string(), color.to_string());
|
||||
}
|
||||
let mut id = 10;
|
||||
for hue in 0..24 {
|
||||
let h = hue as f64 * 15.0;
|
||||
for step in 0..10 {
|
||||
let saturated = step < 5;
|
||||
let level = (step % 5) as f64;
|
||||
let l = 0.75 - level * 0.14;
|
||||
let s = if saturated { 0.85 } else { 0.4 };
|
||||
add(id, format!("Stift {id}"), hsl_to_hex(h, s, l));
|
||||
id += 1;
|
||||
}
|
||||
}
|
||||
for (gid, color) in [(250, "#333333"), (251, "#5b5b5b"), (252, "#848484"), (253, "#adadad"), (254, "#d6d6d6"), (255, "#ffffff")] {
|
||||
add(gid, format!("Grau {gid}"), color.to_string());
|
||||
}
|
||||
(pens, styles)
|
||||
}
|
||||
|
||||
/// Stile (Farbe + Strichstärke) des aktiven Stiftsatzes (`activePenSet(p)?.pens`).
|
||||
struct Active<'a>(Option<&'a Map<String, Value>>);
|
||||
|
||||
impl Active<'_> {
|
||||
fn of(root: &Map<String, Value>) -> Active<'_> {
|
||||
let want = root.get("activePenSetId").filter(|v| !v.is_null());
|
||||
let set = root
|
||||
.get("penSets")
|
||||
.and_then(Value::as_array)
|
||||
.and_then(|a| a.iter().find(|s| s.get("id").filter(|v| !v.is_null()) == want));
|
||||
Active(set.and_then(|s| s.get("pens")).and_then(Value::as_object))
|
||||
}
|
||||
|
||||
fn style(&self, pen: &Value) -> Option<&Value> {
|
||||
let k = key_of(pen)?;
|
||||
self.0?.get(&k).filter(|v| !v.is_null())
|
||||
}
|
||||
|
||||
fn color(&self, pen: &Value) -> Value {
|
||||
match self.style(pen).and_then(|s| s.get("color")) {
|
||||
Some(c) if c.is_string() => c.clone(),
|
||||
_ => Value::String(PEN_FALLBACK_COLOR.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn weight(&self, pen: &Value) -> Value {
|
||||
match self.style(pen).and_then(|s| s.get("weight")) {
|
||||
Some(w) if w.is_number() => w.clone(),
|
||||
_ => json!(PEN_FALLBACK_WEIGHT),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bauteil: Farben aus den Stift-Verweisen neu schreiben (`bakeComponent`).
|
||||
fn bake_component(a: &Active, c: &Value) -> Value {
|
||||
let Some(src) = c.as_object() else { return c.clone() };
|
||||
let mut m = src.clone();
|
||||
for (pen, key) in [("colorPenId", "color"), ("foregroundPenId", "foreground"), ("backgroundPenId", "background")] {
|
||||
if truthy(src.get(pen)) {
|
||||
m.insert(key.to_string(), a.color(&src[pen]));
|
||||
}
|
||||
}
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
/// Kategorie samt Kindern (`bakeCategory`).
|
||||
fn bake_category(a: &Active, cat: &Value) -> Value {
|
||||
let Some(src) = cat.as_object() else { return cat.clone() };
|
||||
let mut m = src.clone();
|
||||
if truthy(src.get("colorPenId")) {
|
||||
m.insert("color".into(), a.color(&src["colorPenId"]));
|
||||
m.insert("lw".into(), a.weight(&src["colorPenId"]));
|
||||
}
|
||||
if let Some(ch) = src.get("children").and_then(Value::as_array) {
|
||||
m.insert("children".into(), Value::Array(ch.iter().map(|c| bake_category(a, c)).collect()));
|
||||
}
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
/// Nur Farbe (Dach, Öffnung, Treppe, Raum; `bakeElementColor`).
|
||||
fn bake_color(a: &Active, x: &Value) -> Value {
|
||||
let Some(src) = x.as_object() else { return x.clone() };
|
||||
if !truthy(src.get("colorPenId")) {
|
||||
return x.clone();
|
||||
}
|
||||
let mut m = src.clone();
|
||||
m.insert("color".into(), a.color(&src["colorPenId"]));
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
/// Farbe + Strichstärke unter `weight_key` + Vorder-/Hintergrund (`bakeElementColorAndWeight`).
|
||||
fn bake_color_weight(a: &Active, x: &Value, weight_key: &str) -> Value {
|
||||
let Some(src) = x.as_object() else { return x.clone() };
|
||||
let mut m = src.clone();
|
||||
if truthy(src.get("colorPenId")) {
|
||||
m.insert("color".into(), a.color(&src["colorPenId"]));
|
||||
m.insert(weight_key.into(), a.weight(&src["colorPenId"]));
|
||||
}
|
||||
if truthy(src.get("foregroundPenId")) {
|
||||
m.insert("foreground".into(), a.color(&src["foregroundPenId"]));
|
||||
}
|
||||
if truthy(src.get("backgroundPenId")) {
|
||||
m.insert("background".into(), a.color(&src["backgroundPenId"]));
|
||||
}
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
/// `replace`-Ops für alle Elemente von `collection`, die `f` ändert (Listenreihenfolge; `patchItems`).
|
||||
fn patch_items(root: &Map<String, Value>, collection: &str, f: &dyn Fn(&Value) -> Value, ops: &mut Vec<Value>) {
|
||||
let Some(list) = root.get(collection).and_then(Value::as_array) else { return };
|
||||
for e in list {
|
||||
let next = f(e);
|
||||
if next != *e {
|
||||
ops.push(json!({"kind": "replace", "collection": collection, "entity": next}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ops, die alle Farben/Strichstärken mit Stift-Verweis aus dem aktiven Stiftsatz neu schreiben (`rebakePenOps`).
|
||||
/// Ändert nichts, wenn der Wert schon stimmt (die TS-Fassung schrieb die Ebenen immer ganz neu).
|
||||
pub fn rebake_ops(root: &Map<String, Value>) -> Vec<Value> {
|
||||
let a = Active::of(root);
|
||||
let mut ops = Vec::new();
|
||||
patch_items(root, "components", &|c| bake_component(&a, c), &mut ops);
|
||||
if let Some(layers) = root.get("layers").and_then(Value::as_array) {
|
||||
let next: Vec<Value> = layers.iter().map(|c| bake_category(&a, c)).collect();
|
||||
if next != *layers {
|
||||
ops.push(json!({"kind": "setField", "key": "layers", "value": next}));
|
||||
}
|
||||
}
|
||||
patch_items(root, "walls", &|w| bake_color_weight(&a, w, "strokeWeight"), &mut ops);
|
||||
patch_items(root, "drawings2d", &|d| bake_color_weight(&a, d, "weightMm"), &mut ops);
|
||||
patch_items(root, "ceilings", &|c| bake_color_weight(&a, c, "strokeWeight"), &mut ops);
|
||||
patch_items(root, "columns", &|c| bake_color_weight(&a, c, "strokeWeight"), &mut ops);
|
||||
for coll in ["roofs", "openings", "stairs", "rooms"] {
|
||||
patch_items(root, coll, &|x| bake_color(&a, x), &mut ops);
|
||||
}
|
||||
ops
|
||||
}
|
||||
|
||||
/// Ops zum Anlegen der Standardpalette (`seedStandardPenSetOps`): Stifte ersetzen, Satz anhängen (`set_id`,
|
||||
/// `set_name`), aktiv setzen, falls noch keiner aktiv war, und neu backen. Die Stifte kommen als ein
|
||||
/// `setField` (die TS-Fassung schrieb eine Listen-Differenz; Ergebnis gleich).
|
||||
pub fn seed_standard_ops(root: &Map<String, Value>, set_id: &str, set_name: &str) -> Vec<Value> {
|
||||
let (pens, styles) = standard_pen_palette();
|
||||
let pen_set = json!({"id": set_id, "name": set_name, "pens": styles});
|
||||
let mut ops: Vec<Value> = Vec::new();
|
||||
let mut work = root.clone();
|
||||
if root.get("pens") != Some(&Value::Array(pens.clone())) {
|
||||
ops.push(json!({"kind": "setField", "key": "pens", "value": pens}));
|
||||
}
|
||||
work.insert("pens".into(), Value::Array(pens));
|
||||
ops.push(json!({"kind": "add", "collection": "penSets", "items": [pen_set.clone()]}));
|
||||
let sets = work.entry("penSets").or_insert_with(|| Value::Array(vec![]));
|
||||
if let Value::Array(a) = sets {
|
||||
a.push(pen_set);
|
||||
}
|
||||
let keep = root.get("activePenSetId").filter(|v| !v.is_null());
|
||||
let active = keep.cloned().unwrap_or_else(|| Value::String(set_id.into()));
|
||||
if root.get("activePenSetId") != Some(&active) {
|
||||
ops.push(json!({"kind": "setField", "key": "activePenSetId", "value": active}));
|
||||
}
|
||||
work.insert("activePenSetId".into(), active);
|
||||
ops.extend(rebake_ops(&work));
|
||||
ops
|
||||
}
|
||||
|
||||
/// `{...x, colorPenId: undefined …}`: Verweise auf `id` entfernen (`clearPenRefs`).
|
||||
fn clear_refs(x: &Value, id: &str) -> Value {
|
||||
let Some(src) = x.as_object() else { return x.clone() };
|
||||
let hit = |k: &str| src.get(k).and_then(Value::as_str) == Some(id);
|
||||
if !(hit("colorPenId") || hit("foregroundPenId") || hit("backgroundPenId")) {
|
||||
return x.clone();
|
||||
}
|
||||
let mut m = src.clone();
|
||||
for k in ["colorPenId", "foregroundPenId", "backgroundPenId"] {
|
||||
if hit(k) {
|
||||
m.shift_remove(k);
|
||||
}
|
||||
}
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
/// Kategorie: Verweis auf `id` entfernen, rekursiv (`clearCategoryPenRefs`).
|
||||
fn clear_category(cat: &Value, id: &str) -> Value {
|
||||
let Some(src) = cat.as_object() else { return cat.clone() };
|
||||
let mut m = src.clone();
|
||||
if src.get("colorPenId").and_then(Value::as_str) == Some(id) {
|
||||
m.shift_remove("colorPenId");
|
||||
}
|
||||
if let Some(ch) = src.get("children").and_then(Value::as_array) {
|
||||
m.insert("children".into(), Value::Array(ch.iter().map(|c| clear_category(c, id)).collect()));
|
||||
}
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
/// Ops zum Löschen des Stifts `id`: aus `pens` und allen Stiftsätzen entfernen, Verweise in Bauteilen
|
||||
/// und im Kategorien-Baum löschen (`deletePen`).
|
||||
pub fn delete_pen_ops(root: &Map<String, Value>, id: &str) -> Vec<Value> {
|
||||
let mut ops = Vec::new();
|
||||
let known = root.get("pens").and_then(Value::as_array).is_some_and(|a| a.iter().any(|e| e.get("id").and_then(Value::as_str) == Some(id)));
|
||||
if known {
|
||||
ops.push(json!({"kind": "remove", "collection": "pens", "ids": [id]}));
|
||||
}
|
||||
patch_items(
|
||||
root,
|
||||
"penSets",
|
||||
&|s| {
|
||||
let Some(src) = s.as_object() else { return s.clone() };
|
||||
let mut m = src.clone();
|
||||
if let Some(Value::Object(p)) = src.get("pens") {
|
||||
let mut p = p.clone();
|
||||
p.shift_remove(id);
|
||||
m.insert("pens".into(), Value::Object(p));
|
||||
}
|
||||
Value::Object(m)
|
||||
},
|
||||
&mut ops,
|
||||
);
|
||||
patch_items(root, "components", &|c| clear_refs(c, id), &mut ops);
|
||||
if let Some(layers) = root.get("layers").and_then(Value::as_array) {
|
||||
let next: Vec<Value> = layers.iter().map(|c| clear_category(c, id)).collect();
|
||||
if next != *layers {
|
||||
ops.push(json!({"kind": "setField", "key": "layers", "value": next}));
|
||||
}
|
||||
}
|
||||
ops
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn root(v: Value) -> Map<String, Value> {
|
||||
v.as_object().unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hsl_und_paletten() {
|
||||
assert_eq!(hsl_to_hex(0.0, 1.0, 0.5), "#ff0000");
|
||||
assert_eq!(hsl_to_hex(-120.0, 1.0, 0.5), "#0000ff");
|
||||
let free = free_color_palette();
|
||||
assert_eq!(free.len(), 48);
|
||||
assert_eq!(free[0], "#000000");
|
||||
assert_eq!(free[7], "#ffffff");
|
||||
let (pens, styles) = standard_pen_palette();
|
||||
assert_eq!(pens.len(), 255);
|
||||
assert_eq!(styles.len(), 255);
|
||||
assert_eq!(styles["7"]["color"], "#000000");
|
||||
assert_eq!(pens[9]["name"], "Stift 10");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rebake_schreibt_nur_geaenderte() {
|
||||
let p = root(json!({
|
||||
"penSets": [{"id": "a", "name": "A", "pens": {"1": {"color": "#111111", "weight": 0.5}}}],
|
||||
"activePenSetId": "a",
|
||||
"components": [{"id": "c1", "color": "#000", "colorPenId": "1"}, {"id": "c2", "color": "#000"}],
|
||||
"layers": [{"code": "20", "colorPenId": "9", "color": "#000", "lw": 1, "children": [{"code": "21"}]}],
|
||||
"walls": [{"id": "w", "colorPenId": "1", "color": "#111111", "strokeWeight": 0.5}, {"id": "w2", "colorPenId": "1"}],
|
||||
}));
|
||||
let ops = rebake_ops(&p);
|
||||
let kinds: Vec<(String, String)> = ops
|
||||
.iter()
|
||||
.map(|o| (o["kind"].as_str().unwrap().into(), o["entity"]["id"].as_str().or(o["key"].as_str()).unwrap().into()))
|
||||
.collect();
|
||||
assert_eq!(kinds, vec![("replace".into(), "c1".into()), ("setField".into(), "layers".into()), ("replace".into(), "w2".into())]);
|
||||
// fehlender Stift im Satz: Rückfallfarbe
|
||||
assert_eq!(ops[1]["value"][0]["color"], PEN_FALLBACK_COLOR);
|
||||
assert_eq!(ops[1]["value"][0]["lw"], PEN_FALLBACK_WEIGHT);
|
||||
assert_eq!(ops[2]["entity"]["strokeWeight"], 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stift_loeschen_entfernt_verweise() {
|
||||
let p = root(json!({
|
||||
"pens": [{"id": "1", "name": "x"}, {"id": "2", "name": "y"}],
|
||||
"penSets": [{"id": "a", "pens": {"1": {"color": "#1", "weight": 1}, "2": {"color": "#2", "weight": 1}}}],
|
||||
"components": [{"id": "c", "colorPenId": "1", "foregroundPenId": "2"}],
|
||||
"layers": [{"code": "1", "children": [{"code": "2", "colorPenId": "1"}]}],
|
||||
}));
|
||||
let ops = delete_pen_ops(&p, "1");
|
||||
assert_eq!(ops.len(), 4);
|
||||
assert_eq!(ops[0]["kind"], "remove");
|
||||
assert!(ops[1]["entity"]["pens"].get("1").is_none());
|
||||
assert!(ops[2]["entity"].get("colorPenId").is_none());
|
||||
assert_eq!(ops[2]["entity"]["foregroundPenId"], "2");
|
||||
assert!(ops[3]["value"][0]["children"][0].get("colorPenId").is_none());
|
||||
assert!(delete_pen_ops(&p, "9").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standardpalette_anlegen() {
|
||||
let p = root(json!({"components": [{"id": "c", "color": "#000", "colorPenId": "7"}], "layers": []}));
|
||||
let ops = seed_standard_ops(&p, "penset-1", "Standard (CAD-Palette)");
|
||||
assert_eq!(ops[0]["key"], "pens");
|
||||
assert_eq!(ops[1]["collection"], "penSets");
|
||||
assert_eq!(ops[2]["value"], "penset-1");
|
||||
// Bauteil bekommt die Farbe von Stift 7 (Schwarz) aus dem neuen aktiven Satz
|
||||
assert_eq!(ops[3]["entity"]["color"], "#000000");
|
||||
assert_eq!(ops.len(), 4);
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,20 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
|
||||
}
|
||||
}
|
||||
|
||||
/// Abfragen auf der rohen Projekt-Wurzel (JSON-Baum, verlustfrei; Antwort JSON). `text`: Argument als Text/JSON.
|
||||
pub fn run_root(root: &serde_json::Map<String, serde_json::Value>, name: &str, text: &str) -> Result<String, String> {
|
||||
match name {
|
||||
// Stiftsätze ([K4] S3, `pens.rs`): Ops statt Projekt-Kopien.
|
||||
"penRebakeOps" => json(&crate::pens::rebake_ops(root)),
|
||||
"penDeleteOps" => json(&crate::pens::delete_pen_ops(root, text)),
|
||||
"penSeedOps" => {
|
||||
let a: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("penSeedOps: {e}"))?;
|
||||
json(&crate::pens::seed_standard_ops(root, a["id"].as_str().unwrap_or(""), a["name"].as_str().unwrap_or("")))
|
||||
}
|
||||
_ => Err(format!("Unbekannte Wurzel-Abfrage: {name}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Argumente der Gruppen-Abfragen (`containingGroup`: kind/id/path, `expandToGroups`: raw/path).
|
||||
#[derive(serde::Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
|
||||
@@ -196,6 +196,16 @@ pub fn doc_query_args(h: u32, name: &str, args: &[f64], text: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Abfrage auf der rohen Projekt-Wurzel (`crate::queries::run_root`); Fehler wie bei [`doc_query`].
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_query_root(h: u32, name: &str, text: &str) -> String {
|
||||
let result = with_doc(h, |d| crate::queries::run_root(d.root(), name, text)).unwrap_or_else(|| Err("Dokument nicht offen".to_string()));
|
||||
match result {
|
||||
Ok(json) => json,
|
||||
Err(e) => format!("\u{1}{e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Boden-Spuren aller 2D-Zeichnungen als LineList-Vertices `[px, py, pz, r, g, b]` (Float32);
|
||||
/// leer bei Fehler oder ohne Zeichnungen.
|
||||
#[wasm_bindgen]
|
||||
|
||||
@@ -38,6 +38,7 @@ mod plan_dxf;
|
||||
mod plan_print_svg;
|
||||
mod drawings;
|
||||
mod layers;
|
||||
mod pens;
|
||||
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
//! Bindungen der Stift-Paletten (`crate::pens`): zustandslos; die Rechnung auf dem Projekt (Neu-Backen,
|
||||
//! Stift löschen, Standardsatz) läuft als Wurzel-Abfrage (`doc_query_root`). Unbekannter Name = leerer Text.
|
||||
|
||||
use crate::pens;
|
||||
use serde_json::{json, Value};
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
/// Paletten: `freePalette` (48 Farben), `standardPalette` (`{pens, styles}`), `hslToHex` (`arg_json` = `[h, s, l]`).
|
||||
#[wasm_bindgen]
|
||||
pub fn pens_call(name: &str, arg_json: &str) -> String {
|
||||
match name {
|
||||
"freePalette" => json!(pens::free_color_palette()).to_string(),
|
||||
"standardPalette" => {
|
||||
let (p, s) = pens::standard_pen_palette();
|
||||
json!({"pens": p, "styles": s}).to_string()
|
||||
}
|
||||
"hslToHex" => match serde_json::from_str::<Value>(arg_json).ok().as_ref().and_then(Value::as_array) {
|
||||
Some(a) if a.len() == 3 => {
|
||||
let n = |i: usize| a[i].as_f64().unwrap_or(f64::NAN);
|
||||
json!(pens::hsl_to_hex(n(0), n(1), n(2))).to_string()
|
||||
}
|
||||
_ => String::new(),
|
||||
},
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,9 @@ export type LoadFileResult =
|
||||
| { ok: true; project: Project; warnings: string[]; migratedFrom: number | null }
|
||||
| { ok: false; error: string };
|
||||
|
||||
/** Wurzel-Abfragen des Kerns (`queries.rs::run_root`). */
|
||||
export type RootQueryName = "penRebakeOps" | "penDeleteOps" | "penSeedOps";
|
||||
|
||||
/** Abfragen des Kerns (`queries.rs`). */
|
||||
export type QueryName =
|
||||
| "kennzahlen"
|
||||
@@ -124,6 +127,17 @@ export class ProjectDocument {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Abfrage auf dem rohen Projekt-JSON des Kerns (`queries.rs::run_root`): rechnet verlustfrei auf dem
|
||||
* Baum (unbekannte Felder, Schlüsselreihenfolge) und liefert meist Ops. `text`: Argument (Text/JSON).
|
||||
*/
|
||||
queryRoot<T>(name: RootQueryName, text = ""): T {
|
||||
if (!this.handle) throw new Error(`Kern-Abfrage „${name}": Dokument nicht offen`);
|
||||
const out = core().doc_query_root(this.handle, name, text);
|
||||
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
|
||||
return JSON.parse(out) as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* Abfrage mit binärer Antwort (`queries.rs::run_bin`, z. B. `planDomains` als Plan-Puffer v2,
|
||||
* s. `plan/planBuf.ts`). Fehler kommen als Fehlerpuffer (`decodePlanBuf` wirft die Meldung).
|
||||
|
||||
@@ -4,7 +4,8 @@ import {
|
||||
resolvePenColor,
|
||||
resolvePenWeight,
|
||||
rebakePenOps,
|
||||
generateStandardPenPalette,
|
||||
freeColorPalette,
|
||||
deletePenOps,
|
||||
seedStandardPenSetOps,
|
||||
PEN_FALLBACK_COLOR,
|
||||
PEN_FALLBACK_WEIGHT,
|
||||
@@ -146,7 +147,7 @@ describe("rebakePenColors — Ebenen (Farbe UND Strichstärke, inkl. verschachte
|
||||
expect(out.layers[0].lw).toBe(0.7);
|
||||
});
|
||||
|
||||
it("bäckt eine verschachtelte Kategorie (children) und lässt Geschwister ohne Stift unverändert", () => {
|
||||
it("bäckt eine verschachtelte Kategorie (children) und lässt Geschwister ohne Stift inhaltlich unverändert", () => {
|
||||
const child = cat({ code: "21", colorPenId: "2" });
|
||||
const untouchedChild = cat({ code: "22", color: "#untouched" });
|
||||
const parent = cat({ code: "20", children: [child, untouchedChild] });
|
||||
@@ -157,7 +158,7 @@ describe("rebakePenColors — Ebenen (Farbe UND Strichstärke, inkl. verschachte
|
||||
});
|
||||
const out = rebakePenColors(p);
|
||||
expect(out.layers[0].children?.[0].color).toBe("#00ff00");
|
||||
expect(out.layers[0].children?.[1]).toBe(untouchedChild); // referenzgleich, unangetastet
|
||||
expect(out.layers[0].children?.[1]).toEqual(untouchedChild);
|
||||
});
|
||||
|
||||
it("lässt eine Kategorie OHNE Stift-Verweis referenzgleich", () => {
|
||||
@@ -298,8 +299,10 @@ describe("rebakePenColors — Elemente OHNE Strichstärke-Feld (Raum), Robusthei
|
||||
});
|
||||
});
|
||||
|
||||
describe("generateStandardPenPalette", () => {
|
||||
const { pens, styles } = generateStandardPenPalette();
|
||||
describe("Standardpalette (Kern)", () => {
|
||||
const seeded = seedStandardPenSet(baseProject());
|
||||
const pens = seeded.pens!;
|
||||
const styles = seeded.penSets![0].pens;
|
||||
|
||||
it("liefert genau 255 Stifte mit IDs '1'..'255', je Farbe+Strichstärke", () => {
|
||||
expect(pens.length).toBe(255);
|
||||
@@ -353,3 +356,32 @@ describe("seedStandardPenSet", () => {
|
||||
expect(out.components[0].color).toBe("#00ff00");
|
||||
});
|
||||
});
|
||||
|
||||
describe("freeColorPalette", () => {
|
||||
it("liefert 8 Graustufen und 8 × 5 Farbtöne als #rrggbb", () => {
|
||||
const pal = freeColorPalette();
|
||||
expect(pal).toHaveLength(48);
|
||||
expect(pal[0]).toBe("#000000");
|
||||
expect(pal[7]).toBe("#ffffff");
|
||||
for (const c of pal) expect(c).toMatch(/^#[0-9a-f]{6}$/);
|
||||
expect(freeColorPalette()).toBe(pal);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deletePenOps", () => {
|
||||
it("entfernt Stift, Satz-Einträge und alle Verweise (Bauteile, verschachtelte Kategorien)", () => {
|
||||
const p = baseProject({
|
||||
pens: [{ id: "1", name: "a" }, { id: "2", name: "b" }],
|
||||
penSets: [{ id: "s", name: "S", pens: { "1": ps("#111111"), "2": ps("#222222") } }],
|
||||
components: [comp({ colorPenId: "1", foregroundPenId: "2" })],
|
||||
layers: [{ code: "20", name: "x", color: "#000", visible: true, lw: 1, children: [{ code: "21", name: "y", color: "#000", visible: true, lw: 1, colorPenId: "1" }] } as LayerCategory],
|
||||
});
|
||||
const out = applyOps(p, deletePenOps(p, "1"));
|
||||
expect(out.pens!.map((x) => x.id)).toEqual(["2"]);
|
||||
expect(Object.keys(out.penSets![0].pens)).toEqual(["2"]);
|
||||
expect(out.components[0].colorPenId).toBeUndefined();
|
||||
expect(out.components[0].foregroundPenId).toBe("2");
|
||||
expect(out.layers[0].children![0].colorPenId).toBeUndefined();
|
||||
expect(deletePenOps(out, "1")).toEqual([]);
|
||||
});
|
||||
});
|
||||
+45
-216
@@ -1,139 +1,50 @@
|
||||
// Stiftsatz-Auflösung (ArchiCAD-Stiftsatz-Muster) — reine Funktionen, keine
|
||||
// Modell-Mutation. Der Trick, der jeden bestehenden Farb-/Strichstärke-Leser
|
||||
// (2D-Plan, beide 3D-Renderer, DXF-Export, Vorschau-Swatches) UNVERÄNDERT
|
||||
// lässt: `Component.color`/`.foreground`/`.background`, `LayerCategory.color`/
|
||||
// `.lw` bzw. die Element-Felder (`color`/`strokeWeight`/`weightMm`) bleiben
|
||||
// IMMER die eine gültige, aufgelöste Farbe/Strichstärke. Ein Stift-Verweis
|
||||
// (`xxxPenId`) schreibt diese Felder nur bei Gelegenheit (Stiftsatz-Wechsel,
|
||||
// Stift-Änderung, neue Zuweisung) per `rebakePenColors` aus dem aktiven
|
||||
// Stiftsatz NEU — kein Leser muss je einen Stift auflösen.
|
||||
// Stiftsatz-Auflösung (ArchiCAD-Stiftsatz-Muster) im Rust-Kern ([K4] S3, `src-tauri/core/src/pens.rs`).
|
||||
// Der Trick, der jeden bestehenden Farb-/Strichstärke-Leser (2D-Plan, beide 3D-Renderer, DXF-Export,
|
||||
// Vorschau-Swatches) UNVERÄNDERT lässt: `Component.color`/`.foreground`/`.background`,
|
||||
// `LayerCategory.color`/`.lw` bzw. die Element-Felder (`color`/`strokeWeight`/`weightMm`) bleiben
|
||||
// IMMER die eine gültige, aufgelöste Farbe/Strichstärke. Ein Stift-Verweis (`xxxPenId`) schreibt diese
|
||||
// Felder nur bei Gelegenheit (Stiftsatz-Wechsel, Stift-Änderung, neue Zuweisung) per `rebakePenOps` aus
|
||||
// dem aktiven Stiftsatz NEU — kein Leser muss je einen Stift auflösen.
|
||||
//
|
||||
// Ein Stift (`PenStyle`) trägt Farbe UND Strichstärke zusammen (wie ein
|
||||
// echter ArchiCAD-/AutoCAD-Stift) — beide wandern gemeinsam, wenn ein
|
||||
// Element/eine Ebene auf „Stift" statt „Frei" gestellt wird.
|
||||
// Ein Stift (`PenStyle`) trägt Farbe UND Strichstärke zusammen (wie ein echter ArchiCAD-/AutoCAD-Stift).
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
// Im Kern: Standardpalette (255 Stifte, rein prozedural per HSL, keine externe Bibliothek, Stifte 1–9 und
|
||||
// 250–255 wie `ACI_PALETTE` in `export/exportDxf.ts`), Freie-Farbe-Palette, Neu-Backen und das Entfernen
|
||||
// von Stift-Verweisen. Hier bleiben nur die Lese-Auflösung einzelner Stifte (O(1), je Swatch im Render) und
|
||||
// dünne Fassaden, die die Ops des Kerns liefern (`documentFor(project)`: das Kern-Dokument folgt dem Projekt).
|
||||
//
|
||||
// Bewusst NICHT abgedeckt: Layout-Annotationen (`Layout.annotations[]`) und `Tür`/`ExtrudedSolid`/Kontext-
|
||||
// Objekte — kein `colorPenId`-Feld dort (Scope-Entscheid, s. PENDENZEN.md).
|
||||
|
||||
import type { ColorPen, Component, LayerCategory, PenSet, PenStyle, Project } from "./types";
|
||||
import { applyOps } from "../core/ops";
|
||||
import type { PenStyle, Project } from "./types";
|
||||
import type { CoreOp } from "../core/ops";
|
||||
import { addItems, fieldOps, patchItems, setFieldIfChanged } from "../core/opsBuild";
|
||||
import { documentFor } from "../core/document";
|
||||
import { core } from "../engine/coreWasm";
|
||||
|
||||
/** Farbe eines Stifts, der im aktiven Stiftsatz (noch) keinen Eintrag hat. */
|
||||
export const PEN_FALLBACK_COLOR = "#9aa0a6";
|
||||
/** Strichstärke (mm) eines Stifts, der im aktiven Stiftsatz (noch) keinen Eintrag hat. */
|
||||
export const PEN_FALLBACK_WEIGHT = 0.18;
|
||||
|
||||
/** HSL (h in Grad 0..360, s/l in 0..1) → "#rrggbb". Reine Konvertierung, keine Bibliothek nötig. */
|
||||
export function hslToHex(h: number, s: number, l: number): string {
|
||||
const c = (1 - Math.abs(2 * l - 1)) * s;
|
||||
const hp = (((h % 360) + 360) % 360) / 60;
|
||||
const x = c * (1 - Math.abs((hp % 2) - 1));
|
||||
const [r1, g1, b1] =
|
||||
hp < 1 ? [c, x, 0] : hp < 2 ? [x, c, 0] : hp < 3 ? [0, c, x] : hp < 4 ? [0, x, c] : hp < 5 ? [x, 0, c] : [c, 0, x];
|
||||
const m = l - c / 2;
|
||||
const toHex = (v: number) => Math.round((v + m) * 255).toString(16).padStart(2, "0");
|
||||
return `#${toHex(r1)}${toHex(g1)}${toHex(b1)}`;
|
||||
let freePalette: string[] | null = null;
|
||||
|
||||
/**
|
||||
* Feste Freie-Farbe-Palette für den Palette-Popover (`ui/PenColorField.tsx`): 8 Graustufen (Schwarz→Weiss)
|
||||
* + 8 Farbtöne × 5 Helligkeitsstufen = 48 Swatches. Aus dem Kern (erst nach `initCore()` lesbar, daher
|
||||
* eine Funktion, kein Modul-Wert); jeder Aufruf liefert dieselbe Liste.
|
||||
*/
|
||||
export function freeColorPalette(): string[] {
|
||||
if (!freePalette) freePalette = JSON.parse(core().pens_call("freePalette", "")) as string[];
|
||||
return freePalette;
|
||||
}
|
||||
|
||||
/**
|
||||
* Feste Freie-Farbe-Palette für den Palette-Popover (`ui/PenColorField.tsx`):
|
||||
* 8 Graustufen (Schwarz→Weiss) + 8 Farbtöne × 5 Helligkeitsstufen = 48
|
||||
* Swatches. Rein prozedural (HSL), dieselbe Begründung wie
|
||||
* `generateStandardPenPalette` — kein externes Farbschema.
|
||||
*/
|
||||
export const FREE_COLOR_PALETTE: string[] = (() => {
|
||||
const out: string[] = [];
|
||||
for (let i = 0; i < 8; i++) {
|
||||
const v = Math.round((i / 7) * 255);
|
||||
out.push(`#${v.toString(16).padStart(2, "0").repeat(3)}`);
|
||||
}
|
||||
for (let hue = 0; hue < 8; hue++) {
|
||||
for (let level = 0; level < 5; level++) {
|
||||
out.push(hslToHex(hue * 45, 0.75, 0.75 - level * 0.14));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
})();
|
||||
|
||||
/**
|
||||
* Generiert 255 Stifte + einen passenden Stiftsatz nach klassischer CAD-
|
||||
* Nummerierungs-Konvention (AutoCAD Color Index / ArchiCAD-Stiftsätze): Stifte
|
||||
* 1–9 die Grundfarben (Rot/Gelb/Grün/Cyan/Blau/Magenta/Schwarz/zwei Grautöne —
|
||||
* dieselben Werte wie die bestehende `ACI_PALETTE` in `export/exportDxf.ts`,
|
||||
* damit beide Stellen konsistent bleiben), 10–249 24 Farbtöne × 10 Helligkeits-/
|
||||
* Sättigungsstufen (prozedural per HSL erzeugt), 250–255 ein Graustufen-Keil
|
||||
* (identische Werte wie `ACI_PALETTE`s 250–255). **Keine externe Bibliothek
|
||||
* oder ein konkretes lizenziertes Farbschema** — reine Mathematik (HSL-Kreis),
|
||||
* daher lizenzfrei; strukturell an die altbekannte 255-Stift-Konvention aus
|
||||
* AutoCAD/ArchiCAD angelehnt, nicht Pixel-für-Pixel identisch mit deren
|
||||
* (proprietärer) Originaltabelle. Strichstärke einheitlich `PEN_FALLBACK_WEIGHT`
|
||||
* (0.18 mm) — im Stiftsatz-Tab pro Stift frei änderbar.
|
||||
*/
|
||||
export function generateStandardPenPalette(): { pens: ColorPen[]; styles: Record<string, PenStyle> } {
|
||||
const pens: ColorPen[] = [];
|
||||
const styles: Record<string, PenStyle> = {};
|
||||
const add = (id: number, name: string, color: string) => {
|
||||
pens.push({ id: String(id), name });
|
||||
styles[String(id)] = { color, weight: PEN_FALLBACK_WEIGHT };
|
||||
};
|
||||
|
||||
// 1–9: Grundfarben (wie ACI_PALETTE in exportDxf.ts).
|
||||
add(1, "Rot", "#ff0000");
|
||||
add(2, "Gelb", "#ffff00");
|
||||
add(3, "Grün", "#00ff00");
|
||||
add(4, "Cyan", "#00ffff");
|
||||
add(5, "Blau", "#0000ff");
|
||||
add(6, "Magenta", "#ff00ff");
|
||||
add(7, "Schwarz", "#000000");
|
||||
add(8, "Dunkelgrau", "#414141");
|
||||
add(9, "Grau", "#808080");
|
||||
|
||||
// 10–249: 24 Farbtöne (15°-Schritte) × 10 Stufen (5 gesättigt hell→dunkel,
|
||||
// 5 entsättigt hell→dunkel) — 240 Stifte.
|
||||
let id = 10;
|
||||
for (let hue = 0; hue < 24; hue++) {
|
||||
const h = hue * 15;
|
||||
for (let step = 0; step < 10; step++) {
|
||||
const saturated = step < 5;
|
||||
const level = step % 5; // 0..4
|
||||
const l = 0.75 - level * 0.14; // 0.75 → 0.19
|
||||
const s = saturated ? 0.85 : 0.4;
|
||||
add(id, `Stift ${id}`, hslToHex(h, s, l));
|
||||
id++;
|
||||
}
|
||||
}
|
||||
|
||||
// 250–255: Graustufen-Keil (wie ACI_PALETTE).
|
||||
const greys: [number, string][] = [
|
||||
[250, "#333333"],
|
||||
[251, "#5b5b5b"],
|
||||
[252, "#848484"],
|
||||
[253, "#adadad"],
|
||||
[254, "#d6d6d6"],
|
||||
[255, "#ffffff"],
|
||||
];
|
||||
for (const [gid, color] of greys) add(gid, `Grau ${gid}`, color);
|
||||
|
||||
return { pens, styles };
|
||||
}
|
||||
|
||||
/**
|
||||
* Setzt `Project.pens`/`penSets` auf die generierte 255er-Standardpalette
|
||||
* (s. {@link generateStandardPenPalette}) — ERSETZT bestehende `pens`/den neu
|
||||
* angelegten Satz vollständig (kein Merge), gedacht für den Erststart, bevor
|
||||
* eigene Stifte/Sätze existieren. Der neue Satz wird aktiv, wenn noch KEIN
|
||||
* Stiftsatz aktiv war (dieselbe Konvention wie `addPenSet`).
|
||||
* Setzt `Project.pens`/`penSets` auf die generierte 255er-Standardpalette — ERSETZT bestehende `pens`
|
||||
* vollständig (kein Merge), gedacht für den Erststart. Der neue Satz wird aktiv, wenn noch KEIN Stiftsatz
|
||||
* aktiv war.
|
||||
*/
|
||||
export function seedStandardPenSetOps(project: Project): CoreOp[] {
|
||||
const { pens, styles } = generateStandardPenPalette();
|
||||
const penSet: PenSet = { id: `penset-${Date.now()}`, name: "Standard (CAD-Palette)", pens: styles };
|
||||
const stateOps = [
|
||||
...fieldOps(project, "pens", pens),
|
||||
...addItems("penSets", [penSet]),
|
||||
...setFieldIfChanged(project, "activePenSetId", project.activePenSetId ?? penSet.id),
|
||||
];
|
||||
return [...stateOps, ...rebakePenOps(applyOps(project, stateOps))];
|
||||
return documentFor(project).queryRoot<CoreOp[]>("penSeedOps", JSON.stringify({ id: `penset-${Date.now()}`, name: "Standard (CAD-Palette)" }));
|
||||
}
|
||||
|
||||
/** Der aktuell aktive Stiftsatz, oder `undefined` (kein Stiftsatz angelegt/aktiviert). */
|
||||
@@ -156,102 +67,20 @@ export function resolvePenWeight(project: Project, penId: string): number {
|
||||
return resolvePenStyle(project, penId)?.weight ?? PEN_FALLBACK_WEIGHT;
|
||||
}
|
||||
|
||||
/** Bäckt die Stift-Farbe(n) EINES Bauteils neu (reine Funktion, unverändert wenn kein Stift gesetzt). */
|
||||
function bakeComponent(project: Project, c: Component): Component {
|
||||
if (!c.colorPenId && !c.foregroundPenId && !c.backgroundPenId) return c;
|
||||
return {
|
||||
...c,
|
||||
...(c.colorPenId ? { color: resolvePenColor(project, c.colorPenId) } : {}),
|
||||
...(c.foregroundPenId ? { foreground: resolvePenColor(project, c.foregroundPenId) } : {}),
|
||||
...(c.backgroundPenId ? { background: resolvePenColor(project, c.backgroundPenId) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Bäckt Farbe UND Strichstärke (`.lw`) EINER Ebenen-Kategorie neu (rekursiv über `children`). */
|
||||
function bakeCategory(project: Project, cat: LayerCategory): LayerCategory {
|
||||
const next: LayerCategory = cat.colorPenId
|
||||
? { ...cat, color: resolvePenColor(project, cat.colorPenId), lw: resolvePenWeight(project, cat.colorPenId) }
|
||||
: cat;
|
||||
if (!cat.children) return next;
|
||||
const children = cat.children.map((c) => bakeCategory(project, c));
|
||||
return children === cat.children ? next : { ...next, children };
|
||||
}
|
||||
|
||||
/**
|
||||
* Bäckt die eigene `color`-Stift-Kopplung EINES Modell-Elements neu (nur
|
||||
* Farbe — für Elementarten ohne eigenes Strichstärke-Override-Feld: Dach,
|
||||
* Öffnung, Treppe, Raum). Unverändert (referenzgleich), wenn kein Stift
|
||||
* gesetzt ist.
|
||||
*/
|
||||
function bakeElementColor<T extends { colorPenId?: string; color?: string }>(
|
||||
project: Project,
|
||||
x: T,
|
||||
): T {
|
||||
return x.colorPenId ? { ...x, color: resolvePenColor(project, x.colorPenId) } : x;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wie {@link bakeElementColor}, zusätzlich (a) die Strichstärke unter
|
||||
* `weightKey` (Wand/Decke/Stütze: `strokeWeight`; Drawing2D: `weightMm`) —
|
||||
* nur über `colorPenId` gekoppelt (ein Stift trägt Farbe UND Strichstärke
|
||||
* zusammen; Vordergrund/Hintergrund sind reine Musterfarben ohne
|
||||
* Strichstärke-Aspekt) — und (b) die Attribut-Override-Farben `foreground`/
|
||||
* `background` DIESER Element-Instanz, unabhängig über `foregroundPenId`/
|
||||
* `backgroundPenId` (analog `Component.foregroundPenId`/`backgroundPenId`,
|
||||
* nur eben am Element statt am Bauteil). Für Elementarten MIT eigenem
|
||||
* Strichstärke- UND Vordergrund/Hintergrund-Override-Feld (Wand/Decke/
|
||||
* Stütze/Drawing2D — exakt dieselben vier wie bei der Strichstärke).
|
||||
*/
|
||||
function bakeElementColorAndWeight<
|
||||
T extends {
|
||||
colorPenId?: string;
|
||||
color?: string;
|
||||
foregroundPenId?: string;
|
||||
foreground?: string;
|
||||
backgroundPenId?: string;
|
||||
background?: string;
|
||||
},
|
||||
K extends string,
|
||||
>(project: Project, x: T & Partial<Record<K, number>>, weightKey: K): T {
|
||||
if (!x.colorPenId && !x.foregroundPenId && !x.backgroundPenId) return x;
|
||||
return {
|
||||
...x,
|
||||
...(x.colorPenId
|
||||
? { color: resolvePenColor(project, x.colorPenId), [weightKey]: resolvePenWeight(project, x.colorPenId) }
|
||||
: {}),
|
||||
...(x.foregroundPenId ? { foreground: resolvePenColor(project, x.foregroundPenId) } : {}),
|
||||
...(x.backgroundPenId ? { background: resolvePenColor(project, x.backgroundPenId) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Schreibt für JEDES Bauteil/JEDE Ebenen-Kategorie/JEDES Modell-Element mit
|
||||
* gesetztem Stift die Farbe (+ ggf. Strichstärke) des AKTIVEN Stiftsatzes in
|
||||
* `color`/`foreground`/`background`/`lw`/`strokeWeight`/`weightMm` — reine
|
||||
* Funktion, liefert ein neues `Project` (unveränderte Teile bleiben
|
||||
* referenzgleich). Aufzurufen nach: Stiftsatz-Wechsel, Änderung EINES Stifts
|
||||
* im aktiven Satz, oder Neuzuweisung eines Stifts an ein Bauteil/eine Ebene
|
||||
* (dort reicht meist ein direkter Patch, s. `resolvePenColor`/
|
||||
* `resolvePenWeight` — diese Funktion ist für die FLÄCHIGEN Fälle, die viele
|
||||
* Objekte auf einmal betreffen).
|
||||
*
|
||||
* Bewusst NICHT abgedeckt: Layout-Annotationen (`Layout.annotations[]`,
|
||||
* verschachtelt in `Project.layouts`) und `Tür`/`ExtrudedSolid`/Kontext-
|
||||
* Objekte — kein `colorPenId`-Feld dort (Scope-Entscheid, s. PENDENZEN.md).
|
||||
* Ops, die für JEDES Bauteil/JEDE Ebenen-Kategorie/JEDES Modell-Element mit gesetztem Stift die Farbe
|
||||
* (+ ggf. Strichstärke) des AKTIVEN Stiftsatzes in `color`/`foreground`/`background`/`lw`/`strokeWeight`/
|
||||
* `weightMm` schreiben; nur wirklich geänderte Elemente. Aufzurufen nach: Stiftsatz-Wechsel, Änderung EINES
|
||||
* Stifts im aktiven Satz oder Neuzuweisung eines Stifts (dort reicht meist ein direkter Patch).
|
||||
*/
|
||||
export function rebakePenOps(project: Project): CoreOp[] {
|
||||
const all = () => true;
|
||||
const layers = project.layers.map((cat) => bakeCategory(project, cat));
|
||||
return [
|
||||
...patchItems(project, "components", all, (c) => bakeComponent(project, c)),
|
||||
...(layers.every((c, i) => c === project.layers[i]) ? [] : fieldOps(project, "layers", layers)),
|
||||
...patchItems(project, "walls", all, (w) => bakeElementColorAndWeight(project, w, "strokeWeight")),
|
||||
...patchItems(project, "drawings2d", all, (d) => bakeElementColorAndWeight(project, d, "weightMm")),
|
||||
...patchItems(project, "ceilings", all, (c) => bakeElementColorAndWeight(project, c, "strokeWeight")),
|
||||
...patchItems(project, "columns", all, (c) => bakeElementColorAndWeight(project, c, "strokeWeight")),
|
||||
...patchItems(project, "roofs", all, (r) => bakeElementColor(project, r)),
|
||||
...patchItems(project, "openings", all, (o) => bakeElementColor(project, o)),
|
||||
...patchItems(project, "stairs", all, (s) => bakeElementColor(project, s)),
|
||||
...patchItems(project, "rooms", all, (r) => bakeElementColor(project, r)),
|
||||
];
|
||||
return documentFor(project).queryRoot<CoreOp[]>("penRebakeOps");
|
||||
}
|
||||
|
||||
/**
|
||||
* Ops zum Löschen des Stifts `penId`: aus `pens` und allen Stiftsätzen entfernen und die Verweise
|
||||
* (`colorPenId`/`foregroundPenId`/`backgroundPenId`) in Bauteilen und im Kategorien-Baum löschen.
|
||||
*/
|
||||
export function deletePenOps(project: Project, penId: string): CoreOp[] {
|
||||
return documentFor(project).queryRoot<CoreOp[]>("penDeleteOps", penId);
|
||||
}
|
||||
@@ -51,6 +51,7 @@ import type {
|
||||
} from "../model/types";
|
||||
import {
|
||||
activePenSet,
|
||||
deletePenOps,
|
||||
rebakePenOps,
|
||||
seedStandardPenSetOps,
|
||||
PEN_FALLBACK_COLOR,
|
||||
@@ -920,31 +921,7 @@ export function createProjectSlice(
|
||||
|
||||
renamePen: (id, name) => applyChange((p) => patchItem(p, "pens", id, { name })),
|
||||
|
||||
deletePen: (id) =>
|
||||
applyChange((p) => {
|
||||
const clearPenRefs = <T extends { colorPenId?: string; foregroundPenId?: string; backgroundPenId?: string }>(x: T): T =>
|
||||
x.colorPenId === id || x.foregroundPenId === id || x.backgroundPenId === id
|
||||
? {
|
||||
...x,
|
||||
colorPenId: x.colorPenId === id ? undefined : x.colorPenId,
|
||||
foregroundPenId: x.foregroundPenId === id ? undefined : x.foregroundPenId,
|
||||
backgroundPenId: x.backgroundPenId === id ? undefined : x.backgroundPenId,
|
||||
}
|
||||
: x;
|
||||
const clearCategoryPenRefs = (cat: LayerCategory): LayerCategory => ({
|
||||
...(cat.colorPenId === id ? { ...cat, colorPenId: undefined } : cat),
|
||||
...(cat.children ? { children: cat.children.map(clearCategoryPenRefs) } : {}),
|
||||
});
|
||||
return [
|
||||
...removeItems(p, "pens", [id]),
|
||||
...patchItems(p, "penSets", () => true, (s) => {
|
||||
const { [id]: _removed, ...rest } = s.pens;
|
||||
return { ...s, pens: rest };
|
||||
}),
|
||||
...patchItems(p, "components", () => true, clearPenRefs),
|
||||
...fieldOps(p, "layers", p.layers.map(clearCategoryPenRefs)),
|
||||
];
|
||||
}),
|
||||
deletePen: (id) => applyChange((p) => deletePenOps(p, id)),
|
||||
|
||||
addPenSet: () =>
|
||||
applyChange((p) => {
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
// Manager läuft auch als eigenes natives Fenster ohne gemeinsamen Store.
|
||||
|
||||
import { useState } from "react";
|
||||
import { FREE_COLOR_PALETTE } from "../model/penSets";
|
||||
import { freeColorPalette } from "../model/penSets";
|
||||
import { MATERIAL_PALETTE, RAL_CLASSIC, TANGO_PALETTE } from "../model/color";
|
||||
import type { BuiltinPaletteBanks, CustomPalette } from "../model/types";
|
||||
import { Swatch } from "./ColorSwatchCell";
|
||||
@@ -59,7 +59,7 @@ export function FreeColorPicker({
|
||||
banks.push({
|
||||
id: "simple",
|
||||
label: t("pen.paletteSimple"),
|
||||
entries: FREE_COLOR_PALETTE.map((hex) => ({ hex, title: hex })),
|
||||
entries: freeColorPalette().map((hex) => ({ hex, title: hex })),
|
||||
});
|
||||
}
|
||||
if (builtinBanks?.tango !== false) {
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
import { useState } from "react";
|
||||
import type { BuiltinPaletteBank, Project } from "../../model/types";
|
||||
import { MATERIAL_PALETTE, RAL_CLASSIC, TANGO_PALETTE } from "../../model/color";
|
||||
import { FREE_COLOR_PALETTE } from "../../model/penSets";
|
||||
import { freeColorPalette } from "../../model/penSets";
|
||||
import { t } from "../../i18n";
|
||||
import { DeleteButton, EmptyState, FieldRow, TextField } from "./fields";
|
||||
|
||||
@@ -20,15 +20,16 @@ import { DeleteButton, EmptyState, FieldRow, TextField } from "./fields";
|
||||
* Die vier mitgelieferten Bänke. `labelKey` statt fertigem Label, damit `t()`
|
||||
* erst zur RENDERZEIT läuft (Sprachwechsel wirkt sonst nicht — gleiche
|
||||
* Konvention wie `PATTERN_OPTIONS` in `HatchesTab.tsx`); Eigennamen
|
||||
* (Tango/Material/RAL) stehen direkt in `label`.
|
||||
* (Tango/Material/RAL) stehen direkt in `label`. Eine Funktion, weil die Freie-Farbe-Palette aus dem
|
||||
* Kern kommt (erst nach `initCore()` lesbar).
|
||||
*/
|
||||
const BUILTIN_BANKS: {
|
||||
const builtinBanks = (): {
|
||||
id: BuiltinPaletteBank;
|
||||
label?: string;
|
||||
labelKey?: string;
|
||||
preview: string[];
|
||||
}[] = [
|
||||
{ id: "simple", labelKey: "pen.paletteSimple", preview: FREE_COLOR_PALETTE },
|
||||
}[] => [
|
||||
{ id: "simple", labelKey: "pen.paletteSimple", preview: freeColorPalette() },
|
||||
{ id: "tango", label: "Tango", preview: TANGO_PALETTE.map((c) => c.hex) },
|
||||
{ id: "material", label: "Material", preview: MATERIAL_PALETTE.map((c) => c.hex) },
|
||||
{ id: "ral", label: "RAL Classic", preview: RAL_CLASSIC.map((c) => c.hex) },
|
||||
@@ -73,7 +74,7 @@ export function PalettesTab({
|
||||
{/* Mitgelieferte Bänke: nur ein/aus — Inhalt ist fest. */}
|
||||
<div className="res-fields">
|
||||
<div className="res-section-label">{t("resources.palettes.builtin")}</div>
|
||||
{BUILTIN_BANKS.map((bank) => (
|
||||
{builtinBanks().map((bank) => (
|
||||
<FieldRow
|
||||
key={bank.id}
|
||||
label={bank.label ?? t(bank.labelKey!)}
|
||||
|
||||
Reference in new issue
Block a user