graph-explorer-style 0.3.0

Scene model, animation and declarative styling for graph-explorer.
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
651
use serde::Deserialize;
use serde_json::Value;
use std::collections::HashMap;

pub type Attrs = HashMap<String, Value>;

pub mod anim;
pub mod interner;
pub mod scene;
pub use anim::*;
pub use interner::{Interner, LabelInterner, NodeIndex, LabelId, IdKind, EMPTY_LABEL};
pub use scene::*;

/// RGBA in 0..1. Deserializes from a hex string "#rrggbb" or "#rrggbbaa".
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Rgba(pub [f32; 4]);

impl Rgba {
    pub fn from_hex(s: &str) -> Result<Rgba, String> {
        let h = s.strip_prefix('#').ok_or_else(|| format!("missing #: {s}"))?;
        if !h.is_ascii() { return Err(format!("hex must be ASCII: {s}")); }
        let n = |i: usize| u8::from_str_radix(&h[i..i + 2], 16).map(|v| v as f32 / 255.0);
        let px = |i: usize| n(i).map_err(|e| format!("bad hex {s}: {e}"));
        match h.len() {
            6 => Ok(Rgba([px(0)?, px(2)?, px(4)?, 1.0])),
            8 => Ok(Rgba([px(0)?, px(2)?, px(4)?, px(6)?])),
            _ => Err(format!("hex must be 6 or 8 digits: {s}")),
        }
    }
}

impl<'de> Deserialize<'de> for Rgba {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        Rgba::from_hex(&s).map_err(serde::de::Error::custom)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Shape { #[default] Circle, Square, Diamond }

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NodeRole { Normal, Focus, Selected, History, Candidate, Provisional }
impl NodeRole {
    pub fn as_str(&self) -> &'static str {
        match self { NodeRole::Normal=>"normal", NodeRole::Focus=>"focus", NodeRole::Selected=>"selected", NodeRole::History=>"history", NodeRole::Candidate=>"candidate", NodeRole::Provisional=>"provisional" }
    }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EdgeRole { Normal, HistoryLink, CandidateLink, Provisional }
impl EdgeRole {
    pub fn as_str(&self) -> &'static str {
        match self { EdgeRole::Normal=>"normal", EdgeRole::HistoryLink=>"history", EdgeRole::CandidateLink=>"candidate", EdgeRole::Provisional=>"provisional" }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct NodeStyle { pub color: [f32;4], pub radius: f32, pub opacity: f32, pub shape: Shape, pub label_visible: bool, pub label_text: Option<String> }
#[derive(Debug, Clone, PartialEq)]
pub struct EdgeStyle { pub color: [f32;4], pub opacity: f32, pub width: f32, pub label_visible: bool, pub label_text: Option<String> }

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PartialNodeStyle {
    #[serde(default)] pub color: Option<Rgba>,
    #[serde(default)] pub radius: Option<f32>,
    #[serde(default)] pub opacity: Option<f32>,
    #[serde(default)] pub shape: Option<Shape>,
    #[serde(default)] pub label_visible: Option<bool>,
    #[serde(default)] pub label_text: Option<String>,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PartialEdgeStyle {
    #[serde(default)] pub color: Option<Rgba>,
    #[serde(default)] pub opacity: Option<f32>,
    #[serde(default)] pub width: Option<f32>,
    #[serde(default)] pub label_visible: Option<bool>,
    /// Overrides whatever `edge_base.label_attr` supplied for this edge —
    /// prettify a raw relationship type, or name an edge the data does not.
    #[serde(default)] pub label_text: Option<String>,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Selector {
    #[serde(default)] pub role: Option<String>,
    #[serde(default)] pub attr: Option<String>,
    #[serde(default)] pub equals: Option<Value>,
    #[serde(default)] pub one_of: Option<Vec<Value>>,
}

#[derive(Debug, Clone, Copy, PartialEq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ScalableNodeProp { Radius, Opacity }
#[derive(Debug, Clone, Copy, PartialEq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ScalableEdgeProp { Width, Opacity }

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NodeScale { pub by: String, pub property: ScalableNodeProp, pub domain: [f32;2], pub range: [f32;2] }
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EdgeScale { pub by: String, pub property: ScalableEdgeProp, pub domain: [f32;2], pub range: [f32;2] }

/// A rule is a `when` gate plus a `set` (categorical override) and/or a `scale`.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NodeRule { #[serde(default)] pub when: Option<Selector>, #[serde(default)] pub set: Option<PartialNodeStyle>, #[serde(default)] pub scale: Option<NodeScale> }
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EdgeRule { #[serde(default)] pub when: Option<Selector>, #[serde(default)] pub set: Option<PartialEdgeStyle>, #[serde(default)] pub scale: Option<EdgeScale> }

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StyleSpec {
    pub node_base: NodeBaseSpec,
    #[serde(default)] pub node_rules: Vec<NodeRule>,
    pub edge_base: EdgeBaseSpec,
    #[serde(default)] pub edge_rules: Vec<EdgeRule>,
    #[serde(default)] pub labels: LabelLodSpec,
}

/// Label level-of-detail. Both knobs are host-tunable via `set_style`.
#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct LabelLodSpec {
    /// Zoom gate: a label is a candidate only when its node's on-screen
    /// radius (world radius × zoom) is at least this many pixels.
    pub min_screen_radius_px: f32,
    /// Importance cap: at most this many labels per frame; survivors are the
    /// top-N by importance = degree, with the current node and its neighbors
    /// boosted so the user's context never loses its labels.
    pub max_labels: usize,
    /// Zoom gate for EDGE labels: an edge shorter than this on screen has no
    /// room to print a relationship name along it.
    pub edge_min_screen_length_px: f32,
    /// Importance cap for edge labels, counted separately from `max_labels`
    /// so turning edge labels on cannot silently evict node labels.
    pub max_edge_labels: usize,
}
impl Default for LabelLodSpec {
    fn default() -> Self {
        Self {
            min_screen_radius_px: 8.0,
            max_labels: 200,
            edge_min_screen_length_px: 60.0,
            max_edge_labels: 100,
        }
    }
}

// Base specs deserialize from JSON with defaults, then convert into the resolved *Style.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NodeBaseSpec { pub color: Rgba, pub radius: f32, #[serde(default = "one")] pub opacity: f32, #[serde(default)] pub shape: Shape, #[serde(default = "yes")] pub label_visible: bool }
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EdgeBaseSpec {
    pub color: Rgba,
    #[serde(default = "one")] pub opacity: f32,
    pub width: f32,
    /// Name an edge attr to draw as the edge's label — `"rel"`, `"type"`,
    /// whatever the dataset uses. Unset (the default) means edges carry no
    /// labels at all, so adding this field changes nothing for a spec that
    /// does not ask for it.
    ///
    /// An attr reference rather than a literal because relationship types are
    /// generally not known when the spec is written: a graph read from a
    /// database has whatever types the database has. Per-rule `label_text`
    /// overrides this for the types a host *does* want to name.
    #[serde(default)] pub label_attr: Option<String>,
    #[serde(default = "yes")] pub label_visible: bool,
}
fn one() -> f32 { 1.0 }
fn yes() -> bool { true }

/// Render an attr value as label text, or `None` if it is not a scalar.
///
/// Strings render bare (no JSON quotes); numbers and booleans render as
/// written. Arrays, objects and null render nothing — there is no sensible
/// one-line form, and `"[object Object]"` on an edge is worse than no label.
/// This is the same scalar/non-scalar line `graph-explorer-proxy` already
/// draws when deciding what survives into `attrs`.
fn scalar_text(v: &Value) -> Option<String> {
    match v {
        Value::String(s) => Some(s.clone()),
        Value::Number(n) => Some(n.to_string()),
        Value::Bool(b) => Some(b.to_string()),
        _ => None,
    }
}

impl Selector {
    fn matches(&self, attrs: &Attrs, role_str: &str) -> bool {
        if let Some(r) = &self.role { if r != role_str { return false; } }
        if let Some(a) = &self.attr {
            let v = attrs.get(a);
            if let Some(eq) = &self.equals { if v != Some(eq) { return false; } }
            if let Some(list) = &self.one_of { if !v.is_some_and(|v| list.contains(v)) { return false; } }
            if self.equals.is_none() && self.one_of.is_none() && v.is_none() { return false; }
        }
        true
    }
}

fn lerp_clamp(x: f32, d: [f32;2], r: [f32;2]) -> f32 {
    let span = d[1] - d[0];
    if span == 0.0 { return r[0]; }
    let t = ((x - d[0]) / span).clamp(0.0, 1.0);
    r[0] + t * (r[1] - r[0])
}

impl StyleSpec {
    pub fn node(&self, attrs: &Attrs, role: NodeRole) -> NodeStyle {
        let b = &self.node_base;
        let mut s = NodeStyle { color: b.color.0, radius: b.radius, opacity: b.opacity, shape: b.shape, label_visible: b.label_visible, label_text: None };
        let role_str = role.as_str();
        for rule in &self.node_rules {
            if let Some(sel) = &rule.when { if !sel.matches(attrs, role_str) { continue; } }
            if let Some(set) = &rule.set {
                if let Some(c) = &set.color { s.color = c.0; }
                if let Some(v) = set.radius { s.radius = v; }
                if let Some(v) = set.opacity { s.opacity = v; }
                if let Some(v) = set.shape { s.shape = v; }
                if let Some(v) = set.label_visible { s.label_visible = v; }
                if let Some(v) = &set.label_text { s.label_text = Some(v.clone()); }
            }
            if let Some(sc) = &rule.scale {
                if let Some(x) = attrs.get(&sc.by).and_then(|v| v.as_f64()) {
                    let mapped = lerp_clamp(x as f32, sc.domain, sc.range);
                    match sc.property { ScalableNodeProp::Radius => s.radius = mapped, ScalableNodeProp::Opacity => s.opacity = mapped }
                }
            }
        }
        s
    }

    pub fn edge(&self, attrs: &Attrs, role: EdgeRole) -> EdgeStyle {
        let b = &self.edge_base;
        // The attr-derived default is resolved BEFORE the rule loop, so a
        // rule's `label_text` overrides it by the same last-write-wins path
        // every other property uses.
        let mut s = EdgeStyle {
            color: b.color.0,
            opacity: b.opacity,
            width: b.width,
            label_visible: b.label_visible,
            label_text: b.label_attr.as_ref().and_then(|k| attrs.get(k)).and_then(scalar_text),
        };
        let role_str = role.as_str();
        for rule in &self.edge_rules {
            if let Some(sel) = &rule.when { if !sel.matches(attrs, role_str) { continue; } }
            if let Some(set) = &rule.set {
                if let Some(c) = &set.color { s.color = c.0; }
                if let Some(v) = set.opacity { s.opacity = v; }
                if let Some(v) = set.width { s.width = v; }
                if let Some(v) = set.label_visible { s.label_visible = v; }
                if let Some(v) = &set.label_text { s.label_text = Some(v.clone()); }
            }
            if let Some(sc) = &rule.scale {
                if let Some(x) = attrs.get(&sc.by).and_then(|v| v.as_f64()) {
                    let mapped = lerp_clamp(x as f32, sc.domain, sc.range);
                    match sc.property { ScalableEdgeProp::Width => s.width = mapped, ScalableEdgeProp::Opacity => s.opacity = mapped }
                }
            }
        }
        s
    }

    /// The active label level-of-detail config (host-tunable via `set_style`).
    pub fn label_lod(&self) -> LabelLodSpec { self.labels }

    /// Whether any edge could carry a label. Lets the scene builder skip the
    /// whole edge-label path — including interning — for the overwhelmingly
    /// common case of a spec that never asked for edge labels.
    pub fn edge_labels_possible(&self) -> bool {
        self.edge_base.label_attr.is_some()
            || self.edge_rules.iter().any(|r| r.set.as_ref().is_some_and(|s| s.label_text.is_some()))
    }
}

impl Default for StyleSpec {
    fn default() -> Self {
        let json = r##"{
          "node_base": { "color": "#1f70eb", "radius": 14, "opacity": 1, "shape": "circle", "label_visible": true },
          "node_rules": [
            { "when": { "role": "focus" },    "set": { "color": "#e3b341", "radius": 20 } },
            { "when": { "role": "selected" }, "set": { "color": "#3399ff", "radius": 18 } },
            { "when": { "role": "history" },  "set": { "color": "#59667a", "radius": 12 } },
            { "when": { "role": "provisional" }, "set": { "color": "#5a6d8c", "radius": 11, "opacity": 0.45 } }
          ],
          "edge_base": { "color": "#3a4252", "opacity": 1, "width": 1.5 },
          "edge_rules": [
            { "when": { "role": "provisional" }, "set": { "color": "#2b3444", "opacity": 0.35, "width": 1.0 } }
          ]
        }"##;
        serde_json::from_str(json).expect("built-in default spec must parse")
    }
}

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

    #[test]
    fn rgba_parses_hex() {
        assert_eq!(Rgba::from_hex("#1f6feb").unwrap().0, [0.12156863, 0.43529412, 0.92156863, 1.0]);
        assert_eq!(Rgba::from_hex("#00000080").unwrap().0[3], 128.0 / 255.0);
        assert!(Rgba::from_hex("nope").is_err());
    }

    #[test]
    fn stylespec_deserializes_from_json() {
        let json = r##"{
          "node_base": { "color": "#1f6feb", "radius": 14, "opacity": 1, "shape": "circle", "label_visible": true },
          "node_rules": [
            { "when": { "role": "focus" }, "set": { "color": "#e3b341", "radius": 20 } },
            { "scale": { "by": "degree", "property": "radius", "domain": [1, 10], "range": [8, 24] } }
          ],
          "edge_base": { "color": "#3a4252", "opacity": 1, "width": 1.5 },
          "edge_rules": []
        }"##;
        let spec: StyleSpec = serde_json::from_str(json).unwrap();
        assert_eq!(spec.node_rules.len(), 2);
        assert_eq!(spec.node_base.radius, 14.0);
    }

    fn spec_json(rules: &str) -> StyleSpec {
        let json = format!(r##"{{
          "node_base": {{ "color": "#1f6feb", "radius": 14 }},
          "node_rules": [{rules}],
          "edge_base": {{ "color": "#3a4252", "width": 1.5 }},
          "edge_rules": []
        }}"##);
        serde_json::from_str(&json).unwrap()
    }

    /// Build a spec whose edges carry `edge_base` fields `base` and rules `rules`.
    fn edge_spec(base: &str, rules: &str) -> StyleSpec {
        let json = format!(r##"{{
          "node_base": {{ "color": "#1f6feb", "radius": 14 }},
          "node_rules": [],
          "edge_base": {{ "color": "#3a4252", "width": 1.5 {base} }},
          "edge_rules": [{rules}]
        }}"##);
        serde_json::from_str(&json).unwrap()
    }

    fn edge_attrs(pairs: &[(&str, serde_json::Value)]) -> Attrs {
        pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()
    }

    #[test]
    fn label_attr_supplies_edge_label_text() {
        let spec = edge_spec(r##", "label_attr": "rel""##, "");
        let a = edge_attrs(&[("rel", serde_json::json!("written_by"))]);
        assert_eq!(spec.edge(&a, EdgeRole::Normal).label_text.as_deref(), Some("written_by"));
    }

    #[test]
    fn a_rule_label_text_overrides_the_attr_derived_default() {
        let spec = edge_spec(
            r##", "label_attr": "rel""##,
            r##"{ "when": { "attr": "rel", "equals": "written_by" }, "set": { "label_text": "written by" } }"##,
        );
        let a = edge_attrs(&[("rel", serde_json::json!("written_by"))]);
        assert_eq!(spec.edge(&a, EdgeRole::Normal).label_text.as_deref(), Some("written by"));
        // A type with no rule keeps the raw attr value.
        let b = edge_attrs(&[("rel", serde_json::json!("features"))]);
        assert_eq!(spec.edge(&b, EdgeRole::Normal).label_text.as_deref(), Some("features"));
    }

    #[test]
    fn label_visible_false_suppresses_a_label_the_attr_would_supply() {
        let spec = edge_spec(
            r##", "label_attr": "rel""##,
            r##"{ "when": { "attr": "rel", "equals": "in_genre" }, "set": { "label_visible": false } }"##,
        );
        let a = edge_attrs(&[("rel", serde_json::json!("in_genre"))]);
        let s = spec.edge(&a, EdgeRole::Normal);
        assert!(!s.label_visible);
        // The text is still resolved; visibility is the renderer's gate. What
        // matters is that the two are independent.
        assert_eq!(s.label_text.as_deref(), Some("in_genre"));
    }

    #[test]
    fn an_edge_missing_the_named_attr_gets_no_label() {
        let spec = edge_spec(r##", "label_attr": "rel""##, "");
        let a = edge_attrs(&[("weight", serde_json::json!(3))]);
        assert_eq!(spec.edge(&a, EdgeRole::Normal).label_text, None);
    }

    /// Non-scalars have no sensible one-line form. Rendering `[object Object]`
    /// on an edge is worse than rendering nothing.
    #[test]
    fn non_scalar_attr_values_produce_no_label() {
        for v in [serde_json::json!([1, 2]), serde_json::json!({"a": 1}), serde_json::json!(null)] {
            let spec = edge_spec(r##", "label_attr": "rel""##, "");
            let a = edge_attrs(&[("rel", v.clone())]);
            assert_eq!(spec.edge(&a, EdgeRole::Normal).label_text, None, "for {v}");
        }
    }

    #[test]
    fn numbers_and_bools_render_as_written() {
        let spec = edge_spec(r##", "label_attr": "w""##, "");
        assert_eq!(
            spec.edge(&edge_attrs(&[("w", serde_json::json!(42))]), EdgeRole::Normal).label_text.as_deref(),
            Some("42"),
        );
        assert_eq!(
            spec.edge(&edge_attrs(&[("w", serde_json::json!(true))]), EdgeRole::Normal).label_text.as_deref(),
            Some("true"),
        );
        // A string renders bare, without the quotes `Value::to_string` adds.
        assert_eq!(
            spec.edge(&edge_attrs(&[("w", serde_json::json!("hi"))]), EdgeRole::Normal).label_text.as_deref(),
            Some("hi"),
        );
    }

    /// The no-behaviour-change guarantee: a spec that never mentions edge
    /// labels gets none, and the scene builder can skip the path entirely.
    #[test]
    fn edge_labels_are_off_unless_the_spec_asks_for_them() {
        let spec = edge_spec("", "");
        let a = edge_attrs(&[("rel", serde_json::json!("written_by"))]);
        assert_eq!(spec.edge(&a, EdgeRole::Normal).label_text, None);
        assert!(!spec.edge_labels_possible());

        assert!(edge_spec(r##", "label_attr": "rel""##, "").edge_labels_possible());
        assert!(edge_spec("", r##"{ "set": { "label_text": "x" } }"##).edge_labels_possible());
        assert!(!StyleSpec::default().edge_labels_possible(), "the built-in spec must stay label-free");
    }

    #[test]
    fn categorical_rule_matches_role_and_attr() {
        let spec = spec_json(r##"
          { "when": { "role": "focus" }, "set": { "color": "#e3b341", "radius": 20 } },
          { "when": { "attr": "group", "equals": "input" }, "set": { "shape": "square" } }
        "##);
        let mut attrs = Attrs::new();
        attrs.insert("group".into(), serde_json::json!("input"));
        // focus role -> gold+20, and group=input -> square
        let s = spec.node(&attrs, NodeRole::Focus);
        assert_eq!(s.color, [0.8901961, 0.7019608, 0.25490198, 1.0]);
        assert_eq!(s.radius, 20.0);
        assert_eq!(s.shape, Shape::Square);
        // normal role, no group -> base blue/14/circle
        let base = spec.node(&Attrs::new(), NodeRole::Normal);
        assert_eq!(base.radius, 14.0);
        assert_eq!(base.shape, Shape::Circle);
    }

    #[test]
    fn scale_rule_maps_and_clamps() {
        let spec = spec_json(r##"{ "scale": { "by": "deg", "property": "radius", "domain": [1, 10], "range": [8, 24] } }"##);
        let at = |v: f64| { let mut a = Attrs::new(); a.insert("deg".into(), serde_json::json!(v)); a };
        assert_eq!(spec.node(&at(1.0), NodeRole::Normal).radius, 8.0);
        assert_eq!(spec.node(&at(10.0), NodeRole::Normal).radius, 24.0);
        assert_eq!(spec.node(&at(5.5), NodeRole::Normal).radius, 16.0); // midpoint
        assert_eq!(spec.node(&at(100.0), NodeRole::Normal).radius, 24.0); // clamped high
        assert_eq!(spec.node(&at(-5.0), NodeRole::Normal).radius, 8.0);   // clamped low
    }

    #[test]
    fn later_rules_win() {
        let spec = spec_json(r##"
          { "set": { "color": "#111111" } },
          { "set": { "color": "#222222" } }
        "##);
        assert_eq!(spec.node(&Attrs::new(), NodeRole::Normal).color, Rgba::from_hex("#222222").unwrap().0);
    }

    fn approx(a: [f32;4], b: [f32;4]) -> bool { a.iter().zip(b).all(|(x,y)| (x-y).abs() < 0.02) }

    #[test]
    fn default_spec_matches_current_look() {
        let spec = StyleSpec::default();
        let normal = spec.node(&Attrs::new(), NodeRole::Normal);
        assert!(approx(normal.color, [0.12, 0.44, 0.92, 1.0]));
        assert_eq!(normal.radius, 14.0);
        assert_eq!(normal.shape, Shape::Circle);
        let focus = spec.node(&Attrs::new(), NodeRole::Focus);
        assert!(approx(focus.color, [0.89, 0.70, 0.25, 1.0]));
        assert_eq!(focus.radius, 20.0);
        let hist = spec.node(&Attrs::new(), NodeRole::History);
        assert_eq!(hist.radius, 12.0);
        let e = spec.edge(&Attrs::new(), EdgeRole::Normal);
        assert_eq!(e.width, 1.5);
    }

    #[test]
    fn from_hex_rejects_non_ascii_without_panicking() {
        assert!(Rgba::from_hex("#1f6f€b").is_err());
    }

    #[test]
    fn scale_with_degenerate_domain_is_finite() {
        let spec: StyleSpec = serde_json::from_str(r##"{
          "node_base": { "color": "#1f6feb", "radius": 14 },
          "node_rules": [ { "scale": { "by": "d", "property": "radius", "domain": [5,5], "range": [10,20] } } ],
          "edge_base": { "color": "#3a4252", "width": 1.5 }, "edge_rules": []
        }"##).unwrap();
        let mut a = Attrs::new(); a.insert("d".into(), serde_json::json!(5.0));
        let r = spec.node(&a, NodeRole::Normal).radius;
        assert!(r.is_finite());
        assert_eq!(r, 10.0);
    }

    #[test]
    fn unknown_selector_key_is_rejected() {
        let bad = r##"{
          "node_base": { "color": "#1f6feb", "radius": 14 },
          "node_rules": [ { "when": { "attrs": "group" }, "set": { "shape": "square" } } ],
          "edge_base": { "color": "#3a4252", "width": 1.5 }, "edge_rules": []
        }"##;
        assert!(serde_json::from_str::<StyleSpec>(bad).is_err());
    }

    #[test]
    fn provisional_roles_stringify_for_selectors() {
        assert_eq!(NodeRole::Provisional.as_str(), "provisional");
        assert_eq!(EdgeRole::Provisional.as_str(), "provisional");
    }

    #[test]
    fn default_spec_ghosts_provisional_nodes_and_edges() {
        let spec = StyleSpec::default();
        let n = spec.node(&Attrs::new(), NodeRole::Provisional);
        assert_eq!(n.color, Rgba::from_hex("#5a6d8c").unwrap().0);
        assert_eq!(n.radius, 11.0);
        assert_eq!(n.opacity, 0.45);

        let e = spec.edge(&Attrs::new(), EdgeRole::Provisional);
        assert_eq!(e.color, Rgba::from_hex("#2b3444").unwrap().0);
        assert_eq!(e.opacity, 0.35);
        assert_eq!(e.width, 1.0);
    }

    #[test]
    fn provisional_ghosting_stays_clickable() {
        // graph-explorer-render's hit test ignores targets below 0.05 opacity, and
        // clicking a ghost is how you walk into it.
        let spec = StyleSpec::default();
        // keep in sync with graph-explorer-render's MIN_HITTABLE_OPACITY
        assert!(spec.node(&Attrs::new(), NodeRole::Provisional).opacity > 0.05);
    }

    #[test]
    fn a_host_rule_overrides_the_built_in_provisional_rule_selectively() {
        // Layering on the SHIPPED default, not a hand-copied spec: this fails if
        // anyone removes or reorders the built-in provisional rule, which a
        // freshly-constructed spec would not notice.
        let mut spec = StyleSpec::default();
        spec.node_rules.push(serde_json::from_str(
            r##"{ "when": { "role": "provisional" }, "set": { "color": "#ff00aa" } }"##).unwrap());
        let n = spec.node(&Attrs::new(), NodeRole::Provisional);
        assert_eq!(n.color, Rgba::from_hex("#ff00aa").unwrap().0);
        assert_eq!(n.radius, 11.0, "the built-in radius survives a colour-only override");
        assert_eq!(n.opacity, 0.45);
    }

    #[test]
    fn a_host_edge_rule_overrides_the_built_in_provisional_edge_rule_selectively() {
        // Edge side of the same guarantee: layering on the shipped default,
        // not a hand-copied spec.
        let mut spec = StyleSpec::default();
        spec.edge_rules.push(serde_json::from_str(
            r##"{ "when": { "role": "provisional" }, "set": { "width": 4.0 } }"##).unwrap());
        let e = spec.edge(&Attrs::new(), EdgeRole::Provisional);
        assert_eq!(e.width, 4.0);
        assert_eq!(e.opacity, 0.35, "the built-in opacity survives a width-only override");
    }

    #[test]
    fn a_replacement_spec_without_provisional_rules_falls_back_to_base() {
        // Wholesale replacement drops the built-in ghosting, same as it already
        // does for focus/history. It must not error.
        let json = r##"{
          "node_base": { "color": "#1f70eb", "radius": 14 },
          "edge_base": { "color": "#3a4252", "width": 1.5 }
        }"##;
        let spec: StyleSpec = serde_json::from_str(json).unwrap();
        let n = spec.node(&Attrs::new(), NodeRole::Provisional);
        assert_eq!(n.color, Rgba::from_hex("#1f70eb").unwrap().0);
        assert_eq!(n.opacity, 1.0);
    }

    #[test]
    fn provisional_composes_with_an_attribute_selector() {
        // Layering on the shipped default, not a hand-copied spec, so this
        // fails if the built-in provisional rule is removed or reordered.
        let mut spec = StyleSpec::default();
        spec.node_rules.push(serde_json::from_str(
            r##"{ "when": { "role": "provisional", "attr": "kind", "equals": "Person" },
                  "set": { "color": "#ff00aa" } }"##).unwrap());
        let mut person = Attrs::new();
        person.insert("kind".into(), serde_json::json!("Person"));

        let p = spec.node(&person, NodeRole::Provisional);
        assert_eq!(p.color, Rgba::from_hex("#ff00aa").unwrap().0, "matching attr overrides the ghost colour");
        assert_eq!(p.opacity, 0.45, "the built-in opacity survives a colour-only override");

        // Non-Person ghost keeps the built-in ghost colour, not the base blue.
        assert_eq!(spec.node(&Attrs::new(), NodeRole::Provisional).color, Rgba::from_hex("#5a6d8c").unwrap().0);

        // A Person that isn't provisional is unaffected.
        assert_eq!(spec.node(&person, NodeRole::Normal).color, Rgba::from_hex("#1f70eb").unwrap().0);
    }

    #[test]
    fn label_lod_defaults_and_parses() {
        let s: StyleSpec = serde_json::from_str(
            r##"{ "node_base": {"color":"#ffffff","radius":8}, "edge_base": {"color":"#888888","width":1} }"##).unwrap();
        assert_eq!(s.labels.min_screen_radius_px, 8.0);
        assert_eq!(s.labels.max_labels, 200);
        let s: StyleSpec = serde_json::from_str(
            r##"{ "node_base": {"color":"#ffffff","radius":8}, "edge_base": {"color":"#888888","width":1},
                 "labels": { "max_labels": 50 } }"##).unwrap();
        assert_eq!(s.labels.max_labels, 50);
        assert_eq!(s.labels.min_screen_radius_px, 8.0, "partial keeps other defaults");
    }

    #[test]
    fn edge_label_lod_defaults_and_parses() {
        let s: StyleSpec = serde_json::from_str(
            r##"{ "node_base": {"color":"#ffffff","radius":8}, "edge_base": {"color":"#888888","width":1} }"##).unwrap();
        assert_eq!(s.labels.edge_min_screen_length_px, 60.0);
        assert_eq!(s.labels.max_edge_labels, 100);
        let s: StyleSpec = serde_json::from_str(
            r##"{ "node_base": {"color":"#ffffff","radius":8}, "edge_base": {"color":"#888888","width":1},
                 "labels": { "edge_min_screen_length_px": 20, "max_edge_labels": 5 } }"##).unwrap();
        assert_eq!(s.labels.edge_min_screen_length_px, 20.0);
        assert_eq!(s.labels.max_edge_labels, 5);
        // The edge caps are counted separately, so setting them must not
        // disturb the node caps.
        assert_eq!(s.labels.max_labels, 200);
    }

    #[test]
    fn label_lod_rejects_unknown_fields() {
        assert!(serde_json::from_str::<StyleSpec>(
            r##"{ "node_base": {"color":"#ffffff","radius":8}, "edge_base": {"color":"#888888","width":1},
                 "labels": { "wobble": 1 } }"##).is_err());
    }
}