[124] Merge: Kern prüft neue Ops gegen das typisierte Modell (Batch-Rollback), json_util, erste Befehle typisiert

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-11-03 22:56:53 +00:00
commit 137afdda84
31 files changed
+733 -311

No files matched your search

+14 -1
View File
@@ -1115,8 +1115,21 @@ Prüfung des ganzen Programms (Rust-Kern, TS-Hülle, Build/Sicherheit), nur Code
e2e `transform.spec.ts`. Geändert gegenüber vorher: Spiegeln per Knopf/Tippen bewegt jetzt wie per Taste das
Original (vorher Kopie), getippte Zahl nach dem Drehzentrum gilt als Distanz-Punkt (vorher ignoriert).
Offen: ungenutzte i18n-Schlüssel (`cmd.move.base` …, `transform.bar` …) aufräumen; nicht in der Tauri-App geprüft. · M 3.11. Nachtrag: Spiegeln mit Vorgabe Kopie (Original bleibt, wie AutoCAD/Rhino; Entscheid Maintainer), U spiegelt das Original.
- ○ **[124] Kern typisiert.** 152 Funktionen lesen rohes JSON (`grips::field/num_of`); Ops gegen Modell prüfen,
- ◐ **[124] Kern typisiert.** 152 Funktionen lesen rohes JSON (`grips::field/num_of`); Ops gegen Modell prüfen,
`cmd_*` auf `&Project`. · L
3.11. Stufe 1: (1) `apply_checked` prüft neue Werte gegen das Modell (`model/check.rs`: `add`/`replace`-Elemente,
`setField`; gleiche Lese-Logik wie die typisierte Sicht) → ganze Folge zurück, Meldung mit Liste, id, Feldpfad,
serde-Fehler. Laden bleibt tolerant; ein Element mit Alt-Fehler darf ihn behalten, aber keinen neuen bekommen.
Tiefe NaN-Marken werden vor der Prüfung null (Pflichtfeld → abgelehnt; vorher still als null gespeichert).
Kosten: ~5 µs je kleiner Änderung (Musterhaus komplex, 1000 Änderungen nativ: Commit ~280–330 µs vorher wie
nachher, im Rauschen; Messung `tausend_kleine_aenderungen_musterhaus`). Kein Erzeuger musste korrigiert werden
(cargo test, vitest inkl. beider Musterhäuser als Op-Folge, e2e). (2) JSON-Hilfen `grips` → `json_util.rs`.
(3) Muster `&Project` in den Befehlen: `commands::ops`/`cmd_create`/`cmd_solid::ops` bekommen die typisierte
Sicht (`Document::project_lookup`); typisiert: Kategorie-Suche, aktiver Wandtyp, Raumerkennungs-Wände, Raumzahl,
Tür-/Fenstertyp (Decke, Raum, Treppe, Öffnung, Dach, Dachfenster, Gaube). **Offen:** übrige Leser in `cmd_draw`,
`cmd_edit`, `cmd_transform`, `cmd_wall_edit`, `cmd_split`, `cmd_paste`, Rest `cmd_solid`/`cmd_create` (Wand,
Picks, Extrusion), `grips`, `selection_info`, `dim_assoc`, `pens`, `layers`, `geo_translate`, Importe; Einfügen
einer Kopie eines Alt-Fehler-Elements (`add`) wird jetzt abgelehnt. Nicht in der Tauri-App geprüft.
- ✅ **[125] Doppelte Schnitt-Dominanz** (`render3d/section_boolean.rs` ↔ `core/plan_section.rs`) auf eine Fassung. · S
3.11.: eine Fassung `dossier_hatch::section_dominance` (f64, JS-`min/max`, Schneider-Vorauswahl `ugrid` — mit
`ugrid` aus dem Kern nach `hatchgen` verschoben); `core/plan/section.rs` und `render3d/section_boolean.rs` sind
+85 -87
View File
@@ -16,9 +16,10 @@
//! Elemente mit der Schlüsselreihenfolge der früheren Objekt-Literale.
use crate::cmd_transform::{IdGen, Shapes};
use crate::grips::{arr, field, js_num, num_of, pt, truthy, xy};
use crate::json_util::{arr, field, js_num, num_of, pt, truthy, xy};
use crate::jsmath::hypot2;
use crate::jsnum;
use crate::model::{LayerCategory, Project};
use crate::ops::{id_of, Op};
use kernel2d::{self as k, Vec2 as P};
use serde_json::{json, Map, Value};
@@ -226,35 +227,38 @@ pub(crate) fn point_segment_distance(p: V, a: V, b: V) -> f64 {
// ── Projekt lesen ────────────────────────────────────────────────────────────
/// Gibt es die Kategorie `code` irgendwo im Ebenen-Baum (`layers`, rekursiv über `children`)?
pub(crate) fn has_category(root: &Map<String, Value>, code: &str) -> bool {
fn walk(list: &[Value], code: &str) -> bool {
list.iter().any(|c| field(c, "code").and_then(Value::as_str) == Some(code) || walk(arr(field(c, "children")), code))
// Lesen über die typisierte Sicht (`&Project`, [124]): Muster für die weiteren Befehle. Neue Elemente
// entstehen weiter als JSON (Schlüsselreihenfolge der früheren Objekt-Literale).
/// Erste Kategorie `code` im Ebenen-Baum (Tiefensuche über `children`, wie `flat.find`).
fn find_category<'a>(list: &'a [LayerCategory], code: &str) -> Option<&'a LayerCategory> {
for c in list {
if c.code == code {
return Some(c);
}
if let Some(f) = c.children.as_deref().and_then(|ch| find_category(ch, code)) {
return Some(f);
}
}
walk(arr(root.get("layers")), code)
None
}
/// Gibt es die Kategorie `code` irgendwo im Ebenen-Baum (`layers`, rekursiv über `children`)?
pub(crate) fn has_category(p: &Project, code: &str) -> bool {
find_category(&p.layers, code).is_some()
}
/// Kategorie `code`, falls vorhanden, sonst die aktive.
pub(crate) fn category_or(root: &Map<String, Value>, code: &str, ctx: &Ctx) -> Value {
s(if has_category(root, code) { code } else { ctx.cat })
pub(crate) fn category_or(p: &Project, code: &str, ctx: &Ctx) -> Value {
s(if has_category(p, code) { code } else { ctx.cat })
}
/// Farbe der Kategorie `code` (erste im Baum, Tiefensuche wie `flat.find`), sonst `def`.
fn category_color(root: &Map<String, Value>, code: &str, def: &str) -> Value {
fn walk<'a>(list: &'a [Value], code: &str) -> Option<&'a Value> {
for c in list {
if field(c, "code").and_then(Value::as_str) == Some(code) {
return Some(c);
}
if let Some(f) = walk(arr(field(c, "children")), code) {
return Some(f);
}
}
None
}
match walk(arr(root.get("layers")), code).and_then(|c| field(c, "color")) {
None | Some(Value::Null) => s(def),
Some(c) => c.clone(),
/// Farbe der Kategorie `code` (erste im Baum), sonst `def` (auch bei leerer Farbe: fehlt sie in der
/// Datei, liest die typisierte Sicht "").
fn category_color(p: &Project, code: &str, def: &str) -> Value {
match find_category(&p.layers, code) {
Some(c) if !c.color.is_empty() => s(&c.color),
_ => s(def),
}
}
@@ -268,12 +272,10 @@ fn active_wall_type<'a>(root: &'a Map<String, Value>, ctx: &Ctx) -> Option<&'a V
list.iter().find(|t| id_of(t) == Some(ctx.wall_type)).or(list.first())
}
/// id des aktiven Wandtyps (Fallback: die id aus dem Kontext).
fn active_wall_type_id(root: &Map<String, Value>, ctx: &Ctx) -> Value {
match active_wall_type(root, ctx) {
Some(t) => field(t, "id").cloned().unwrap_or(Value::Null),
None => s(ctx.wall_type),
}
/// id des aktiven Wandtyps (Fallback: erster Typ, sonst die id aus dem Kontext).
fn active_wall_type_id(p: &Project, ctx: &Ctx) -> Value {
let t = p.wall_types.iter().find(|t| t.id == ctx.wall_type).or(p.wall_types.first());
s(t.map_or(ctx.wall_type, |t| t.id.as_str()))
}
/// Gesamtdicke eines Wand-/Deckentyps (`wallTypeThickness`: Summe der Schichten).
@@ -351,11 +353,11 @@ fn wall_type_for_thickness(root: &Map<String, Value>, base: &Value, thickness: f
/// Wand-Befehl: je Achssegment eine Wand des aktiven Typs (Null-Strecken übersprungen); eine gelockte
/// Dicke (einschichtig) wählt/erzeugt den passenden Wandtyp.
fn wall_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
fn wall_ops(root: &Map<String, Value>, p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
let pts = pts_of(v, "pts");
let height = ctx.floor_height.unwrap_or(DEF_HEIGHT);
let mut type_ops = Vec::new();
let mut type_id = active_wall_type_id(root, ctx);
let mut type_id = active_wall_type_id(p, ctx);
if let (Some(base), Some(t)) = (active_wall_type(root, ctx), opt_n(v, "thick")) {
if layers_len(base) == 1 && t >= MIN_THICKNESS && (t - type_thickness(base)).abs() > 1e-4 {
let (o, id) = wall_type_for_thickness(root, base, t, ids);
@@ -441,7 +443,7 @@ fn abs_area(pts: &[V]) -> f64 {
}
/// Decke aus einem geschlossenen Umriss (entartet → nichts).
fn ceiling_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
fn ceiling_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
let Some(outline) = normalize_outline(&pts_of(v, "pts")) else { return Vec::new() };
if abs_area(&outline) < 1e-4 {
return Vec::new();
@@ -452,28 +454,23 @@ fn ceiling_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen)
("id", s(&ids.next("C"))),
("type", s("ceiling")),
("floorId", s(ctx.level)),
("categoryCode", category_or(root, "30", ctx)),
("categoryCode", category_or(p, "30", ctx)),
("outline", pvs(&outline)),
("wallTypeId", active_wall_type_id(root, ctx)),
("wallTypeId", active_wall_type_id(p, ctx)),
])],
)
}
/// Wände des Geschosses als `[n, (ax, ay, bx, by, dicke)…]` für die Raumerkennung.
fn floor_walls_flat(root: &Map<String, Value>, level: &str) -> Vec<f64> {
let types = wall_types(root);
fn floor_walls_flat(p: &Project, level: &str) -> Vec<f64> {
let mut out = vec![0.0];
let mut n = 0;
for w in arr(root.get("walls")) {
if floor_of(w) != Some(level) {
continue;
}
let tid = field(w, "wallTypeId").and_then(Value::as_str);
let wt = types.iter().find(|t| id_of(t) == tid);
let (a, b) = (xy(field(w, "start").unwrap_or(&Value::Null)), xy(field(w, "end").unwrap_or(&Value::Null)));
let t = wt.map_or(0.2, type_thickness);
for w in p.walls.iter().filter(|w| w.floor_id == level) {
let wt = p.wall_types.iter().find(|t| t.id == w.wall_type_id);
// Summe der Schichten wie `type_thickness` (Startwert 0, Reihenfolge der Liste).
let t = wt.map_or(0.2, |t| t.layers.iter().fold(0.0, |sum, l| sum + l.thickness));
// Bogenwand ([T2]): als Sehnenzug.
let pts = crate::wall_arc::axis_polyline(a, b, bulge_of(w), 0.0, t);
let pts = crate::wall_arc::axis_polyline((w.start.x, w.start.y), (w.end.x, w.end.y), w.bulge, 0.0, t);
for q in pts.windows(2) {
out.extend([q[0].0, q[0].1, q[1].0, q[1].1, t]);
n += 1;
@@ -484,8 +481,8 @@ fn floor_walls_flat(root: &Map<String, Value>, level: &str) -> Vec<f64> {
}
/// Lichter Umriss der Zelle um `at` (Raum „innen“), `None` = keine geschlossene Zelle.
fn room_inside(root: &Map<String, Value>, level: &str, at: V) -> Option<Vec<V>> {
let f = crate::room_boundary::from_point(at.0, at.1, &floor_walls_flat(root, level), 0.05, true);
fn room_inside(p: &Project, level: &str, at: V) -> Option<Vec<V>> {
let f = crate::room_boundary::from_point(at.0, at.1, &floor_walls_flat(p, level), 0.05, true);
if f.is_empty() {
return None;
}
@@ -494,9 +491,9 @@ fn room_inside(root: &Map<String, Value>, level: &str, at: V) -> Option<Vec<V>>
}
/// Raum aus Umriss (Modus „manuell“: `pts`; „innen“: `at` → Zelle).
fn room_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
fn room_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
let boundary = match opt_p(v, "at") {
Some(at) => match room_inside(root, ctx.level, at) {
Some(at) => match room_inside(p, ctx.level, at) {
Some(b) if b.len() >= 3 => b,
_ => return Vec::new(),
},
@@ -507,8 +504,8 @@ fn room_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) ->
if boundary.len() < 3 || e.gross < 1e-4 {
return Vec::new();
}
let code = if has_category(root, "60") { "60" } else { ctx.cat };
let name = format!("Raum {}", arr(root.get("rooms")).len() + 1);
let code = if has_category(p, "60") { "60" } else { ctx.cat };
let name = format!("Raum {}", p.rooms.as_ref().map_or(0, Vec::len) + 1);
let doc = json!({ "version": 1, "paragraphs": [{ "runs": [{ "text": name, "marks": {} }], "align": "center" }] });
add_op(
"rooms",
@@ -520,7 +517,7 @@ fn room_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) ->
("siaCategory", s("HNF")),
("name", s(&name)),
("boundary", pvs(&boundary)),
("color", category_color(root, code, "#5a7a9a")),
("color", category_color(p, code, "#5a7a9a")),
("stampAnchor", pt(e.centroid[0], e.centroid[1])),
("stampDoc", doc),
])],
@@ -547,7 +544,7 @@ struct StairBuilt {
steps: f64,
}
fn build_stair(root: &Map<String, Value>, v: &Value, ctx: &Ctx, id: Value) -> StairBuilt {
fn build_stair(p: &Project, v: &Value, ctx: &Ctx, id: Value) -> StairBuilt {
let shape = s_of(v, "shape");
let start = p_of(v, "start");
let cursor = p_of(v, "cursor");
@@ -574,7 +571,7 @@ fn build_stair(root: &Map<String, Value>, v: &Value, ctx: &Ctx, id: Value) -> St
("id", id),
("type", s("stair")),
("floorId", s(ctx.level)),
("categoryCode", category_or(root, "40", ctx)),
("categoryCode", category_or(p, "40", ctx)),
("shape", s(shape)),
("start", pv(start)),
("dir", pv(dir)),
@@ -618,14 +615,14 @@ fn build_stair(root: &Map<String, Value>, v: &Value, ctx: &Ctx, id: Value) -> St
StairBuilt { fields: f, params, rise, steps }
}
fn stair_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
let b = build_stair(root, v, ctx, s(&ids.next("ST")));
fn stair_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
let b = build_stair(p, v, ctx, s(&ids.next("ST")));
add_op("stairs", vec![obj(b.fields)])
}
/// Treppen-Vorschau: Tritte, Podest, Lauflinie; `info = [Stufenzahl]`.
fn stair_preview(root: &Map<String, Value>, v: &Value, ctx: &Ctx, out: &mut Shapes, info: &mut Vec<f64>) {
let b = build_stair(root, v, ctx, Value::Null);
fn stair_preview(p: &Project, v: &Value, ctx: &Ctx, out: &mut Shapes, info: &mut Vec<f64>) {
let b = build_stair(p, v, ctx, Value::Null);
info.push(b.steps);
let f = crate::stair::geometry(&b.params, b.rise);
if f.len() < 4 {
@@ -709,7 +706,7 @@ fn pick_wall<'a>(root: &'a Map<String, Value>, level: &str, p: V) -> Option<(&'a
}
/// Öffnung in eine Wand (`start`/`end` der Host-Wand beim Picken, `pos` = Abstand vom Wandanfang).
fn opening_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
fn opening_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
let (st, en) = (p_of(v, "start"), p_of(v, "end"));
let len = match arc_of(st, en, opt_n(v, "bulge")) {
Some(a) => a.length(),
@@ -718,13 +715,14 @@ fn opening_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen)
let width = jsnum::max(0.1, jsnum::min(n_of(v, "width"), len));
let position = jsnum::max(0.0, jsnum::min(n_of(v, "pos"), jsnum::max(0.0, len - width)));
let door = s_of(v, "kind") == "door";
let lib = arr(root.get(if door { "doorTypes" } else { "windowTypes" }));
let type_id = lib.first().and_then(|t| field(t, "id")).filter(|id| truthy(Some(id)));
// Erster Typ der Bibliothek (leere id = keiner, JS-Wahrheitswert).
let first = if door { p.door_types.as_ref().and_then(|l| l.first()).map(|t| &t.id) } else { p.window_types.as_ref().and_then(|l| l.first()).map(|t| &t.id) };
let type_id = first.filter(|id| !id.is_empty());
let mut f = vec![
("id", s(&ids.next("O"))),
("type", s("opening")),
("hostWallId", s(s_of(v, "wall"))),
("categoryCode", category_or(root, "21", ctx)),
("categoryCode", category_or(p, "21", ctx)),
("kind", s(s_of(v, "kind"))),
("position", js_num(position)),
("width", js_num(width)),
@@ -732,7 +730,7 @@ fn opening_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen)
("sillHeight", js_num(if door { 0.0 } else { n_of(v, "sill") })),
];
if let Some(t) = type_id {
f.push(("typeId", t.clone()));
f.push(("typeId", s(t)));
}
if door {
f.push(("hinge", s(s_of(v, "hinge"))));
@@ -813,7 +811,7 @@ fn opening_preview(v: &Value, cursor: Option<V>, out: &mut Shapes, info: &mut Ve
// ── Dach, Stütze ─────────────────────────────────────────────────────────────
fn roof_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
fn roof_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
let (a, b) = (p_of(v, "a"), p_of(v, "b"));
let (w, d) = ((b.0 - a.0).abs(), (b.1 - a.1).abs());
if w < 0.1 || d < 0.1 {
@@ -826,7 +824,7 @@ fn roof_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) ->
("id", s(&ids.next("RF"))),
("type", s("roof")),
("floorId", s(ctx.level)),
("categoryCode", category_or(root, "31", ctx)),
("categoryCode", category_or(p, "31", ctx)),
("outline", pvs(&rect_corners(a, b))),
("shape", s(shape)),
("pitchDeg", js_num(if shape == "flach" { 0.0 } else { 30.0 })),
@@ -959,20 +957,20 @@ fn extrude_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen)
// ═════════════════════════════════════════════════════════════════════════════
/// Ops eines Zeichenbefehls (`None` = kein Zeichenbefehl).
pub fn ops(root: &Map<String, Value>, v: &Value) -> Option<Vec<Op>> {
pub fn ops(root: &Map<String, Value>, p: &Project, v: &Value) -> Option<Vec<Op>> {
let ctx = ctx_of(v);
let mut ids = IdGen::new(s_of(v, "stamp"));
let ids = &mut ids;
Some(match s_of(v, "cmd") {
"wall" => wall_ops(root, v, &ctx, ids),
"ceiling" => ceiling_ops(root, v, &ctx, ids),
"room" => room_ops(root, v, &ctx, ids),
"stair" => stair_ops(root, v, &ctx, ids),
"opening" => opening_ops(root, v, &ctx, ids),
"roof" => roof_ops(root, v, &ctx, ids),
"wall" => wall_ops(root, p, v, &ctx, ids),
"ceiling" => ceiling_ops(p, v, &ctx, ids),
"room" => room_ops(p, v, &ctx, ids),
"stair" => stair_ops(p, v, &ctx, ids),
"opening" => opening_ops(p, v, &ctx, ids),
"roof" => roof_ops(p, v, &ctx, ids),
"column" => column_ops(v, &ctx, ids),
"extrude" => extrude_ops(root, v, &ctx, ids),
_ => return crate::cmd_draw::ops(root, v, &ctx, ids).or_else(|| crate::cmd_solid::ops(root, v, &ctx, ids)),
_ => return crate::cmd_draw::ops(root, v, &ctx, ids).or_else(|| crate::cmd_solid::ops(root, p, v, &ctx, ids)),
})
}
@@ -998,8 +996,8 @@ impl Preview {
/// Vorschau eines Zeichenbefehls: `v` = Optionen (`cmd`, …, `ctx`), `pts` = die Punkte flach (je Befehl
/// die gesetzten Punkte und zuletzt der Cursor).
pub fn preview(root: &Map<String, Value>, v: &Value, pts: &[f64]) -> Preview {
preview_req(root, &Req::new(v.clone()), pts)
pub fn preview(root: &Map<String, Value>, project: &Project, v: &Value, pts: &[f64]) -> Preview {
preview_req(root, project, &Req::new(v.clone()), pts)
}
/// Gelesene Vorschau-Anfrage: die Optionen und, für den Mausschritt ohne Hash-Suchen, Befehl und Kontext.
@@ -1024,7 +1022,7 @@ impl Req {
}
/// Wie [`preview`] mit gelesener Anfrage (Mausschritt: dieselbe Anfrage, neue Punkte).
pub fn preview_req(root: &Map<String, Value>, req: &Req, pts: &[f64]) -> Preview {
pub fn preview_req(root: &Map<String, Value>, project: &Project, req: &Req, pts: &[f64]) -> Preview {
let v = &req.v;
let ctx = Ctx { level: &req.level, floor_height: req.floor_height, cat: &req.cat, wall_type: &req.wall_type, text_height: req.text_height, symbol: req.symbol };
let pts = flat_pts(pts);
@@ -1032,9 +1030,9 @@ pub fn preview_req(root: &Map<String, Value>, req: &Req, pts: &[f64]) -> Preview
let out = &mut p.shapes;
match req.cmd.as_str() {
"wall" => wall_preview(root, v, &ctx, &pts, out),
"stair" => stair_preview(root, v, &ctx, out, &mut p.info),
"stair" => stair_preview(project, v, &ctx, out, &mut p.info),
"opening" => opening_preview(v, pts.first().copied(), out, &mut p.info),
"roomInside" => p.ok = pts.first().and_then(|at| room_inside(root, ctx.level, *at)).is_some_and(|b| b.len() >= 3),
"roomInside" => p.ok = pts.first().and_then(|at| room_inside(project, ctx.level, *at)).is_some_and(|b| b.len() >= 3),
"column" => {
if let Some(at) = pts.first() {
out.poly(&column_footprint(*at, v));
@@ -1161,7 +1159,7 @@ mod tests {
fn bogenwand_drei_punkt_und_tangential() {
let r = root(json!({"wallTypes": [{"id": "WT1", "name": "Beton", "layers": [{"componentId": "c", "thickness": 0.2}]}]}));
// (0,0)→(4,0) durch (2,2): Halbkreis, Scheitel links → Modell-Bulge +1; dann tangential weiter nach (4,-4)?
let o = ops(&r, &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0], [8, 0]], "segs": [{"x": 2, "y": 2}, 1], "thick": null}))).unwrap();
let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0], [8, 0]], "segs": [{"x": 2, "y": 2}, 1], "thick": null}))).unwrap();
let w = items(&o, 0);
let b0 = w[0]["bulge"].as_f64().unwrap();
assert!((b0 - 1.0).abs() < 1e-9, "{b0}");
@@ -1169,19 +1167,19 @@ mod tests {
let b1 = w[1]["bulge"].as_f64().unwrap();
assert!((b1 + 1.0).abs() < 1e-9, "{b1}");
// Gerade Wand ohne `bulge`-Feld.
let o = ops(&r, &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0]], "segs": [0], "thick": null}))).unwrap();
let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0]], "segs": [0], "thick": null}))).unwrap();
assert!(items(&o, 0)[0].get("bulge").is_none());
}
#[test]
fn waende_je_segment_mit_typ_und_hoehe() {
let r = root(json!({"wallTypes": [{"id": "WT1", "name": "Beton", "layers": [{"componentId": "c", "thickness": 0.2}]}]}));
let o = ops(&r, &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0], [4, 0], [4, 3]], "thick": null}))).unwrap();
let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0], [4, 0], [4, 3]], "thick": null}))).unwrap();
let w = items(&o, 0);
assert_eq!(w.as_array().unwrap().len(), 2);
assert_eq!(w[0], json!({"id": "W-s-1", "type": "wall", "floorId": "F1", "categoryCode": "20", "start": {"x": 0, "y": 0}, "end": {"x": 4, "y": 0}, "wallTypeId": "WT1", "height": 3}));
// Gelockte Dicke → neuer einschichtiger Typ vor den Wänden.
let o = ops(&r, &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0]], "thick": 0.3}))).unwrap();
let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0]], "thick": 0.3}))).unwrap();
assert_eq!(items(&o, 0)[0], json!({"id": "WT-s-1", "name": "Beton 30 cm", "layers": [{"componentId": "c", "thickness": 0.3}]}));
assert_eq!(items(&o, 1)[0]["wallTypeId"], "WT-s-1");
}
@@ -1206,7 +1204,7 @@ mod tests {
let r = root(json!({"wallTypes": wt, "rooms": [], "layers": [{"code": "60", "color": "#abc"}], "walls": [
wall("a", (0.0, 0.0), (5.0, 0.0)), wall("b", (5.0, 0.0), (5.0, 4.0)), wall("c", (5.0, 4.0), (0.0, 4.0)), wall("d", (0.0, 4.0), (0.0, 0.0))],
"groups": [{"id": "g", "name": "G", "wallIds": ["a"], "drawingIds": []}]}));
let o = ops(&r, &req(json!({"cmd": "room", "at": [2, 2]}))).unwrap();
let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "room", "at": [2, 2]}))).unwrap();
let room = &items(&o, 0)[0];
assert_eq!(room["name"], "Raum 1");
assert_eq!(room["color"], "#abc");
@@ -1228,7 +1226,7 @@ mod tests {
assert_eq!(q["hit"]["id"], "w");
assert!((q["hit"]["t"].as_f64().unwrap() - std::f64::consts::PI).abs() < 1e-9);
assert_eq!(q["hit"]["bulge"], 1);
let o = ops(&r, &req(json!({"cmd": "opening", "wall": "w", "start": [0, 0], "end": [4, 0], "bulge": 1, "kind": "window", "pos": 6.0, "width": 1.2, "height": 1.2, "sill": 0.9}))).unwrap();
let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "opening", "wall": "w", "start": [0, 0], "end": [4, 0], "bulge": 1, "kind": "window", "pos": 6.0, "width": 1.2, "height": 1.2, "sill": 0.9}))).unwrap();
let pos = items(&o, 0)[0]["position"].as_f64().unwrap();
assert!((pos - (2.0 * std::f64::consts::PI - 1.2)).abs() < 1e-9, "{pos}");
}
@@ -1239,11 +1237,11 @@ mod tests {
let q = query(&r, &json!({"q": "pickWall", "level": "F1", "pt": [2, 0.3]})).unwrap().unwrap();
assert_eq!(q["hit"]["id"], "w");
assert_eq!(q["hit"]["t"], 2);
let o = ops(&r, &req(json!({"cmd": "opening", "wall": "w", "start": [0, 0], "end": [6, 0], "kind": "window", "pos": 5.5, "width": 1.2, "height": 1.2, "sill": 0.9}))).unwrap();
let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "opening", "wall": "w", "start": [0, 0], "end": [6, 0], "kind": "window", "pos": 5.5, "width": 1.2, "height": 1.2, "sill": 0.9}))).unwrap();
let op = &items(&o, 0)[0];
assert_eq!(op["position"], 4.8);
assert_eq!(op["typeId"], "FT");
let p = preview(&r, &json!({"cmd": "opening", "start": [0, 0], "end": [6, 0], "kind": "window", "width": 1.2, "pos": null}), &[2.0, 1.0]);
let p = preview(&r, &crate::model::lenient::typed_for_test(&r), &json!({"cmd": "opening", "start": [0, 0], "end": [6, 0], "kind": "window", "width": 1.2, "pos": null}), &[2.0, 1.0]);
assert_eq!(p.info[0], 2.0);
assert_eq!(p.shapes.count, 2);
}
+4 -4
View File
@@ -9,7 +9,7 @@ use crate::cmd_create::{
pts_of, pv, pvs, s, s_of, seg_len, to_p, type_thickness, wall_types, Ctx, Preview, V, EPS,
};
use crate::cmd_transform::{IdGen, Shapes};
use crate::grips::{arr, field, js_num, num_of, num_or, with, xy};
use crate::json_util::{arr, field, js_num, num_of, num_or, with, xy};
use crate::jsmath::hypot2;
use crate::jsnum;
use crate::ops::{id_of, Op};
@@ -373,7 +373,7 @@ fn straight_edges(g: &Value) -> Vec<(V, V)> {
Some("polyline") => {
let pts: Vec<V> = arr(field(g, "pts")).iter().map(xy).collect();
let bulge = arr(field(g, "bulge"));
polyline_edges(&pts, crate::grips::truthy(field(g, "closed")))
polyline_edges(&pts, crate::json_util::truthy(field(g, "closed")))
.into_iter()
.enumerate()
.filter(|(i, _)| num_or(bulge.get(*i), 0.0).abs() <= EPS)
@@ -1182,11 +1182,11 @@ fn auto_dims(root: &Map<String, Value>, ctx: &Ctx, prefix: &str, scale: f64) ->
Some((_, wi)) => format!("{prefix}-{}-arc-{}", ctx.level, id_of(walls[wi]).unwrap_or("")),
None => format!("{prefix}-{}-{}-{}", ctx.level, SIDES[c.side as usize], CHAINS[c.chain as usize]),
};
let pts = Value::Array(c.pts.iter().map(|q| crate::grips::pt(q[0], q[1])).collect());
let pts = Value::Array(c.pts.iter().map(|q| crate::json_util::pt(q[0], q[1])).collect());
let mut fields = vec![("shape", s("dimension")), ("pts", pts), ("offset", js_num(c.offset))];
// Bogenmass ([T2]): Kette auf dem Kreis um die Bogenmitte.
if let Some((ctr, _)) = c.arc {
fields.push(("arcCenter", crate::grips::pt(ctr[0], ctr[1])));
fields.push(("arcCenter", crate::json_util::pt(ctr[0], ctr[1])));
}
// Assoziativ ([38]): je Punkt das Merkmal (Ecke, Leibung), aus dem er stammt.
let chain: Vec<V> = c.pts.iter().map(|q| (q[0], q[1])).collect();
+1 -1
View File
@@ -13,7 +13,7 @@
use crate::cmd_transform::{IdGen, Shapes};
use crate::cmd_wall_edit as wall_edit;
use crate::grips::{arr, field, js_num, num_of, num_or, pt, truthy, with, with_all, xy};
use crate::json_util::{arr, field, js_num, num_of, num_or, pt, truthy, with, with_all, xy};
use crate::jsmath::hypot2;
use crate::jsnum;
use crate::ops::{id_of, Op};
+1 -1
View File
@@ -12,7 +12,7 @@
//! fehlende kommen ans Ende, unbekannte Felder bleiben).
use crate::cmd_transform::IdGen;
use crate::grips::{arr, field, with_all};
use crate::json_util::{arr, field, with_all};
use crate::ops::{id_of, Op};
use serde_json::Value;
use std::collections::HashMap;
+13 -12
View File
@@ -7,9 +7,10 @@
use crate::cmd_create::{add_op, circle_pts, find, n_of, obj, opt_p, p_of, pts_of, pv, pvs, rect_corners, s, s_of, Ctx, Preview, V};
use crate::cmd_transform::{IdGen, Shapes};
use crate::grips::{arr, field, js_num, num_of, num_or, truthy, with, xy};
use crate::json_util::{arr, field, js_num, num_of, num_or, truthy, with, xy};
use crate::jsmath::hypot2;
use crate::jsnum;
use crate::model::Project;
use crate::ops::{id_of, Op};
use serde_json::{json, Map, Value};
@@ -554,7 +555,7 @@ fn ceiling_opening_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx) -> Vec<O
/// Dachfenster / Deckenöffnung mit Oberlicht ([103]): ein Klick setzt die Öffnung (Mitte im Grundriss) in das
/// Dach, dessen Umriss den Punkt enthält (Dächer des aktiven Geschosses zuerst), sonst in die Decke des
/// Geschosses. Masse in der Dachebene (Standard 78 × 118 cm), Fenstertyp wie beim Fenster-Befehl.
fn roof_window_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
fn roof_window_ops(root: &Map<String, Value>, p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
let at = p_of(v, "p");
if !(at.0.is_finite() && at.1.is_finite()) {
return Vec::new();
@@ -581,7 +582,7 @@ fn roof_window_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut Id
("hostWallId", s("")),
(key, s(host_id)),
("hostPoint", pv(at)),
("categoryCode", crate::cmd_create::category_or(root, "21", ctx)),
("categoryCode", crate::cmd_create::category_or(p, "21", ctx)),
("kind", s("window")),
("position", js_num(0.0)),
("width", js_num(width)),
@@ -596,7 +597,7 @@ fn roof_window_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut Id
/// Gaube ([G5]): ein Klick in eine geneigte Dachfläche setzt die Gaube (Stirnmitte am Punkt) und ein
/// Fenster in ihre Stirn (`hostDormerId`). Art über `kind` (schlepp/sattel/flach/walm).
fn dormer_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
fn dormer_ops(root: &Map<String, Value>, p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
let at = p_of(v, "p");
if !(at.0.is_finite() && at.1.is_finite()) {
return Vec::new();
@@ -634,7 +635,7 @@ fn dormer_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen)
("hostWallId", s("")),
("hostRoofId", s(roof_id)),
("hostDormerId", s(&did)),
("categoryCode", crate::cmd_create::category_or(root, "21", ctx)),
("categoryCode", crate::cmd_create::category_or(p, "21", ctx)),
("kind", s("window")),
("position", js_num(0.0)),
("width", js_num(jsnum::round(width * 0.6 * 100.0) / 100.0)),
@@ -726,7 +727,7 @@ fn sectionline_ops(root: &Map<String, Value>, v: &Value, ids: &mut IdGen) -> Vec
None | Some(Value::Null) => js_num(1.0),
Some(x) => x.clone(),
};
return vec![Op::Replace { collection: "drawingLevels".into(), entity: crate::grips::with_all(z, vec![("linePoints", line), ("directionSign", sign)]) }];
return vec![Op::Replace { collection: "drawingLevels".into(), entity: crate::json_util::with_all(z, vec![("linePoints", line), ("directionSign", sign)]) }];
}
let name = s_of(v, "name").replace('\u{1}', &level_letters(of_kind.len()));
add_op(
@@ -766,7 +767,7 @@ fn direction_arrow(a: V, b: V, sign: f64, out: &mut Shapes) {
// Einstiege (über `cmd_create`)
// ═════════════════════════════════════════════════════════════════════════════
pub fn ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Option<Vec<Op>> {
pub fn ops(root: &Map<String, Value>, p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Option<Vec<Op>> {
Some(match s_of(v, "cmd") {
"solid" => solid_ops(v, ctx, ids),
"revolve" => revolve_ops(root, v, ctx, ids),
@@ -777,8 +778,8 @@ pub fn ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) ->
"excavation" => excavation_ops(root, v, ctx, ids),
"ceilingOpening" => ceiling_opening_ops(root, v, ctx),
"roofHole" => roof_hole_ops(root, v, ctx),
"roofWindow" => roof_window_ops(root, v, ctx, ids),
"dormer" => dormer_ops(root, v, ctx, ids),
"roofWindow" => roof_window_ops(root, p, v, ctx, ids),
"dormer" => dormer_ops(root, p, v, ctx, ids),
"sectionline" => sectionline_ops(root, v, ids),
_ => return None,
})
@@ -854,7 +855,7 @@ mod tests {
let run = |x: f64, y: f64, kind: &str| {
let mut ids = IdGen::new("s");
let ctx = Ctx { level: "dg", floor_height: None, cat: "", wall_type: "", text_height: 0.25, symbol: 1.0 };
ops(root, &json!({"cmd": "dormer", "p": {"x": x, "y": y}, "kind": kind}), &ctx, &mut ids).unwrap()
ops(root, &crate::model::lenient::typed_for_test(root), &json!({"cmd": "dormer", "p": {"x": x, "y": y}, "kind": kind}), &ctx, &mut ids).unwrap()
};
let o = run(4.0, 1.5, "sattel");
assert_eq!(o.len(), 2);
@@ -878,7 +879,7 @@ mod tests {
let run = |level: &str, x: f64| {
let mut ids = IdGen::new("s");
let ctx = Ctx { level, floor_height: None, cat: "", wall_type: "", text_height: 0.25, symbol: 1.0 };
ops(root, &json!({"cmd": "roofWindow", "p": {"x": x, "y": 1.0}}), &ctx, &mut ids).unwrap()
ops(root, &crate::model::lenient::typed_for_test(root), &json!({"cmd": "roofWindow", "p": {"x": x, "y": 1.0}}), &ctx, &mut ids).unwrap()
};
let item = |o: &[Op]| match &o[0] {
Op::Add { items, .. } => items[0].clone(),
@@ -900,7 +901,7 @@ mod tests {
let run = |pts: Value| {
let mut ids = IdGen::new("s");
let ctx = Ctx { level: "ug", floor_height: None, cat: "", wall_type: "", text_height: 0.25, symbol: 1.0 };
ops(root, &json!({"cmd": "excavation", "pts": pts}), &ctx, &mut ids).unwrap()
ops(root, &crate::model::lenient::typed_for_test(root), &json!({"cmd": "excavation", "pts": pts}), &ctx, &mut ids).unwrap()
};
let o = run(json!([{"x": 0, "y": 0}, {"x": 10, "y": 8}]));
let Op::Add { collection, items, .. } = &o[0] else { panic!() };
+1 -1
View File
@@ -18,7 +18,7 @@
//! vorher über die Bindungen).
use crate::cmd_transform::IdGen;
use crate::grips::{arr, field, js_num, num_of, pt, truthy, with_opt, xy};
use crate::json_util::{arr, field, js_num, num_of, pt, truthy, with_opt, xy};
use crate::jsmath::hypot2;
use crate::jsnum;
use crate::ops::{id_of, Op};
+2 -2
View File
@@ -10,9 +10,9 @@
//! dasselbe wie `a·x + b·y + e`).
//!
//! Rechnung auf der rohen Projekt-Wurzel (verlustfrei, Schlüsselreihenfolge wie das Objekt-Spreizen in
//! TS); Zahlen wie in JS (`jsnum`, `jsmath`), nicht endliche Ergebnisse als Marken (`grips::js_num`).
//! TS); Zahlen wie in JS (`jsnum`, `jsmath`), nicht endliche Ergebnisse als Marken (`json_util::js_num`).
use crate::grips::{arr, field, js_num, num_of, num_or, pt, truthy, with, with_all, with_opt, xy, N};
use crate::json_util::{arr, field, js_num, num_of, num_or, pt, truthy, with, with_all, with_opt, xy, N};
use crate::jsmath::hypot2;
use crate::jsnum;
use crate::ops::{id_of, Op};
+1 -1
View File
@@ -21,7 +21,7 @@
//! Geschosses, 2D-Linien/-Polylinien (mit Bögen)/-Rechtecke/-Kreise/-Bögen und Achsraster der Ebene.
use crate::cmd_transform::{IdGen, Shapes};
use crate::grips::{arr, field, js_num, num_of, pt, truthy, with, with_all, xy};
use crate::json_util::{arr, field, js_num, num_of, pt, truthy, with, with_all, xy};
use crate::joins::Line;
use crate::model::{DimFeature, DimRef};
use crate::ops::{id_of, Op};
+8 -6
View File
@@ -5,6 +5,7 @@
//! (Verschieben/Drehen/Spiegeln/Skalieren/Reihe, Ausrichten/Verteilen, Block definieren).
use crate::grips::{result_json, GripResult};
use crate::model::Project;
use crate::ops::Op;
use serde_json::{Map, Value};
@@ -12,14 +13,15 @@ fn parse<T: serde::de::DeserializeOwned>(v: &Value, what: &str) -> Result<T, Str
serde_json::from_value(v.clone()).map_err(|e| format!("{what}: {e}"))
}
/// Ops eines Befehls (`text` = JSON `{cmd, …}`, Zahlen dürfen Nicht-endlich-Marken sein).
pub fn ops(root: &Map<String, Value>, text: &str) -> Result<Vec<Op>, String> {
/// Ops eines Befehls (`text` = JSON `{cmd, …}`, Zahlen dürfen Nicht-endlich-Marken sein). `p` = typisierte
/// Sicht derselben Wurzel (Lesen, [124]); geänderte Elemente entstehen verlustfrei aus `root`.
pub fn ops(root: &Map<String, Value>, p: &Project, text: &str) -> Result<Vec<Op>, String> {
let v: Value = serde_json::from_str(text).map_err(|e| format!("cmdOps: {e}"))?;
// Zeichnen in einer betretenen Gruppe: neue Elemente werden ihr Mitglied (`cmd_create::group_ops`).
if let Some(group) = v.get("group").and_then(Value::as_str) {
let mut inner = v.clone();
inner.as_object_mut().map(|m| m.remove("group"));
let mut out = ops(root, &inner.to_string())?;
let mut out = ops(root, p, &inner.to_string())?;
let extra = crate::cmd_create::group_ops(root, &out, group);
out.extend(extra);
return Ok(out);
@@ -30,7 +32,7 @@ pub fn ops(root: &Map<String, Value>, text: &str) -> Result<Vec<Op>, String> {
if let Some(ops) = crate::cmd_edit::ops(root, &v) {
return Ok(ops);
}
if let Some(ops) = crate::cmd_create::ops(root, &v) {
if let Some(ops) = crate::cmd_create::ops(root, p, &v) {
return Ok(ops);
}
Ok(match cmd {
@@ -46,8 +48,8 @@ pub fn ops(root: &Map<String, Value>, text: &str) -> Result<Vec<Op>, String> {
}
/// Wie [`ops`], als Antwort-JSON `{"ops": […]}` (Zahlen mit Nicht-endlich-Marken).
pub fn ops_json(root: &Map<String, Value>, text: &str) -> Result<String, String> {
Ok(result_json(&GripResult { ops: ops(root, text)?, notice: None }))
pub fn ops_json(root: &Map<String, Value>, p: &Project, text: &str) -> Result<String, String> {
Ok(result_json(&GripResult { ops: ops(root, p, text)?, notice: None }))
}
/// Schneller Hasher für id-Mengen der Befehle (FNV-1a; je Mausschritt werden Tausende ids geprüft,
+3 -3
View File
@@ -657,7 +657,7 @@ fn refs_of(g: &Value) -> Option<Vec<Option<DimRef>>> {
}
fn pv(p: P) -> Value {
crate::grips::pt(p.0, p.1)
crate::json_util::pt(p.0, p.1)
}
fn with(v: &Value, key: &str, x: Value) -> Value {
@@ -1062,14 +1062,14 @@ mod tests {
fn befehl_bemassung_haengt_gefangene_punkte_an() {
let r = project();
let req = json!({"cmd": "dimension", "pts": [[0, -2], [2, -2], [5, -2]], "snaps": [[0, -0.15], [2, -0.15]], "offset": -0.5, "ctx": {"level": "eg"}, "stamp": "s"});
let ops = crate::commands::ops(&r, &req.to_string()).unwrap();
let ops = crate::commands::ops(&r, &crate::model::lenient::typed_for_test(&r), &req.to_string()).unwrap();
let Op::Add { items, .. } = &ops[0] else { panic!("{ops:?}") };
let refs = &items[0]["geom"]["refs"];
assert_eq!(refs[0]["feature"], json!("wall"));
assert_eq!(refs[1]["feature"], json!("opening"));
assert_eq!(refs[2], Value::Null);
// Aussenbemassung: Ketten hängen an Ecken und Leibungen.
let ops = crate::commands::ops(&r, &json!({"cmd": "autodim", "ctx": {"level": "eg"}, "stamp": "s"}).to_string()).unwrap();
let ops = crate::commands::ops(&r, &crate::model::lenient::typed_for_test(&r), &json!({"cmd": "autodim", "ctx": {"level": "eg"}, "stamp": "s"}).to_string()).unwrap();
let n_refs: usize = ops
.iter()
.filter_map(|o| if let Op::Add { items, .. } = o { Some(items) } else { None })
+176 -12
View File
@@ -1,5 +1,6 @@
//! Projekt-Dokument ([K4], Stufen S1/S3): Rust hält das Projekt als JSON-Baum, wendet Op-Folgen
//! (`ops.rs`) atomar an, prüft sie (NaN, neue doppelte ids → Rücknahme mit Meldungen) und führt den
//! (`ops.rs`) atomar an, prüft sie (NaN, neue doppelte ids, Werte gegen das typisierte Modell
//! `model::check` → Rücknahme mit Meldungen) und führt den
//! Undo/Redo-Verlauf als inverse Ops. Die Ableitungen (Kennzahlen, 3D, Export …) lesen die
//! typisierte Sicht [`Document::project`].
//!
@@ -14,6 +15,16 @@ use serde_json::{Map, Value};
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
/// Nicht-endlich-Marken in den Werten einer Op durch `null` ersetzen (Speicherform, s. `ops.rs`).
fn sanitize_op(op: &mut Op) {
match op {
Op::Add { items, .. } => items.iter_mut().for_each(crate::ops::sanitize_non_finite),
Op::Replace { entity, .. } => crate::ops::sanitize_non_finite(entity),
Op::SetField { value: Some(v), .. } => crate::ops::sanitize_non_finite(v),
_ => {}
}
}
#[derive(Clone, Debug, Default)]
pub struct Document {
root: Map<String, Value>,
@@ -339,6 +350,14 @@ impl Document {
Ok(self.typed.as_ref().expect("gerade gesetzt"))
}
/// Typisierte Sicht und die Wurzel samt Positions-Index (getrennte Ausleihen): Befehle lesen das Projekt
/// typisiert und bauen geänderte Elemente verlustfrei aus dem rohen Baum ([124]).
pub fn project_lookup(&mut self) -> Result<(&Project, Lookup<'_>), String> {
self.project()?;
let p = self.typed.as_ref().expect("gerade gelesen");
Ok((p, Lookup { root: &self.root, pos: Some(&self.pos) }))
}
/// 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
@@ -588,7 +607,7 @@ impl Document {
}
/// Wendet `ops` atomar an und prüft sie (`ops::validate`, Werte vor dem Anwenden, neue doppelte ids
/// danach — die Ops gehen ohne Kopie ins Dokument über). Verstösse → `Err(Meldungen)`, Dokument
/// danach — die Ops gehen ohne Kopie ins Dokument über; neue Werte gegen das typisierte Modell, [124]). Verstösse → `Err(Meldungen)`, Dokument
/// unverändert. Ok → inverse Ops. `sanitize`: die Ops können Nicht-endlich-Marken enthalten
/// (s. `ops.rs`).
fn apply_checked(&mut self, ops: Vec<Op>, sanitize: bool) -> Result<Vec<Op>, Vec<String>> {
@@ -606,9 +625,17 @@ impl Document {
// Je Op: Feld, ob `replace`, ob `add`, Befunde der Werte.
let mut info: Vec<(String, bool, bool, Vec<String>)> = Vec::with_capacity(n);
let mut pos = self.pos.take();
for op in ops {
for mut op in ops {
let mut found = Vec::new();
crate::ops::value_problems(&op, &had, &mut found);
if found.is_empty() {
if sanitize {
// Tiefer liegende Nicht-endlich-Marken als null (Speicherform), vor der Modell-Prüfung:
// ein optionales Feld nimmt null an, ein Pflichtfeld weist es zurück.
sanitize_op(&mut op);
}
self.type_problems(&mut op, &mut found);
}
info.push((op.key().to_owned(), matches!(op, Op::Replace { .. }), matches!(op, Op::Add { .. }), found));
let (inv, hit) = self.apply_recorded(op, &mut pos);
inverses.push(inv);
@@ -634,15 +661,6 @@ impl Document {
return Err(problems);
}
*self.pos.get_mut() = pos;
if sanitize {
// Angenommene Nicht-endlich-Marken (zu tief für die Prüfung) als null speichern.
let keys: HashSet<&str> = info.iter().map(|i| i.0.as_str()).collect();
for k in keys {
if let Some(v) = self.root.get_mut(k) {
crate::ops::sanitize_non_finite(v);
}
}
}
for ((key, replace, _, _), hit) in info.into_iter().zip(&hits) {
self.mark_dirty(key, replace, *hit);
}
@@ -650,6 +668,25 @@ impl Document {
Ok(inverses.into_iter().rev().flatten().collect())
}
/// Prüft die neuen Werte einer Op gegen das typisierte Modell ([124], `model::check`): eingefügte und
/// ersetzte Elemente, gesetzte Felder. Ein Element, das schon vorher nicht passte (Alt-Datei), darf
/// seine alten Fehler behalten, aber keine neuen dazubekommen.
fn type_problems(&self, op: &mut Op, out: &mut Vec<String>) {
use crate::model::check::{check_items, check_set_field};
match op {
Op::Add { collection, items, .. } => out.extend(check_items(collection, items, &|_| None)),
Op::Replace { collection, entity } => {
let list = self.root.get(collection.as_str()).and_then(Value::as_array);
let old = |id: &str| list.and_then(|l| l.iter().find(|e| id_of(e) == Some(id)));
let mut one = vec![std::mem::take(entity)];
out.extend(check_items(collection, &mut one, &old));
*entity = one.pop().unwrap_or_default();
}
Op::SetField { key, value, .. } => out.extend(check_set_field(key, value.as_ref(), self.root.get(key.as_str()))),
Op::Remove { .. } | Op::Reorder { .. } => {}
}
}
/// Wendet `ops` atomar an, ohne Verlauf (Abgleich des Spiegels). Verstösse (NaN, neue
/// doppelte ids) → `Err(Meldungen)`, Dokument unverändert.
pub fn apply(&mut self, ops: &[Op]) -> Result<(), Vec<String>> {
@@ -1111,6 +1148,77 @@ mod tests {
assert_eq!(d.field("walls").unwrap()[0]["p"]["q"]["r"]["s"]["t"], Value::Null);
}
/// [124]: neue Werte müssen zum typisierten Modell passen; die ganze Folge wird zurückgenommen.
#[test]
fn falsch_typisierte_ops_abgelehnt() {
let mut d = Document::from_json(
r#"{"id":"p","name":"x","walls":[{"id":"w1","height":2.5}],"drawings2d":[{"id":"d1","levelId":"eg","geom":{"shape":"line","a":{"x":0,"y":0},"b":{"x":1,"y":0}}}]}"#,
)
.unwrap();
let start = d.to_json();
let reject = |d: &mut Document, v: Value, needle: &[&str]| {
let p = d.commit(ops(v), None, 0.0, true).unwrap_err();
let text = p.join(" | ");
for n in needle {
assert!(text.contains(n), "„{n}\" fehlt in: {text}");
}
};
// Falscher Typ (Text statt Zahl) — die gültige Op davor wird mit zurückgenommen.
reject(
&mut d,
json!([{"kind":"setField","key":"name","value":"neu"},{"kind":"replace","collection":"walls","entity":{"id":"w1","height":"hoch"}}]),
&["walls", "w1", "height", "invalid type"],
);
// Unbekannte Variante eines Enums ohne Rückfall.
reject(
&mut d,
json!([{"kind":"add","collection":"drawings2d","items":[{"id":"d2","levelId":"eg","geom":{"shape":"klecks"}}]}]),
&["drawings2d", "d2", "geom", "unknown variant"],
);
// NaN: flach (bisherige Meldung) und tief (Marke als null → Pflichtfeld fehlt).
reject(&mut d, json!([{"kind":"replace","collection":"walls","entity":{"id":"w1","height":"\u{1}NaN"}}]), &["NaN ist nicht endlich"]);
reject(
&mut d,
json!([{"kind":"add","collection":"blockDefs","items":[{"id":"b1","name":"B","geom2d":[{"shape":"polyline","closed":false,"pts":[{"x":0,"y":0},{"x":"\u{1}NaN","y":0}]}]}]}]),
&["b1", "geom2d[0]", "null"],
);
// Feld: falscher Typ, Liste mit kaputtem Element.
reject(&mut d, json!([{"kind":"setField","key":"parcelArea","value":"gross"}]), &["parcelArea"]);
reject(&mut d, json!([{"kind":"setField","key":"walls","value":[{"id":"w1"},{"id":"w9","start":7}]}]), &["w9", "start"]);
assert_eq!(d.to_json(), start, "Dokument unverändert");
assert_eq!(d.history().undo_depth(), 0, "kein Schritt");
// Gültige Ops werden angenommen (auch Felder ausserhalb des Modells und null = Feld fehlt).
d.commit(
ops(json!([
{"kind":"replace","collection":"walls","entity":{"id":"w1","height":3}},
{"kind":"add","collection":"drawings2d","items":[{"id":"d2","levelId":"eg","geom":{"shape":"circle","center":{"x":0,"y":0},"r":1}}]},
{"kind":"setField","key":"parcelArea","value":500},
{"kind":"setField","key":"siteRules","value":null},
{"kind":"setField","key":"eigenesFeld","value":{"x":"y"}},
{"kind":"add","collection":"eigeneListe","items":[{"id":"e","a":[1,"b"]}]}
])),
None,
0.0,
false,
)
.unwrap();
assert_eq!(d.field("walls").unwrap()[0]["height"], json!(3));
}
/// [124]: Alt-Dateien laden tolerant; ein Element mit Alt-Fehler bleibt änderbar, neue Fehler nicht.
#[test]
fn alt_fehler_bleiben_aenderbar() {
let mut d = Document::from_json(r#"{"id":"p","walls":[{"id":"w1","height":null,"start":{"x":0,"y":0}}],"parcelArea":"alt"}"#).unwrap();
assert_eq!(d.project().unwrap().walls[0].height, 0.0, "tolerant geladen");
d.commit(ops(json!([{"kind":"replace","collection":"walls","entity":{"id":"w1","height":null,"start":{"x":1,"y":0}}}])), None, 0.0, false).unwrap();
assert_eq!(d.project().unwrap().walls[0].start.x, 1.0);
let p = d.commit(ops(json!([{"kind":"replace","collection":"walls","entity":{"id":"w1","height":null,"start":{"x":"a","y":0}}}])), None, 1e4, false).unwrap_err();
assert!(p[0].contains("start.x"), "{p:?}");
// Feld mit Alt-Fehler: derselbe Fehler bleibt erlaubt, ein gültiger Wert sowieso.
d.commit(ops(json!([{"kind":"setField","key":"parcelArea","value":"immer noch alt"}])), None, 2e4, false).unwrap();
d.commit(ops(json!([{"kind":"setField","key":"parcelArea","value":12}])), None, 3e4, false).unwrap();
}
#[test]
fn feld_reihenfolge_bleibt_beim_undo() {
let mut d = doc();
@@ -1238,6 +1346,62 @@ mod big_steps {
assert_eq!(d.to_json(), r#"{"id":"p","walls":[{"id":"a","x":2},{"id":"d"}]}"#);
}
/// Messung ([124]): 1000 kleine Änderungen (Wand-Höhe, Öffnung, Zeichnung, Feld) auf dem Musterhaus
/// komplex. Datei: `MK_OUT=<pfad> npx vitest run src/model/sampleProjectComplex.test.ts`, dann
/// `DOSSIER_COMPLEX=<pfad> cargo test --release -- --ignored --nocapture tausend_kleine`.
#[test]
#[ignore]
fn tausend_kleine_aenderungen_musterhaus() {
let Ok(path) = std::env::var("DOSSIER_COMPLEX") else { return };
let mut d = Document::default();
d.load_file(&std::fs::read_to_string(path).unwrap(), 0.0).unwrap();
d.project().unwrap();
let pick = |d: &Document, c: &str, k: usize| {
let l = d.field(c).and_then(Value::as_array).unwrap();
l[k % l.len()].clone()
};
let n = 1000;
let (mut commit, mut typed, mut check) = (0.0, 0.0, 0.0);
for i in 0..n {
let op = match i % 4 {
0 => {
let mut w = pick(&d, "walls", i);
w["height"] = json!(2.5 + (i % 7) as f64 * 0.01);
Op::Replace { collection: "walls".into(), entity: w }
}
1 => {
let mut o = pick(&d, "openings", i);
o["sillHeight"] = json!(0.8 + (i % 5) as f64 * 0.01);
Op::Replace { collection: "openings".into(), entity: o }
}
2 => {
let mut g = pick(&d, "drawings2d", i);
g["categoryCode"] = json!(if i % 8 == 2 { "20" } else { "80" });
Op::Replace { collection: "drawings2d".into(), entity: g }
}
_ => Op::SetField { key: "parcelArea".into(), value: Some(json!(1500 + i)), at: None },
};
let mut probe = op.clone();
let t = std::time::Instant::now();
let mut found = Vec::new();
d.type_problems(&mut probe, &mut found);
check += t.elapsed().as_secs_f64();
assert!(found.is_empty(), "{found:?}");
let t = std::time::Instant::now();
d.commit(vec![op], None, i as f64 * 1000.0, false).unwrap();
commit += t.elapsed().as_secs_f64();
let t = std::time::Instant::now();
d.project().unwrap();
typed += t.elapsed().as_secs_f64();
}
eprintln!(
"Musterhaus komplex, {n} Änderungen: commit {:.1} µs/Schritt (davon Modell-Prüfung {:.1} µs), typisierte Sicht {:.1} µs/Schritt",
commit * 1e6 / n as f64,
check * 1e6 / n as f64,
typed * 1e6 / n as f64
);
}
/// Messung (nativ): grosser Import (150 000 Zeichnungen) committen, Undo, Redo. `cargo test --release -- --ignored`.
#[test]
#[ignore]
+1 -1
View File
@@ -20,7 +20,7 @@ fn shift_all(v: Option<&Value>, dx: f64, dy: f64) -> Value {
Value::Array(v.and_then(Value::as_array).map(|a| a.iter().map(|p| shift(p, dx, dy)).collect()).unwrap_or_default())
}
use crate::grips::truthy;
use crate::json_util::truthy;
/// `{...m, key: v}` — ein vorhandener Schlüssel behält seine Stelle; `None` = `undefined` (Feld entfällt).
fn set(m: &mut Map<String, Value>, key: &str, v: Option<Value>) {
+1 -164
View File
@@ -17,132 +17,14 @@
pub use crate::document::Lookup;
use crate::jsmath::hypot2;
use crate::jsnum;
use crate::json_util::{arr, field, js_num, num_of, num_or, pt, truthy, with, with_all, with_opt, xy, N};
use crate::ops::{id_of, Op};
use serde_json::{Map, Value};
// ── JS-Zahlen in JSON ────────────────────────────────────────────────────────
/// Feld `k` eines Objekts. Kleine Objekte (Punkte, Elemente) werden linear durchsucht: das ist deutlich
/// billiger als der Hash (SipHash) der `IndexMap` je Zugriff — die Griff- und Objekt-Info-Rechnung liest
/// Dutzende Felder je Aufruf.
#[inline]
pub fn field<'a>(v: &'a Value, k: &str) -> Option<&'a Value> {
match v {
Value::Object(m) if m.len() <= 32 => m.iter().find(|(kk, _)| kk.as_str() == k).map(|(_, x)| x),
Value::Object(m) => m.get(k),
_ => None,
}
}
/// Zahl als JSON-Wert wie nach `JSON.stringify` → `serde_json`: ganze Zahlen als Ganzzahl, sonst f64;
/// NaN/±∞ als Marke (`"\u{1}NaN"` …), −0 als 0.
pub fn js_num(x: f64) -> Value {
if x.is_nan() {
return Value::String("\u{1}NaN".into());
}
if x.is_infinite() {
return Value::String(if x > 0.0 { "\u{1}Infinity" } else { "\u{1}-Infinity" }.into());
}
if x.fract() == 0.0 {
if (0.0..18446744073709551616.0).contains(&x) {
return Value::from(x as u64);
}
if x < 0.0 && x >= -9223372036854775808.0 {
return Value::from(x as i64);
}
}
Value::from(x)
}
/// Zahl eines JSON-Werts wie in JS-Arithmetik auf der Leseansicht: Zahl, Nicht-endlich-Marke, `null` = 0
/// (so rechnet JS mit `null`; das Dokument speichert ein tief liegendes NaN als `null`, eine geladene
/// Datei liest es so zurück); fehlend und alles andere NaN.
pub fn num_of(v: Option<&Value>) -> f64 {
match v {
Some(Value::Number(n)) => n.as_f64().unwrap_or(f64::NAN),
Some(Value::Null) => 0.0,
Some(m) => match crate::ops::non_finite_mark(m) {
Some("Infinity") => f64::INFINITY,
Some("-Infinity") => f64::NEG_INFINITY,
_ => f64::NAN,
},
None => f64::NAN,
}
}
/// `a ?? b` für Zahlen (fehlend/`null` → `b`).
pub(crate) fn num_or(v: Option<&Value>, b: f64) -> f64 {
match v {
None | Some(Value::Null) => b,
v => num_of(v),
}
}
/// JS-Wahrheitswert.
pub 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 nullish(v: Option<&Value>) -> bool {
matches!(v, None | Some(Value::Null))
}
/// Punkt `{x, y}` (wie ein neues Objekt-Literal in TS).
pub fn pt(x: f64, y: f64) -> Value {
let mut m = Map::new();
m.insert("x".into(), js_num(x));
m.insert("y".into(), js_num(y));
Value::Object(m)
}
/// `(x, y)` eines Punkt-Werts (fehlende Koordinaten NaN).
pub fn xy(v: &Value) -> (f64, f64) {
(num_of(field(v, "x")), num_of(field(v, "y")))
}
/// `{...v, key: val}` (vorhandener Schlüssel behält seine Stelle). Der ersetzte Wert wird nicht kopiert
/// (eine grosse Polylinie kostet sonst je Mausschritt eine Kopie mehr).
pub(crate) fn with(v: &Value, key: &str, val: Value) -> Value {
with_all(v, vec![(key, val)])
}
/// Wie [`with`] für mehrere Felder in einem Durchgang (`{...v, a, b}`).
pub(crate) fn with_all(v: &Value, fields: Vec<(&str, Value)>) -> Value {
with_opt(v, fields.into_iter().map(|(k, x)| (k, Some(x))).collect())
}
/// Wie [`with_all`]; `None` = `undefined` (das Feld fällt weg, wie in JSON).
pub(crate) fn with_opt(v: &Value, fields: Vec<(&str, Option<Value>)>) -> Value {
let mut fields: Vec<(&str, Option<Value>, bool)> = fields.into_iter().map(|(k, x)| (k, x, false)).collect();
let src = v.as_object();
let mut m = Map::with_capacity(src.map_or(0, Map::len) + fields.len());
for (k, x) in src.into_iter().flatten() {
match fields.iter_mut().find(|(f, _, _)| *f == k) {
Some((_, new, done)) => {
*done = true;
if let Some(n) = new.take() {
m.insert(k.clone(), n);
}
}
None => {
m.insert(k.clone(), x.clone());
}
}
}
for (k, x, done) in fields {
if let (false, Some(x)) = (done, x) {
m.insert(k.into(), x);
}
}
Value::Object(m)
}
/// Zahl, die TS teils unverändert durchreicht (`ry: g.ry`): Wert für die Rechnung und JSON-Wert
/// (`None` = fehlend/`undefined`; ein `null` bleibt `null`).
#[derive(Clone)]
@@ -161,10 +43,6 @@ fn calc(f: f64) -> Pass {
Pass { f, v: Some(js_num(f)) }
}
pub fn arr(v: Option<&Value>) -> &[Value] {
v.and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[])
}
/// Ganzzahliger Index in `0..len` (JS: `list[i]` trifft nur dann ein Element).
fn index_in(i: f64, len: usize) -> Option<usize> {
(i.fract() == 0.0 && i >= 0.0 && i < len as f64).then_some(i as usize)
@@ -209,47 +87,6 @@ fn with_geom(d: &Value, g: Value) -> Value {
// ── Anfrage ──────────────────────────────────────────────────────────────────
/// Zahl der Anfrage: Zahl oder Nicht-endlich-Marke, `null` = 0 (wie `num_of`), fehlend = NaN.
#[derive(Clone, Copy, Debug)]
pub struct N(pub f64);
impl Default for N {
fn default() -> Self {
N(f64::NAN)
}
}
impl<'de> serde::Deserialize<'de> for N {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct V;
impl serde::de::Visitor<'_> for V {
type Value = N;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("Zahl")
}
fn visit_f64<E>(self, v: f64) -> Result<N, E> {
Ok(N(v))
}
fn visit_i64<E>(self, v: i64) -> Result<N, E> {
Ok(N(v as f64))
}
fn visit_u64<E>(self, v: u64) -> Result<N, E> {
Ok(N(v as f64))
}
fn visit_str<E>(self, v: &str) -> Result<N, E> {
Ok(N(num_of(Some(&Value::String(v.to_owned())))))
}
fn visit_unit<E>(self) -> Result<N, E> {
Ok(N(0.0))
}
fn visit_bool<E>(self, _: bool) -> Result<N, E> {
Ok(N(f64::NAN))
}
}
d.deserialize_any(V)
}
}
/// Eine Änderung aus den Griff-Aktionen des Stores (`GripRequest` in `geometry/grips.ts`); Zahlen dürfen
/// Nicht-endlich-Marken sein. Typisiert gelesen (je Mausschritt billiger als ein JSON-Baum).
#[derive(serde::Deserialize, Default, Debug)]
+2 -2
View File
@@ -7,7 +7,7 @@
//! Positionen/Indizes; `fileio/src/mesh_import.rs`: Zahlenpuffer + Strings). Zahlen wie in der TS-Fassung
//! (`Math.hypot`, `Math.round`), ids aus Zeit (Basis 36) + Zähler.
use crate::grips::js_num;
use crate::json_util::js_num;
use crate::import_drawing::{next_seq, GENERIC_IMPORT_CODE};
use crate::jsmath;
use crate::jsnum;
@@ -195,7 +195,7 @@ fn group_by<T>(items: &[T], key: impl Fn(&T) -> String) -> Vec<Vec<usize>> {
/// LV95-Ursprung des Projekts (`projectGeoOrigin`: `geoAnchor.lv95 − geoAnchor.model`), ohne Bezug `None`.
pub fn project_geo_origin(root: &Map<String, Value>) -> Option<[f64; 2]> {
let a = root.get("geoAnchor").filter(|a| crate::grips::truthy(Some(a)))?;
let a = root.get("geoAnchor").filter(|a| crate::json_util::truthy(Some(a)))?;
let n = |p: &str, k: &str| a.get(p).and_then(|o| o.get(k)).and_then(Value::as_f64).unwrap_or(f64::NAN);
Some([n("lv95", "e") - n("model", "x"), n("lv95", "n") - n("model", "y")])
}
+1 -1
View File
@@ -14,7 +14,7 @@
//! Zahlen und Texte wie in der TS-Fassung (`Math.round`, `toFixed`, `String(n)`, ids aus Zeit + Zähler),
//! Schlüsselreihenfolge der erzeugten Objekte wie die früheren Objekt-Literale.
use crate::grips::js_num;
use crate::json_util::js_num;
use crate::js_fmt::{js_number, to_fixed};
use crate::jsnum;
use crate::ops::Op;
+3 -3
View File
@@ -8,7 +8,7 @@
//! Deckentypen nach Schichten (Material + Dicke, ±0.5 mm), Materialien nach Namen; Zahlen auf 1e-9 m bzw.
//! 1e-6 gerundet (`Math.round(x / step) * step`).
use crate::grips::js_num;
use crate::json_util::js_num;
use crate::import_context::{color_hex, color_of, context_ops, geo_shift, ifc_meshes, project_geo_origin, stamp36, IfcProduct};
use crate::import_drawing::next_seq;
use crate::js_fmt::js_number;
@@ -715,14 +715,14 @@ fn elements_ops(root: &Map<String, Value>, products: &[IfcProduct], el: &Element
ops.extend(grown_list_ops("drawingLevels", root.get("drawingLevels"), std::mem::take(&mut ctx.levels)));
ops.extend(grown_list_ops("components", root.get("components"), std::mem::take(&mut ctx.components)));
ops.extend(grown_list_ops("wallTypes", root.get("wallTypes"), wall_types));
if !ceiling_types.is_empty() || root.get("ceilingTypes").is_some_and(|v| crate::grips::truthy(Some(v))) {
if !ceiling_types.is_empty() || root.get("ceilingTypes").is_some_and(|v| crate::json_util::truthy(Some(v))) {
ops.extend(grown_list_ops("ceilingTypes", root.get("ceilingTypes"), ceiling_types));
}
if !walls.is_empty() {
ops.push(Op::Add { collection: "walls".into(), items: walls, at: None });
}
for (key, items) in [("openings", openings), ("ceilings", ceilings), ("columns", columns), ("rooms", rooms)] {
if root.get(key).is_some_and(|v| crate::grips::truthy(Some(v))) {
if root.get(key).is_some_and(|v| crate::json_util::truthy(Some(v))) {
if !items.is_empty() {
ops.push(Op::Add { collection: key.into(), items, at: None });
}
+171
View File
@@ -0,0 +1,171 @@
//! Lese- und Bau-Hilfen für den rohen JSON-Baum des Projekts ([124], vorher in `grips.rs`): Felder
//! lesen, Zahlen wie JS (`null` = 0, Nicht-endlich-Marken), Wahrheitswerte, Punkte, Objekt-Spreizen
//! (`{...v, key: val}`) und Anfrage-Zahlen ([`N`]).
//!
//! Neuer Kern-Code liest das Projekt typisiert (`&Project`, `model`); diese Hilfen bleiben für Werte,
//! die verlustfrei durchgereicht werden müssen (unbekannte Felder, Schlüsselreihenfolge) und für
//! Anfragen der Hülle.
use serde_json::{Map, Value};
/// Feld `k` eines Objekts. Kleine Objekte (Punkte, Elemente) werden linear durchsucht: das ist deutlich
/// billiger als der Hash (SipHash) der `IndexMap` je Zugriff — die Griff- und Objekt-Info-Rechnung liest
/// Dutzende Felder je Aufruf.
#[inline]
pub fn field<'a>(v: &'a Value, k: &str) -> Option<&'a Value> {
match v {
Value::Object(m) if m.len() <= 32 => m.iter().find(|(kk, _)| kk.as_str() == k).map(|(_, x)| x),
Value::Object(m) => m.get(k),
_ => None,
}
}
/// Zahl als JSON-Wert wie nach `JSON.stringify` → `serde_json`: ganze Zahlen als Ganzzahl, sonst f64;
/// NaN/±∞ als Marke (`"\u{1}NaN"` …), −0 als 0.
pub fn js_num(x: f64) -> Value {
if x.is_nan() {
return Value::String("\u{1}NaN".into());
}
if x.is_infinite() {
return Value::String(if x > 0.0 { "\u{1}Infinity" } else { "\u{1}-Infinity" }.into());
}
if x.fract() == 0.0 {
if (0.0..18446744073709551616.0).contains(&x) {
return Value::from(x as u64);
}
if x < 0.0 && x >= -9223372036854775808.0 {
return Value::from(x as i64);
}
}
Value::from(x)
}
/// Zahl eines JSON-Werts wie in JS-Arithmetik auf der Leseansicht: Zahl, Nicht-endlich-Marke, `null` = 0
/// (so rechnet JS mit `null`; das Dokument speichert ein tief liegendes NaN als `null`, eine geladene
/// Datei liest es so zurück); fehlend und alles andere NaN.
pub fn num_of(v: Option<&Value>) -> f64 {
match v {
Some(Value::Number(n)) => n.as_f64().unwrap_or(f64::NAN),
Some(Value::Null) => 0.0,
Some(m) => match crate::ops::non_finite_mark(m) {
Some("Infinity") => f64::INFINITY,
Some("-Infinity") => f64::NEG_INFINITY,
_ => f64::NAN,
},
None => f64::NAN,
}
}
/// `a ?? b` für Zahlen (fehlend/`null` → `b`).
pub fn num_or(v: Option<&Value>, b: f64) -> f64 {
match v {
None | Some(Value::Null) => b,
v => num_of(v),
}
}
/// JS-Wahrheitswert.
pub 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,
}
}
/// Punkt `{x, y}` (wie ein neues Objekt-Literal in TS).
pub fn pt(x: f64, y: f64) -> Value {
let mut m = Map::new();
m.insert("x".into(), js_num(x));
m.insert("y".into(), js_num(y));
Value::Object(m)
}
/// `(x, y)` eines Punkt-Werts (fehlende Koordinaten NaN).
pub fn xy(v: &Value) -> (f64, f64) {
(num_of(field(v, "x")), num_of(field(v, "y")))
}
/// `{...v, key: val}` (vorhandener Schlüssel behält seine Stelle). Der ersetzte Wert wird nicht kopiert
/// (eine grosse Polylinie kostet sonst je Mausschritt eine Kopie mehr).
pub fn with(v: &Value, key: &str, val: Value) -> Value {
with_all(v, vec![(key, val)])
}
/// Wie [`with`] für mehrere Felder in einem Durchgang (`{...v, a, b}`).
pub fn with_all(v: &Value, fields: Vec<(&str, Value)>) -> Value {
with_opt(v, fields.into_iter().map(|(k, x)| (k, Some(x))).collect())
}
/// Wie [`with_all`]; `None` = `undefined` (das Feld fällt weg, wie in JSON).
pub fn with_opt(v: &Value, fields: Vec<(&str, Option<Value>)>) -> Value {
let mut fields: Vec<(&str, Option<Value>, bool)> = fields.into_iter().map(|(k, x)| (k, x, false)).collect();
let src = v.as_object();
let mut m = Map::with_capacity(src.map_or(0, Map::len) + fields.len());
for (k, x) in src.into_iter().flatten() {
match fields.iter_mut().find(|(f, _, _)| *f == k) {
Some((_, new, done)) => {
*done = true;
if let Some(n) = new.take() {
m.insert(k.clone(), n);
}
}
None => {
m.insert(k.clone(), x.clone());
}
}
}
for (k, x, done) in fields {
if let (false, Some(x)) = (done, x) {
m.insert(k.into(), x);
}
}
Value::Object(m)
}
pub fn arr(v: Option<&Value>) -> &[Value] {
v.and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[])
}
/// Zahl der Anfrage: Zahl oder Nicht-endlich-Marke, `null` = 0 (wie `num_of`), fehlend = NaN.
#[derive(Clone, Copy, Debug)]
pub struct N(pub f64);
impl Default for N {
fn default() -> Self {
N(f64::NAN)
}
}
impl<'de> serde::Deserialize<'de> for N {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct V;
impl serde::de::Visitor<'_> for V {
type Value = N;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("Zahl")
}
fn visit_f64<E>(self, v: f64) -> Result<N, E> {
Ok(N(v))
}
fn visit_i64<E>(self, v: i64) -> Result<N, E> {
Ok(N(v as f64))
}
fn visit_u64<E>(self, v: u64) -> Result<N, E> {
Ok(N(v as f64))
}
fn visit_str<E>(self, v: &str) -> Result<N, E> {
Ok(N(num_of(Some(&Value::String(v.to_owned())))))
}
fn visit_unit<E>(self) -> Result<N, E> {
Ok(N(0.0))
}
fn visit_bool<E>(self, _: bool) -> Result<N, E> {
Ok(N(f64::NAN))
}
}
d.deserialize_any(V)
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ use std::collections::HashSet;
type Tree = Vec<Value>;
use crate::grips::truthy;
use crate::json_util::truthy;
fn code_of(c: &Value) -> Option<&str> {
c.get("code").and_then(Value::as_str)
+1
View File
@@ -106,6 +106,7 @@ pub mod wasm_alloc;
pub mod text_layout;
pub mod plan_text;
pub mod grips;
pub mod json_util;
pub mod selection_info;
pub mod project_refs;
pub mod commands;
+142
View File
@@ -0,0 +1,142 @@
//! Prüfung neuer Werte gegen das typisierte Modell ([124]): Eine Op, die ein Element einfügt/ersetzt
//! oder ein Feld setzt, muss Werte liefern, die sich in den Modelltyp lesen lassen (`Project::set_field`,
//! dieselbe Lese-Logik wie die typisierte Sicht). Sonst würde das Dokument den Wert annehmen und
//! speichern, die typisierte Sicht aber still auf die Vorgabe zurückfallen (`lenient`).
//!
//! Alt-Dateien bleiben tolerant: Laden prüft nicht. Ersetzt eine Op ein Element (oder Feld), das schon
//! vorher nicht zum Modell passte, gilt nur ein NEUER Fehler: die Pfade, die das tolerante Lesen beim
//! neuen Wert verwerfen müsste, dürfen nicht über die des alten hinausgehen.
//!
//! Aufwand: nur die berührten Elemente/Felder werden gelesen (wie die typisierte Sicht es danach
//! ohnehin tut); die Fehlersuche (Pfade, Vergleich mit dem alten Wert) läuft nur im Fehlerfall.
use super::lenient::set_field_lenient;
use super::Project;
use serde_json::Value;
use std::collections::{BTreeSet, HashMap};
/// Liest `v` als Feld `key` (`None`/`null` = Feld fehlt, wie die typisierte Sicht).
pub fn check_field(key: &str, v: Option<&Value>) -> Result<(), String> {
super::allowing_extra(|| Project::default().set_field(key, v.filter(|v| !v.is_null())))
}
/// Pfade, die das tolerante Lesen von `v` als Feld `key` verwerfen müsste (leer = passt).
pub fn bad_paths(key: &str, v: Option<&Value>) -> BTreeSet<String> {
super::allowing_extra(|| set_field_lenient(&mut Project::default(), key, v.filter(|v| !v.is_null()))).into_iter().collect()
}
/// Pfade eines einzelnen Listenelements (ohne den Präfix `key[0]`).
fn item_paths(key: &str, item: &Value) -> BTreeSet<String> {
let one = Value::Array(vec![item.clone()]);
let prefix = format!("{key}[0]");
bad_paths(key, Some(&one))
.into_iter()
.map(|p| match p.strip_prefix(&prefix) {
Some("") => "(Element)".to_string(),
Some(rest) => rest.trim_start_matches('.').to_string(),
None => p,
})
.collect()
}
fn id_text(v: &Value) -> &str {
crate::ops::id_of(v).unwrap_or("undefined")
}
/// Meldung für ein Element, das nicht zum Modell passt.
fn item_message(key: &str, item: &Value, paths: &BTreeSet<String>) -> String {
let err = check_field(key, Some(&Value::Array(vec![item.clone()]))).err().unwrap_or_default();
let fields = paths.iter().cloned().collect::<Vec<_>>().join(", ");
format!("„{key}\" {}: Feld {fields} passt nicht zum Modell ({err}).", id_text(item))
}
/// Prüft neue Listenelemente (`add`/`replace` in die Liste `key`). `items` wird für die Prüfung
/// kurz in ein Array verschoben (keine Kopie) und unverändert zurückgegeben. `old(id)` = das Element
/// mit dieser id vor der Op (Alt-Fehler zählen nicht, s. Modulkopf).
pub fn check_items<'a>(key: &str, items: &mut Vec<Value>, old: &dyn Fn(&str) -> Option<&'a Value>) -> Vec<String> {
let arr = Value::Array(std::mem::take(items));
let whole = check_field(key, Some(&arr));
let Value::Array(back) = arr else { unreachable!("eben gebaut") };
*items = back;
if whole.is_ok() {
return Vec::new();
}
let mut problems = Vec::new();
for item in items.iter() {
let one = Value::Array(vec![item.clone()]);
if check_field(key, Some(&one)).is_ok() {
continue;
}
let paths = item_paths(key, item);
let legacy = crate::ops::id_of(item).and_then(old).map(|o| item_paths(key, o));
if legacy.is_some_and(|l| paths.is_subset(&l)) {
continue;
}
problems.push(item_message(key, item, &paths));
}
problems
}
/// Prüft einen neuen Feldwert (`setField`). `old` = Wert vorher. Bei Listen mit ids werden Alt-Fehler
/// je Element (per id) verglichen, sonst über das ganze Feld.
pub fn check_set_field(key: &str, value: Option<&Value>, old: Option<&Value>) -> Vec<String> {
let Err(err) = check_field(key, value) else { return Vec::new() };
if let Some(Value::Array(items)) = value {
if items.iter().all(|e| crate::ops::id_of(e).is_some()) {
let old_by_id: HashMap<&str, &Value> =
old.and_then(Value::as_array).into_iter().flatten().filter_map(|e| crate::ops::id_of(e).map(|i| (i, e))).collect();
let mut items = items.clone();
return check_items(key, &mut items, &|id| old_by_id.get(id).copied());
}
}
let new_paths = bad_paths(key, value);
if old.is_some_and(|o| new_paths.is_subset(&bad_paths(key, Some(o)))) && !new_paths.is_empty() {
return Vec::new();
}
let fields = new_paths.into_iter().collect::<Vec<_>>().join(", ");
let fields = if fields.is_empty() { key.to_string() } else { fields };
vec![format!("Feld „{key}\": {fields} passt nicht zum Modell ({err}).")]
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn element_pruefung_meldet_id_feld_und_fehler() {
let mut items = vec![json!({"id": "w1", "height": "hoch"})];
let p = check_items("walls", &mut items, &|_| None);
assert_eq!(items.len(), 1, "Elemente kommen zurück");
assert_eq!(p.len(), 1);
assert!(p[0].contains("w1") && p[0].contains("height") && p[0].contains("invalid type"), "{p:?}");
// Passend, fremde Liste (ausserhalb des Modells): keine Meldung.
assert!(check_items("walls", &mut vec![json!({"id": "w", "height": 3})], &|_| None).is_empty());
assert!(check_items("eigeneListe", &mut vec![json!({"id": "x", "a": "b"})], &|_| None).is_empty());
}
#[test]
fn alt_fehler_zaehlen_nicht() {
let old = json!({"id": "w1", "height": null, "start": {"x": 0, "y": 0}});
// Gleicher Alt-Fehler, andere Änderung: angenommen.
let mut items = vec![json!({"id": "w1", "height": null, "start": {"x": 1, "y": 0}})];
assert!(check_items("walls", &mut items, &|_| Some(&old)).is_empty());
// Neuer Fehler dazu: abgelehnt.
let mut items = vec![json!({"id": "w1", "height": null, "start": {"x": "a", "y": 0}})];
let p = check_items("walls", &mut items, &|_| Some(&old));
assert!(p.len() == 1 && p[0].contains("start.x"), "{p:?}");
}
#[test]
fn feld_pruefung() {
assert!(check_set_field("parcelArea", Some(&json!(12.5)), None).is_empty());
assert!(check_set_field("parcelArea", Some(&Value::Null), None).is_empty(), "null = Feld fehlt");
assert!(check_set_field("parcelArea", None, None).is_empty());
let p = check_set_field("parcelArea", Some(&json!("gross")), None);
assert!(p.len() == 1 && p[0].contains("parcelArea"), "{p:?}");
let p = check_set_field("walls", Some(&json!([{"id": "a"}, {"id": "b", "height": [1]}])), None);
assert!(p.len() == 1 && p[0].contains("\" b:") && p[0].contains("height"), "{p:?}");
// Unbekanntes Feld: frei (Extra).
assert!(check_set_field("meinFeld", Some(&json!({"x": "y"})), None).is_empty());
}
}
+7
View File
@@ -271,6 +271,13 @@ pub fn project_lenient(root: &Map<String, Value>) -> (Project, Vec<String>) {
(p, dropped)
}
/// Typisierte Sicht einer Test-Wurzel (tolerant, unbekannte Felder erlaubt): für Tests von Funktionen,
/// die Wurzel und Sicht zugleich lesen ([124]).
#[cfg(test)]
pub fn typed_for_test(root: &Map<String, Value>) -> Project {
super::allowing_extra(|| project_lenient(root).0)
}
#[cfg(test)]
mod tests {
use super::*;
+16 -1
View File
@@ -14,6 +14,21 @@ pub struct Extra(pub serde_json::Map<String, serde_json::Value>);
thread_local! {
/// Gesetzt während [`to_value_typed_only`]: `Extra` schreibt dann nichts.
static OMIT_EXTRA: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Gesetzt während [`allowing_extra`]: unbekannte Felder sind auch in Tests kein Panic.
static ALLOW_EXTRA: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Führt `f` aus, ohne dass unbekannte Felder in Tests einen Panic auslösen (Prüfung neuer Op-Werte,
/// `model::check`: Felder ausserhalb des Modells sind erlaubt — die Test-Stummel tragen viele).
pub fn allowing_extra<R>(f: impl FnOnce() -> R) -> R {
struct Reset(bool);
impl Drop for Reset {
fn drop(&mut self) {
ALLOW_EXTRA.with(|a| a.set(self.0));
}
}
let _reset = Reset(ALLOW_EXTRA.with(|a| a.replace(true)));
f()
}
impl Serialize for Extra {
@@ -44,7 +59,7 @@ impl<'de> Deserialize<'de> for Extra {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let m = serde_json::Map::<String, serde_json::Value>::deserialize(d)?;
#[cfg(test)]
if !m.is_empty() {
if !m.is_empty() && !ALLOW_EXTRA.with(|a| a.get()) {
panic!("Modell kennt Felder nicht: {:?}", m.keys().collect::<Vec<_>>());
}
Ok(Extra(m))
+1
View File
@@ -4,6 +4,7 @@
//! (`src/model/types.generated.ts`) erzeugt `ts_export.rs` daraus (`npm run gen:types`).
//! Neue Modellfelder nur hier eintragen (serde + ts-rs-Attribute, Regeln in `ts_export.rs`).
pub mod check;
pub mod generated;
pub mod helpers;
pub mod items;
+1 -1
View File
@@ -12,7 +12,7 @@ pub const PEN_FALLBACK_COLOR: &str = "#9aa0a6";
/// Strichstärke (mm) eines Stifts ohne Eintrag.
pub const PEN_FALLBACK_WEIGHT: f64 = 0.18;
use crate::grips::truthy;
use crate::json_util::truthy;
/// Schlüssel des Stifts als Objekt-Schlüssel (JS: `pens[penId]`, eine Zahl wird zu Text).
fn key_of(v: &Value) -> Option<String> {
+10 -1
View File
@@ -83,6 +83,16 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
}
}
/// Wie [`run_root`] auf dem Dokument; Befehle (`cmdOps`, [K4] S3, `commands.rs`: `text` = JSON `{cmd, …}`,
/// Antwort `{ops}`) lesen dazu die typisierte Sicht ([124]).
pub fn run_root_doc(d: &mut crate::document::Document, name: &str, text: &str) -> Result<String, String> {
if name == "cmdOps" {
let (p, lk) = d.project_lookup()?;
return crate::commands::ops_json(lk.root, p, text);
}
run_root(&d.lookup(), name, text)
}
/// Abfragen auf der rohen Projekt-Wurzel (JSON-Baum, verlustfrei; Antwort JSON). `text`: Argument als Text/JSON.
/// Elemente per id sucht `lk` (im Dokument über dessen Positions-Index).
pub fn run_root(lk: &crate::document::Lookup, name: &str, text: &str) -> Result<String, String> {
@@ -132,7 +142,6 @@ pub fn run_root(lk: &crate::document::Lookup, name: &str, text: &str) -> Result<
}
// Griff-Änderungen ([K4] S3, `grips.rs`): `text` = JSON der Anfrage; Antwort `{ops, notice}` (ohne Commit).
// Befehle ([K4] S3, `commands.rs`): `text` = JSON `{cmd, …}`; Antwort `{ops}`.
"cmdOps" => crate::commands::ops_json(root, text),
"gripOps" => {
let req: crate::grips::Request = serde_json::from_str(text).map_err(|e| format!("gripOps: {e}"))?;
Ok(crate::grips::result_json(&crate::grips::run(lk, &req)?))
+2 -2
View File
@@ -9,14 +9,14 @@
//! nach einem Mausschritt an einer grossen Liste wäre deren Neueinlesen teurer als die Abfrage). Nur das
//! gewählte Dach, die Treppe und die Stütze werden typisiert gelesen, wo die Geometrie schon typisiert im
//! Kern steht (`roof.rs`, `stair.rs`, `model3d::column_footprint`). Zahlen wie in JS: `null` rechnet wie
//! 0 (`grips::num_of`), nicht endliche Ergebnisse reisen als Marken (`grips::js_num`).
//! 0 (`json_util::num_of`), nicht endliche Ergebnisse reisen als Marken (`json_util::js_num`).
//!
//! Wo TS warf (unbekannter Wandtyp, Deckentyp oder Bauteil), kommt dieselbe Meldung als Fehler.
//! Der B-Rep-Körper einer Extrusion (`spec`) bleibt in TS (truck-Pipeline, `plan/extrudedSolidSpec.ts`).
use crate::document::Lookup;
use crate::model::helpers::heights;
use crate::grips::{arr, field, js_num, num_of, truthy, xy};
use crate::json_util::{arr, field, js_num, num_of, truthy, xy};
use crate::jsmath::hypot2;
use crate::jsnum;
use crate::ops::id_of;
+6 -1
View File
@@ -19,7 +19,12 @@ fn run(h: u32, req: &Req, pts: &[f64]) -> Vec<f64> {
if pts.len() % 2 != 0 {
return Vec::new();
}
with_doc(h, |d| crate::cmd_create::preview_req(d.root(), req, pts).flat()).unwrap_or_default()
with_doc(h, |d| {
let (p, lk) = d.project_lookup().ok()?;
Some(crate::cmd_create::preview_req(lk.root, p, req, pts).flat())
})
.flatten()
.unwrap_or_default()
}
/// Vorschau eines Zeichenbefehls auf dem Dokument `h`: `[ok, nInfo, info…, Formen…]` (Formen wie
+5 -1
View File
@@ -13,7 +13,11 @@ pub fn doc_cmd_commit(h: u32, req_json: &str, key: &str, now_ms: f64) -> String
let key = (!key.is_empty()).then_some(key);
let now = if now_ms.is_finite() { now_ms } else { 0.0 };
let out = with_doc(h, |d| -> Result<String, String> {
let res = crate::grips::GripResult { ops: crate::commands::ops(d.root(), req_json)?, notice: None };
let ops = {
let (p, lk) = d.project_lookup()?;
crate::commands::ops(lk.root, p, req_json)?
};
let res = crate::grips::GripResult { ops, notice: None };
let text = crate::grips::result_json(&res);
if res.ops.is_empty() {
return Ok(text);
+1 -1
View File
@@ -254,7 +254,7 @@ 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_args`].
#[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.lookup(), name, text)).unwrap_or_else(|| Err("Dokument nicht offen".to_string()));
let result = with_doc(h, |d| crate::queries::run_root_doc(d, name, text)).unwrap_or_else(|| Err("Dokument nicht offen".to_string()));
match result {
Ok(json) => json,
Err(e) => format!("\u{1}{e}"),
+52
View File
@@ -0,0 +1,52 @@
// [124] Ops werden gegen das typisierte Modell geprüft: die Beispielprojekte (Musterhaus, Musterhaus
// komplex — dieses entsteht zum Teil über Kern-Befehle) gehen als Op-Folge durch, Element für Element;
// ein falsch typisierter Wert wird mit Meldung (id, Feld, Fehler) zurückgewiesen.
import { describe, expect, it } from "vitest";
import { ProjectDocument } from "./document";
import type { CoreOp } from "./ops";
import type { Project } from "../model/types";
import { sampleProject } from "../model/sampleProject";
import { buildComplexSampleProject } from "../model/sampleProjectComplex";
const empty = (): Project => ({ id: "p", name: "leer", lineStyles: [], hatches: [], components: [], wallTypes: [], drawingLevels: [], layers: [], walls: [], drawings2d: [] });
/** Das ganze Projekt als Ops: Listen mit ids elementweise (`add` je Element), sonst `setField`. */
function projectOps(p: Project): CoreOp[] {
const ops: CoreOp[] = [];
for (const [key, value] of Object.entries(p)) {
if (value === undefined) continue;
const isIdList = Array.isArray(value) && value.length > 0 && value.every((e) => e && typeof e === "object" && typeof (e as { id?: unknown }).id === "string");
if (isIdList) for (const item of value as { id: string }[]) ops.push({ kind: "add", collection: key, items: [item] });
else ops.push({ kind: "setField", key, value });
}
return ops;
}
describe("Op-Prüfung gegen das Modell ([124])", () => {
for (const [name, build] of [["Musterhaus", () => sampleProject], ["Musterhaus komplex", buildComplexSampleProject]] as const) {
it(`${name}: alle Elemente als Ops angenommen`, () => {
const p = build();
const base = empty();
const doc = new ProjectDocument(base);
const res = doc.commit(base, projectOps(p), undefined, 0);
expect("problems" in res ? res.problems : []).toEqual([]);
if ("project" in res) expect(res.project.walls.length).toBe(p.walls.length);
doc.close();
});
}
it("falsch typisierte Werte werden mit id, Feld und Fehler zurückgewiesen", () => {
const p: Project = { ...empty(), walls: [{ ...sampleProject.walls[0], id: "w1" }] };
const doc = new ProjectDocument(p);
const bad = { ...p.walls[0], height: "hoch" as unknown as number };
const res = doc.commit(p, [{ kind: "replace", collection: "walls", entity: bad }], undefined, 0);
expect("problems" in res).toBe(true);
const text = "problems" in res ? res.problems.join(" ") : "";
expect(text).toContain("w1");
expect(text).toContain("height");
const enumBad = doc.commit(p, [{ kind: "add", collection: "drawings2d", items: [{ id: "d", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "klecks" } } as never] }], undefined, 0);
expect("problems" in enumBad && enumBad.problems.join(" ")).toContain("unknown variant");
doc.close();
});
});