BREP_render 0.2.1

BREP Rust rendering engine: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
//! Feature-schema access + the feature-schema → [`FormField`] mapping.
//!
//! The kernel OWNS the feature definitions (`feature_pipeline/schema.rs`; each
//! `features/<feat>.rs` declares its own `schema()` with an `inputParamsSchema`).
//! This module reaches that catalogue from native Rust (re-exported by the
//! kernel as [`brep_kernel::feature_schema_catalogue`]) and maps ONE feature's
//! parameter schema into the general [`FormField`] list the shared egui form
//! engine renders — the SAME `FormField`s the settings dialog uses.
//!
//! The map classifies each kernel param `type`:
//!   * `number`             → [`FieldKind::Scalar`]      (unbounded drag value)
//!   * `string`             → [`FieldKind::Text`]        (`id` is read-only)
//!   * `transform`          → three [`FieldKind::Vec3`]  (position/rotation/scale)
//!   * `boolean_operation`  → an [`FieldKind::Enum`] (operation) + a
//!                            [`FieldKind::Reference`] (tools) + a
//!                            [`FieldKind::Bool`] (mergeCoplanarFaces)
//!   * `reference_selection`→ [`FieldKind::Reference`]   (the #42 seam)
//!
//! REFERENCE-SELECTION field types (rendered as the disabled placeholder — the
//! seam for the next slice's real picker): the top-level `reference_selection`
//! params, and the `targets` list inside a `boolean_operation`. (`transform`'s
//! optional start `reference` is not surfaced here yet.)

use crate::style::{FieldKind, FormField};
use serde_json::Value;

/// The kernel-owned feature-schema catalogue (`{ version, features: [...] }`).
pub fn feature_catalogue() -> Value {
    brep_kernel::feature_schema_catalogue()
}

/// One feature's full schema entry, by its `type` / `shortName` (e.g. `"P.CU"`,
/// `"B"`). `None` if the type is not in the catalogue.
pub fn feature_schema(feature_type: &str) -> Option<Value> {
    feature_catalogue()
        .get("features")?
        .as_array()?
        .iter()
        .find(|f| {
            f.get("type").and_then(Value::as_str) == Some(feature_type)
                || f.get("shortName").and_then(Value::as_str) == Some(feature_type)
        })
        .cloned()
}

/// Human display name for a feature type: the schema `longName` (else the type
/// itself), with the feature's icon character PREPENDED. Every consumer that
/// shows a feature name (add-feature palette, history tree, context-bar offers,
/// dialogs) reads it through here, so the icon appears everywhere with no
/// per-caller wiring — see [`feature_icon`].
pub fn feature_long_name(feature_type: &str) -> String {
    let name = feature_plain_name(feature_type);
    match feature_icon(feature_type) {
        Some(glyph) => format!("{glyph} {name}"),
        None => name,
    }
}

/// The same display name WITHOUT the leading glyph — the schema `longName`, else
/// the type itself.
///
/// For the one kind of caller that draws the icon as ARTWORK rather than as a
/// character: the history tree gives the icon its own column
/// (`brep_app::panels::tree::TreeRow::glyph`), so its label must not carry the
/// glyph a second time. Everything that shows a feature name as plain text
/// keeps reading [`feature_long_name`], which is still where the icon is
/// prepended.
pub fn feature_plain_name(feature_type: &str) -> String {
    feature_schema(feature_type)
        .and_then(|f| f.get("longName").and_then(Value::as_str).map(String::from))
        .unwrap_or_else(|| feature_type.to_string())
}

/// A feature type's SHORT name (`shortName`, e.g. `P.CU`, `S`, `E`), else the
/// type code itself. This is the BASE for a new feature's id: the engine appends
/// the part history's persistent global counter to it (`P.CU` → `P.CU7`,
/// `S` → `S8`) in [`crate::history::History::next_feature_id`].
pub fn feature_short_name(feature_type: &str) -> String {
    feature_schema(feature_type)
        .and_then(|f| f.get("shortName").and_then(Value::as_str).map(String::from))
        .unwrap_or_else(|| feature_type.to_string())
}

/// The icon character for a feature type, if one exists. Every kernel
/// feature type has a FreeCAD-inspired monoline glyph in the font's Private-Use
/// block U+E030-E059 (edited as `BREP_app/assets/glyphs/*.svg`, which are also
/// the source of the inline SVG icon catalog — see `BREP_app/src/icons.rs`;
/// `every_feature_type_has_catalogued_artwork` there checks each of these
/// codepoints actually HAS a glyph, which this module's own test cannot). The font is
/// installed as family `"brep_icons"` at the HEAD of egui's fallback chain
/// ([`crate`]-side `fonts.rs`), so a bare returned `char` renders as the icon.
///
/// Matches the SAME alias set the kernel dispatch does (short codes AND the
/// long-/class-name strings saved files carry — e.g. `"CHAMFER"`, the misspelt
/// `"DATIUM"`, `"PUSH FACE"`), uppercased, so a type loaded from disk resolves.
pub fn feature_icon(kind: &str) -> Option<char> {
    let cp: u32 = match kind.trim().to_ascii_uppercase().as_str() {
        "D" | "DATUM" | "DATIUM" => 0xE030,
        "P" | "PLANE" => 0xE031,
        "P.CU" | "CUBE" => 0xE032,
        "P.CY" | "CYLINDER" => 0xE033,
        "P.CO" | "CONE" => 0xE034,
        "P.S" | "SPHERE" => 0xE035,
        "P.T" | "TORUS" => 0xE036,
        "P.PY" | "PYRAMID" => 0xE037,
        "IMPORT3D" => 0xE038,
        "S" | "SKETCH" => 0xE039,
        "SP" | "SPLINE" => 0xE03A,
        "PORT" => 0xE03B,
        "HX" | "HELIX" => 0xE03C,
        "E" | "EXTRUDE" => 0xE03D,
        "B" | "BOOLEAN" => 0xE03E,
        "F" | "FILLET" => 0xE03F,
        "CH" | "CHAMFER" => 0xE040,
        "O.S" | "OFFSET SHELL" | "OFFSETSHELL" => 0xE041,
        "O.F" | "OFFSET FACE" | "OFFSETFACE" => 0xE042,
        "PF" | "PUSHFACE" | "PUSH FACE" => 0xE043,
        "DF" | "DELETE FACE" | "DELETEFACE" => 0xE044,
        "THK" | "THICKEN" => 0xE045,
        "SM.TAB" => 0xE046,
        "SM.CF" => 0xE047,
        "SM.F" => 0xE048,
        "SM.HEM" => 0xE049,
        "SM.FILLET" | "SM.CFIL" => 0xE04A,
        "SM.CHAMFER" | "SM.CCHM" => 0xE04B,
        "SM.CUTOUT" => 0xE04C,
        "LOFT" => 0xE04D,
        "M" | "MIRROR" => 0xE04E,
        "SPL" | "SPLIT" => 0xE04F,
        "R" | "REVOLVE" => 0xE050,
        "RIB" => 0xE051,
        "SW" | "SWEEP" => 0xE052,
        "SWP" | "PATH SWEEP" | "PATHSWEEP" => 0xE053,
        "H" | "HOLE" => 0xE054,
        "TU" | "TUBE" => 0xE055,
        "XFORM" | "TRANSFORM" => 0xE056,
        "PATTERN" => 0xE057,
        "ACOMP" | "ASSEMBLY COMPONENT" => 0xE058,
        "SM.UNFOLD" => 0xE059,
        _ => return None,
    };
    char::from_u32(cp)
}

/// A feature type's DEFAULT `inputParams`, built from its schema: one entry per
/// `inputParamsSchema` param seeded with that param's `default_value` (missing →
/// `null`). The caller assigns the unique `id` afterwards (the schema's `id`
/// default is `null`). Additive, engine-owned, and reusable by any "add feature"
/// path so a new feature's params always track the kernel schema. Unknown types
/// yield an empty object.
pub fn feature_default_params(feature_type: &str) -> Value {
    let mut params = serde_json::Map::new();
    if let Some(props) = feature_schema(feature_type)
        .as_ref()
        .and_then(|s| s.get("inputParamsSchema"))
        .and_then(Value::as_object)
    {
        for (name, spec) in props {
            let default = spec.get("default_value").cloned().unwrap_or(Value::Null);
            params.insert(name.clone(), default);
        }
    }
    Value::Object(params)
}

/// The boolean operation choices (a fixed kernel enum — the schema stores only a
/// default operation, not the variant set, so the known set rides here).
const BOOLEAN_OPS: &[&str] = &["NONE", "UNION", "SUBTRACT", "INTERSECT"];

/// Map a feature type's `inputParamsSchema` into the general form fields, in
/// schema (insertion) order — the kernel builds schemas with serde_json's
/// `preserve_order`, so grouped fields stay contiguous for the group headers.
pub fn feature_form_fields(feature_type: &str) -> Vec<FormField> {
    let Some(schema) = feature_schema(feature_type) else {
        return Vec::new();
    };
    form_fields_from_schema(&schema)
}

/// Map ANY schema entry carrying an `inputParamsSchema` object into form fields
/// — the shared engine behind [`feature_form_fields`] AND the assembly
/// constraint dialogs (whose schemas come from the kernel's
/// `constraint_schema_catalogue`, same shape, different catalogue). One mapping,
/// two catalogues (the schema-driven-dialog principle).
pub fn form_fields_from_schema(schema: &Value) -> Vec<FormField> {
    let Some(params) = schema
        .get("inputParamsSchema")
        .and_then(Value::as_object)
    else {
        return Vec::new();
    };

    let mut fields = Vec::new();
    for (name, spec) in params {
        let ty = spec.get("type").and_then(Value::as_str).unwrap_or("");
        match ty {
            "number" => fields.push(FormField {
                path: vec![name.clone()],
                label: prettify(name),
                group: "Parameters".into(),
                kind: FieldKind::Scalar { step: 0.5 },
            }),
            "string" => fields.push(FormField {
                path: vec![name.clone()],
                label: prettify(name),
                group: "Parameters".into(),
                // The `id` is the feature's identity; editing it must cascade to
                // references, so it is shown read-only for now.
                kind: FieldKind::Text {
                    read_only: name == "id",
                },
            }),
            "transform" => {
                // TWO transform param shapes share the `transform` schema type,
                // discriminated by the schema's own `default_value` (the shape a
                // fresh feature is seeded with, so it can never lie):
                //   * the ACOMP rigid instance pose `{translate, rotateEulerDeg}`
                //     (assemblies spec §2.2 — no scale, degrees, intrinsic XYZ);
                //   * the legacy `{position, rotationEuler, scale}` triple every
                //     modeling feature uses.
                // The mapping lives HERE (the form-engine altitude) so no dialog
                // ever special-cases a feature type.
                let is_rigid_pose = spec
                    .get("default_value")
                    .map(|d| d.get("translate").is_some() || d.get("rotateEulerDeg").is_some())
                    .unwrap_or(false);
                if is_rigid_pose {
                    fields.push(vec3_field(name, "translate", "Translate", 0.5));
                    fields.push(vec3_field(name, "rotateEulerDeg", "Rotation (deg)", 1.0));
                } else {
                    fields.push(vec3_field(name, "position", "Position", 0.5));
                    fields.push(vec3_field(name, "rotationEuler", "Rotation (deg)", 1.0));
                    fields.push(vec3_field(name, "scale", "Scale", 0.1));
                }
            }
            "boolean" => {
                // A plain checkbox param (e.g. ACOMP `isFixed`, constraint
                // `reverse`/`opposeNormals`/`exteriorAngle`). Label from the
                // schema's `label` when present, else the prettified key.
                fields.push(FormField {
                    path: vec![name.clone()],
                    label: field_label(spec, name),
                    group: "Parameters".into(),
                    kind: FieldKind::Bool,
                });
            }
            "boolean_operation" => {
                fields.push(FormField {
                    path: vec![name.clone(), "operation".into()],
                    label: "Operation".into(),
                    group: "Boolean".into(),
                    kind: FieldKind::Enum {
                        variants: BOOLEAN_OPS.iter().map(|s| s.to_string()).collect(),
                    },
                });
                fields.push(FormField {
                    path: vec![name.clone(), "targets".into()],
                    label: "Tool solids".into(),
                    group: "Boolean".into(),
                    kind: FieldKind::Reference {
                        filter: vec!["SOLID".into()],
                        multiple: true,
                    },
                });
                fields.push(FormField {
                    path: vec![name.clone(), "mergeCoplanarFaces".into()],
                    label: "Merge coplanar faces".into(),
                    group: "Boolean".into(),
                    kind: FieldKind::Bool,
                });
            }
            "button" => {
                // An action button (e.g. Edit Sketch): binds to no value. Its
                // `key` (the schema key) identifies the click to the host. The
                // caption is the schema `label` (falling back to the key).
                let label = spec
                    .get("label")
                    .and_then(Value::as_str)
                    .map(String::from)
                    .unwrap_or_else(|| prettify(name));
                fields.push(FormField {
                    path: vec![name.clone()],
                    label: label.clone(),
                    group: "Parameters".into(),
                    kind: FieldKind::Button { label },
                });
            }
            "reference_selection" => {
                let filter = spec
                    .get("selectionFilter")
                    .and_then(Value::as_array)
                    .map(|a| {
                        a.iter()
                            .filter_map(|v| v.as_str().map(String::from))
                            .collect()
                    })
                    .unwrap_or_default();
                let multiple = spec
                    .get("multiple")
                    .and_then(Value::as_bool)
                    .unwrap_or(false);
                // `"References"` is a SEMANTIC TAG, not a rendered wrapper: the
                // history tree inlines this group (each reference renders as its
                // own self-titled node — no "References" parent), and the context
                // bar keys on it to find a feature's PRE-FILL fields (top-level
                // `reference_selection`s, vs a boolean-op `targets` in `Boolean`;
                // WHETHER a feature is offered is the kernel predicate's call —
                // `feature_pipeline::context_offer`).
                fields.push(FormField {
                    path: vec![name.clone()],
                    label: prettify(name),
                    group: "References".into(),
                    kind: FieldKind::Reference { filter, multiple },
                });
            }
            "options" => {
                // A single-choice enum: render as a dropdown of the schema's
                // `options`, using the field's `label` when present (e.g.
                // flangeLengthReference → "Length reference", inset → "Flange
                // position") else the prettified key.
                let variants = spec
                    .get("options")
                    .and_then(Value::as_array)
                    .map(|a| {
                        a.iter()
                            .filter_map(|v| v.as_str().map(String::from))
                            .collect()
                    })
                    .unwrap_or_default();
                fields.push(FormField {
                    path: vec![name.clone()],
                    label: field_label(spec, name),
                    group: "Parameters".into(),
                    kind: FieldKind::Enum { variants },
                });
            }
            // Unmapped kernel param types (vec3-array/etc. arrive as more
            // features are wired) are skipped rather than mis-rendered.
            _ => {}
        }
    }
    fields
}

fn vec3_field(param: &str, sub: &str, label: &str, step: f64) -> FormField {
    FormField {
        path: vec![param.to_string(), sub.to_string()],
        label: label.to_string(),
        group: "Transform".into(),
        kind: FieldKind::Vec3 { step },
    }
}

/// A field's display label: the schema `label` when set, else the prettified key.
fn field_label(spec: &Value, name: &str) -> String {
    spec.get("label")
        .and_then(Value::as_str)
        .map(String::from)
        .unwrap_or_else(|| prettify(name))
}

/// `sizeX` → `Size X`, `rotationEuler` → `Rotation euler`, `id` → `Id`.
fn prettify(key: &str) -> String {
    let mut out = String::new();
    for (i, ch) in key.chars().enumerate() {
        if i == 0 {
            out.extend(ch.to_uppercase());
        } else if ch.is_ascii_uppercase() {
            out.push(' ');
            out.extend(ch.to_lowercase());
        } else {
            out.push(ch);
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn catalogue_is_reachable_from_native_rust() {
        let cat = feature_catalogue();
        assert!(cat.get("features").and_then(Value::as_array).is_some());
        assert!(feature_schema("P.CU").is_some());
        assert!(feature_schema("P.CY").is_some());
        assert!(feature_schema("B").is_some());
        // Glyph is prepended; the name still ends with the schema longName.
        assert!(feature_long_name("P.CU").ends_with("Primitive Cube"));
        assert!(feature_long_name("P.CU").starts_with(feature_icon("P.CU").unwrap()));
    }

    #[test]
    fn every_catalogue_feature_type_has_an_icon() {
        // The palette + history tree prefix every feature with its glyph, so a
        // missing mapping would leave a bare feature with no icon. Guard the
        // whole catalogue against a future feature landing without a glyph.
        let cat = feature_catalogue();
        for feature in cat["features"].as_array().expect("features") {
            let ty = feature["type"].as_str().expect("type");
            assert!(
                feature_icon(ty).is_some(),
                "feature type {ty} has no icon (add one under BREP_app/assets/glyphs/ + features::feature_icon)"
            );
        }
        // Alias resolution: the long-name / misspelt strings saved files use.
        assert_eq!(feature_icon("CHAMFER"), feature_icon("CH"));
        assert_eq!(feature_icon("DATIUM"), feature_icon("D"));
        assert_eq!(feature_icon("push face"), feature_icon("PF"));
        assert!(feature_icon("NOPE").is_none());
    }

    #[test]
    fn short_name_is_the_schema_code_or_the_type_fallback() {
        // The base for a new feature's id: the schema shortName (incl. dotted
        // primitive codes), falling back to the type code for an unknown type.
        assert_eq!(feature_short_name("P.CU"), "P.CU");
        assert_eq!(feature_short_name("P.S"), "P.S");
        assert_eq!(feature_short_name("S"), "S");
        assert_eq!(feature_short_name("E"), "E");
        assert_eq!(feature_short_name("NOPE"), "NOPE");
    }

    #[test]
    fn cube_form_fields_map_types_correctly() {
        let fields = feature_form_fields("P.CU");
        // id (read-only Text), sizeX/Y/Z (Scalar), transform → 3× Vec3,
        // boolean → Enum + Reference + Bool.
        let by_key = |k: &str| fields.iter().find(|f| f.key() == k).cloned();

        assert!(matches!(
            by_key("id").unwrap().kind,
            FieldKind::Text { read_only: true }
        ));
        assert!(matches!(
            by_key("sizeX").unwrap().kind,
            FieldKind::Scalar { .. }
        ));
        // transform expands into three Vec3 sub-fields on nested paths.
        let position = fields
            .iter()
            .find(|f| f.path == ["transform", "position"])
            .expect("transform.position vec3");
        assert!(matches!(position.kind, FieldKind::Vec3 { .. }));
        assert_eq!(
            fields
                .iter()
                .filter(|f| matches!(f.kind, FieldKind::Vec3 { .. }))
                .count(),
            3
        );
        // boolean_operation expands: operation Enum, targets Reference, merge Bool.
        let op = fields
            .iter()
            .find(|f| f.path == ["boolean", "operation"])
            .expect("boolean.operation");
        assert!(matches!(op.kind, FieldKind::Enum { .. }));
        let targets = fields
            .iter()
            .find(|f| f.path == ["boolean", "targets"])
            .expect("boolean.targets");
        assert!(matches!(targets.kind, FieldKind::Reference { multiple: true, .. }));
    }

    #[test]
    fn flange_options_and_boolean_fields_render() {
        // Regression: `options` and plain `boolean` schema fields fell into the
        // `_ => {}` catch-all and were silently skipped, so the flange's
        // length-reference / position dropdowns (and Reverse-direction toggle)
        // never appeared in the dialog.
        let fields = feature_form_fields("SM.F");
        let by_key = |k: &str| fields.iter().find(|f| f.key() == k).cloned();

        let length_ref = by_key("flangeLengthReference").expect("flangeLengthReference renders");
        assert_eq!(length_ref.label, "Length reference");
        if let FieldKind::Enum { variants } = &length_ref.kind {
            assert!(variants.iter().any(|v| v.as_str() == "Inner Virtual Sharp"));
            assert!(variants.iter().any(|v| v.as_str() == "Outer Virtual Sharp"));
            assert!(variants.iter().any(|v| v.as_str() == "Tangent to Bend"));
        } else {
            panic!("flangeLengthReference should render as an Enum dropdown");
        }

        let inset = by_key("inset").expect("inset (Flange position) renders");
        assert_eq!(inset.label, "Flange position");
        assert!(matches!(inset.kind, FieldKind::Enum { .. }));

        // plain `boolean` now renders too, with its schema label.
        let reverse = by_key("useOppositeCenterline").expect("useOppositeCenterline renders");
        assert_eq!(reverse.label, "Reverse direction");
        assert!(matches!(reverse.kind, FieldKind::Bool));
    }

    #[test]
    fn default_params_seed_from_schema_defaults() {
        // A primitive's defaults are COMPLETE (build-ready) straight from schema.
        let cube = feature_default_params("P.CU");
        assert_eq!(cube["sizeX"], 10.0);
        assert_eq!(cube["sizeY"], 10.0);
        assert_eq!(cube["transform"]["scale"], serde_json::json!([1, 1, 1]));
        assert_eq!(cube["boolean"]["operation"], "NONE");
        // The `id` default is null — the caller assigns a unique one.
        assert_eq!(cube["id"], Value::Null);
        // A feature whose reference default is null still yields the key.
        let boolean = feature_default_params("B");
        assert!(boolean.as_object().unwrap().contains_key("targetSolid"));
        assert_eq!(boolean["boolean"]["operation"], "UNION");
        // Unknown types → empty object (no panic).
        assert_eq!(feature_default_params("NOPE"), serde_json::json!({}));
    }

    #[test]
    fn boolean_feature_target_is_a_reference_field() {
        let fields = feature_form_fields("B");
        let target = fields
            .iter()
            .find(|f| f.key() == "targetSolid")
            .expect("targetSolid field");
        match &target.kind {
            FieldKind::Reference { filter, multiple } => {
                assert_eq!(filter, &["SOLID".to_string()]);
                assert!(!multiple);
            }
            other => panic!("targetSolid should be a Reference, got {other:?}"),
        }
    }

    #[test]
    fn sketch_feature_maps_button_fields() {
        // The SKETCH schema's `editSketch` (`type:"button"`)
        // become `FieldKind::Button` fields carrying the schema label + their key.
        let fields = feature_form_fields("S");
        let edit = fields
            .iter()
            .find(|f| f.key() == "editSketch")
            .expect("editSketch button field");
        assert!(
            matches!(&edit.kind, FieldKind::Button { label } if label == "Edit Sketch"),
            "editSketch should be Button('Edit Sketch'), got {:?}",
            edit.kind
        );
        assert_eq!(edit.path, ["editSketch"], "button binds to its own key");
        // `dumpSketchDiagnostics` was a debug button whose hint promised a download
        // it never performed — it wrote to a JS global / stderr and showed the user
        // nothing. It is gone from the schema; the engine-side
        // `sketch_diagnostics_dump_json` it called stays as the developer API.
        assert!(
            fields.iter().all(|f| f.key() != "dumpSketchDiagnostics"),
            "the dead Dump Diagnostics button must not come back"
        );
    }

    #[test]
    fn acomp_form_fields_map_rigid_pose_and_is_fixed() {
        // The ACOMP schema's `transform` default is the RIGID POSE shape
        // `{translate, rotateEulerDeg}` — the form mapping must bind those two
        // nested paths (NOT the legacy position/rotationEuler/scale triple), and
        // its `isFixed` boolean must surface as a checkbox (dialog-visible per
        // the insert-flow contract).
        let fields = feature_form_fields("ACOMP");
        let translate = fields
            .iter()
            .find(|f| f.path == ["transform", "translate"])
            .expect("transform.translate vec3");
        assert!(matches!(translate.kind, FieldKind::Vec3 { .. }));
        let rotate = fields
            .iter()
            .find(|f| f.path == ["transform", "rotateEulerDeg"])
            .expect("transform.rotateEulerDeg vec3");
        assert!(matches!(rotate.kind, FieldKind::Vec3 { .. }));
        assert!(
            !fields.iter().any(|f| f.path == ["transform", "scale"]),
            "a rigid pose has no scale row"
        );
        let fixed = fields
            .iter()
            .find(|f| f.key() == "isFixed")
            .expect("isFixed checkbox");
        assert!(matches!(fixed.kind, FieldKind::Bool));
        assert_eq!(fixed.label, "Fixed", "schema label wins over the prettified key");
        // The legacy shape is untouched: a cube still maps the full triple.
        let cube = feature_form_fields("P.CU");
        assert!(cube.iter().any(|f| f.path == ["transform", "scale"]));
    }

    #[test]
    fn constraint_schemas_map_through_the_shared_field_engine() {
        // The nine assembly-constraint schemas share the feature-schema shape, so
        // `form_fields_from_schema` renders them with the SAME mapping: elements →
        // Reference (filter + multiplicity from the schema), numbers → Scalar,
        // booleans → Bool, id → read-only Text.
        let catalogue = brep_kernel::constraint_schema_catalogue();
        let distance = catalogue
            .as_array()
            .unwrap()
            .iter()
            .find(|s| s.get("type").and_then(Value::as_str) == Some("distance"))
            .expect("distance schema in the catalogue");
        let fields = form_fields_from_schema(distance);
        let elements = fields
            .iter()
            .find(|f| f.key() == "elements")
            .expect("elements reference field");
        match &elements.kind {
            FieldKind::Reference { filter, multiple } => {
                assert_eq!(filter, &["FACE".to_string(), "VERTEX".into(), "EDGE".into()]);
                assert!(multiple, "two-element constraints take a list");
            }
            other => panic!("elements should be a Reference, got {other:?}"),
        }
        assert!(matches!(
            fields.iter().find(|f| f.key() == "distance").unwrap().kind,
            FieldKind::Scalar { .. }
        ));
        assert!(matches!(
            fields.iter().find(|f| f.key() == "opposeNormals").unwrap().kind,
            FieldKind::Bool
        ));
        assert!(matches!(
            fields.iter().find(|f| f.key() == "id").unwrap().kind,
            FieldKind::Text { read_only: true }
        ));
    }

    #[test]
    fn reference_selection_field_is_a_self_titled_references_tagged_node() {
        // The history tree renders a `reference_selection` field as its OWN
        // top-level-under-the-feature node (no "References" wrapper): the node
        // title is the field's LABEL and it carries the Select button. This pins
        // the descriptor contract that the tree's inlining relies on — the field's
        // `label` is the prettified param name ("Sketch plane"), and its `group`
        // stays `"References"` as the semantic tag (tree inline marker + the
        // context bar's primary-reference discriminator).
        let sketch_plane = feature_form_fields("S")
            .into_iter()
            .find(|f| f.key() == "sketchPlane")
            .expect("sketch has a sketchPlane reference_selection field");
        assert_eq!(sketch_plane.label, "Sketch plane", "node title = field label");
        assert_eq!(sketch_plane.group, "References", "kept as a semantic tag");
        assert_eq!(sketch_plane.path, ["sketchPlane"], "a top-level (primary) reference");
        match &sketch_plane.kind {
            FieldKind::Reference { filter, multiple } => {
                assert_eq!(filter, &["PLANE".to_string(), "FACE".to_string()]);
                assert!(!multiple, "the sketch plane is a single reference");
            }
            other => panic!("sketchPlane should be a Reference, got {other:?}"),
        }
    }
}