darkly 0.5.0

A GPU-native paint engine on wgpu: brushes, layers, blend modes, masks, selections, and undo.
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
use std::collections::{HashMap, HashSet};

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

use super::registration::NodeRegistration;
use super::WireKind;
use crate::gpu::params::ParamValue;

// ── Identifiers ──────────────────────────────────────────────────────

/// Stable node identity inside a graph.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct NodeId(pub u64);

/// Reference to a specific port on a specific node.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct PortRef {
    pub node: NodeId,
    pub port: String,
}

/// A directed wire between two ports.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Connection {
    pub from: PortRef,
    pub to: PortRef,
}

// ── Port definitions ─────────────────────────────────────────────────

/// Direction of data flow through a port.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum PortDir {
    Input,
    Output,
}

/// Display unit for numeric ports.
///
/// Defines how a port's internal value is converted for display in the UI.
/// The conversion methods use `f32` math — any numeric wire type (Scalar,
/// Int) can round-trip through them.  Non-numeric types (Bool, Color)
/// ignore this field.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum UnitType {
    /// Identity — display and internal are both raw values (shown as `0.50`).
    #[default]
    Normalized,
    /// Display as percentage: `display = value × 100`, suffix `%`.
    Percent,
    /// Wire unit is radians; display in degrees. `display = value × 180/π`, suffix `°`.
    Degrees,
    /// Identity with no suffix — useful for dimensionless multipliers.
    Raw,
    /// Identity with `px` suffix — value is in canvas pixels.
    Pixels,
}

impl UnitType {
    /// Convert from port-space to display-space.
    pub fn to_display(self, value: f32) -> f32 {
        match self {
            Self::Normalized | Self::Raw | Self::Pixels => value,
            Self::Percent => value * 100.0,
            Self::Degrees => value * (180.0 / std::f32::consts::PI),
        }
    }

    /// Convert from display-space back to port-space.
    pub fn from_display(self, display: f32) -> f32 {
        match self {
            Self::Normalized | Self::Raw | Self::Pixels => display,
            Self::Percent => display / 100.0,
            Self::Degrees => display * (std::f32::consts::PI / 180.0),
        }
    }

    /// Suffix string for display formatting.
    pub fn suffix(self) -> &'static str {
        match self {
            Self::Normalized => "",
            Self::Percent => "%",
            Self::Degrees => "°",
            Self::Raw => "",
            Self::Pixels => "px",
        }
    }
}

/// Schema for a single port on a node type.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(bound = "")]
pub struct PortDef<W: WireKind> {
    pub name: String,
    pub dir: PortDir,
    pub wire_type: W,
    /// Slider min when the port is disconnected (UI metadata only).
    pub min: f32,
    /// Slider max when the port is disconnected (UI metadata only).
    pub max: f32,
    /// Default value when the port is disconnected.
    pub default: f32,
    /// Quantization step. `0.0` (the default) means continuous; any positive
    /// value snaps the slider, scrub, and typed-value commits to multiples of
    /// `step` from `min`. Used when the wire takes a value but only certain
    /// quantized values produce well-defined behavior — e.g. the shape
    /// node's `frequency`, where only integer values yield a seam-free
    /// closed silhouette. Frontend honors the snap; the engine should still
    /// defend by quantizing inputs in the node evaluator (a wired-in float
    /// from a curve or pen-pressure modulator bypasses the slider).
    #[serde(default)]
    pub step: f32,
    /// Human-readable description shown as a tooltip in the node editor.
    #[serde(default)]
    pub description: String,
    /// Display unit for numeric ports (controls UI conversion and suffix).
    #[serde(default)]
    pub unit_type: UnitType,
    /// Iconify icon name (e.g. `"fa6-solid:circle"`), or empty.
    #[serde(default)]
    pub icon: String,
    /// User-facing display label.  Falls back to `name` if empty.
    #[serde(default)]
    pub label: String,
    /// Whether this port is exposed in the brush properties panel.
    #[serde(default)]
    pub exposed: bool,
    /// Value substituted for this port in every "brush identity"
    /// render: the cursor-following dab overlay, the editor stroke
    /// preview, and the library thumbnail bake. The brush WGSL
    /// compiler clones the graph, drops incoming wires on flagged
    /// ports, and replaces `default` with this constant — so all
    /// previews read as a showcase of the brush regardless of the
    /// user's working scrub. Real strokes still honour the
    /// configured value.
    ///
    /// Use when the port is something the user actively scrubs but
    /// the preview must stay at a canonical value (otherwise the
    /// preview becomes a moving target as the user dials in their
    /// brush). The picker dab tile uses a more aggressive
    /// neutralizer (`reset_exposed_scrubs`) that targets every
    /// exposed scrub regardless of `preview_value`.
    ///
    /// Canonical example: `paint.size` (0.1, so a huge brush's
    /// preview still fits the small cursor mask and the editor
    /// preview doesn't redraw on every size scrub).
    #[serde(default)]
    pub preview_value: Option<f32>,
    /// Declares that scrubbing this port's value does **not** change
    /// what the synthetic-stroke editor preview produces, so the
    /// preview cache and version counter should not bump on its scrub.
    ///
    /// Used by ports whose value the preview *pipeline* (not the
    /// shader) ignores. Canonical example: `pen_input.stabilize` —
    /// the editor preview's stroke engine is hard-wired to use
    /// `PassThrough` as the stabilizer (the path is pre-cooked), so
    /// the live `stabilize` value never reaches it. Marking this
    /// declaratively avoids re-rendering a full stroke every ~100 ms
    /// while the user drags the slider for no visible effect.
    ///
    /// Distinct from [`PortDef::preview_value`]: that one substitutes
    /// values into the *cursor overlay shader*; this one skips a
    /// version bump on the *editor stroke preview*. A port can carry
    /// either, both, or neither.
    #[serde(default)]
    pub preview_irrelevant_scrub: bool,
    /// Conditional visibility: the port is only shown in the UI when the
    /// value of the named param is one of the listed integer values. The
    /// param is referenced by its registration name (e.g. `"algorithm"`)
    /// and is expected to be an `Int`/`Enum` param — those are the only
    /// types where dispatch on a discrete value makes sense.
    ///
    /// When `None` (the default), the port is always visible. When set,
    /// the frontend hides the port row whenever the named param's current
    /// value is outside the allowed list. This is purely a UI affordance —
    /// the engine still accepts and reads the port's value normally; it
    /// just stops showing the user a control they wouldn't act on.
    /// Used by the Shape node to hide algorithm-specific knobs (Perlin's
    /// `seed`, Superformula's `n1`/`n2`/`n3`) under the wrong algorithm.
    #[serde(default)]
    pub visible_when: Option<(String, Vec<i32>)>,
    /// Wire-side natural value range. When a connection's source and dest
    /// ports both declare this, the runner remaps the scalar value at
    /// slot-read time from source range to dest range (affine transform).
    /// When either side is `None`, the value passes through raw.
    ///
    /// Distinct from `min`/`max`, which are slider/UI hints — `with_range`
    /// stays "UI hint only, not enforced", and `with_natural_range` is the
    /// separate, explicit opt-in for wire-boundary range mapping. Most
    /// ports declare both with the same numbers; the two diverge for
    /// over-drag sliders like `paint.size`, where the slider range is
    /// a hint but the wire-side semantics are passthrough.
    #[serde(default)]
    pub natural_range: Option<(f32, f32)>,
    /// Mark this exposed port as part of the brush's *identity* so its
    /// user-set value persists into the dab thumbnail render.
    ///
    /// By default `crate::brush::reset_exposed_scrubs` resets every
    /// exposed input back to its registration default before rendering
    /// the dab thumbnail — the icon represents brush shape/texture, not
    /// the user's working size/opacity/flow knobs. That policy is wrong
    /// for orientation knobs (rotation): a calligraphy nib at
    /// 45° *is* a different-looking brush, and the icon should reflect
    /// that.
    ///
    /// When this flag is set: (1) the reset skips this port, and (2)
    /// scrubbing this port bumps the topology version so the dab
    /// thumbnail re-renders, not just the editor preview.
    #[serde(default)]
    pub persist_in_thumbnail: bool,
}

impl<W: WireKind> PortDef<W> {
    pub fn input(name: impl Into<String>, wire_type: W) -> Self {
        Self {
            name: name.into(),
            dir: PortDir::Input,
            wire_type,
            min: 0.0,
            max: 1.0,
            default: 0.0,
            description: String::new(),
            unit_type: UnitType::default(),
            icon: String::new(),
            label: String::new(),
            exposed: false,
            preview_value: None,
            preview_irrelevant_scrub: false,
            visible_when: None,
            step: 0.0,
            natural_range: None,
            persist_in_thumbnail: false,
        }
    }

    pub fn output(name: impl Into<String>, wire_type: W) -> Self {
        Self {
            name: name.into(),
            dir: PortDir::Output,
            wire_type,
            min: 0.0,
            max: 1.0,
            default: 0.0,
            description: String::new(),
            unit_type: UnitType::default(),
            icon: String::new(),
            label: String::new(),
            exposed: false,
            preview_value: None,
            preview_irrelevant_scrub: false,
            visible_when: None,
            step: 0.0,
            natural_range: None,
            persist_in_thumbnail: false,
        }
    }

    /// Declare the slider/preset range and default value for this port.
    ///
    /// `(min, max)` is a **UI hint** — bounds for slider widgets and preset
    /// editors.  It is **not enforced at evaluation**: `EvalContext::input_f32`
    /// returns whatever value flowed through the wire (including out-of-range
    /// values from upstream sensors, math nodes, or hand-edited graph data).
    /// Consumers that require a hard bound must clamp explicitly inside
    /// their own `evaluate_gpu` (see e.g. `liquify::evaluate_gpu`'s
    /// `.clamp(0.0, 4.0)`).  A blanket "enforce all declared ranges" would
    /// constrain ports that intentionally accept slider over-drag (notably
    /// `stamp.size`, whose 100% mark is at `1.0` but whose slider extends
    /// further to support dramatically over-sized stamps).
    ///
    /// Separate from [`PortDef::with_natural_range`], which declares the
    /// **wire-side** value semantics used for cross-range remap when two
    /// connected ports speak different ranges. Most ports declare both
    /// with the same numbers; the two diverge for over-drag sliders.
    pub fn with_range(mut self, min: f32, max: f32, default: f32) -> Self {
        self.min = min;
        self.max = max;
        self.default = default;
        self
    }

    /// Declare this port's wire-side natural value range. When a connection's
    /// source and dest ports **both** declare a natural range, the runner
    /// remaps the scalar value at slot-read time (affine transform from
    /// source range to dest range). When either side is `None`, the wire
    /// passes the value through raw — preserving math-node passthrough and
    /// over-drag-slider passthrough (e.g. `stamp.size`).
    ///
    /// Independent of [`PortDef::with_range`], which is a UI/slider hint
    /// only. A port can have a slider range without a natural range (the
    /// over-drag case) or a natural range without a slider (most outputs).
    pub fn with_natural_range(mut self, min: f32, max: f32) -> Self {
        self.natural_range = Some((min, max));
        self
    }

    /// Quantize the port's slider to multiples of `step` from `min`. Pass
    /// `1.0` for an integer-valued port. See [`PortDef::step`] for the full
    /// contract — the engine still needs to defend against non-snapped
    /// values arriving via wires.
    pub fn with_step(mut self, step: f32) -> Self {
        self.step = step;
        self
    }

    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = desc.into();
        self
    }

    pub fn with_unit(mut self, unit_type: UnitType) -> Self {
        self.unit_type = unit_type;
        self
    }

    pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
        self.icon = icon.into();
        self
    }

    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.label = label.into();
        self
    }

    /// Mark this port as exposed in the brush properties panel by default.
    pub fn exposed(mut self) -> Self {
        self.exposed = true;
        self
    }

    /// Opt this port out of preview rendering by spoofing it to a
    /// fixed value. See [`PortDef::preview_value`] for the contract.
    /// Use when the port's user-facing value is a working parameter
    /// (size, position, time) rather than part of the brush's identity.
    pub fn with_preview_value(mut self, value: f32) -> Self {
        self.preview_value = Some(value);
        self
    }

    /// Declare that this port's value is ignored by the synthetic-stroke
    /// editor preview pipeline, so the editor preview's cache need not
    /// rebuild on its scrub. See [`PortDef::preview_irrelevant_scrub`]
    /// for the contract.
    pub fn preview_irrelevant_scrub(mut self) -> Self {
        self.preview_irrelevant_scrub = true;
        self
    }

    /// Mark this exposed port as part of the brush's identity — its
    /// user-set value persists into the dab thumbnail, and scrubs of
    /// it rebake the thumbnail. See [`PortDef::persist_in_thumbnail`]
    /// for the contract. Use for orientation knobs (rotation)
    /// that visibly change the dab; don't use for magnitude knobs
    /// (size, opacity, flow) where the icon should stay normalized.
    pub fn persist_in_thumbnail(mut self) -> Self {
        self.persist_in_thumbnail = true;
        self
    }

    /// Show this port in the UI only when the named param's current
    /// integer value is one of `allowed_values`. See [`PortDef::visible_when`]
    /// for the contract. The frontend filters; the engine ignores this
    /// field entirely.
    pub fn with_visible_when(
        mut self,
        param_name: impl Into<String>,
        allowed_values: impl IntoIterator<Item = i32>,
    ) -> Self {
        self.visible_when = Some((param_name.into(), allowed_values.into_iter().collect()));
        self
    }
}

// ── Node instance ────────────────────────────────────────────────────

/// A placed node in a graph.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(bound = "")]
pub struct NodeInstance<W: WireKind> {
    pub id: NodeId,
    /// References the `type_id` from the `NodeRegistration`.
    pub type_id: String,
    /// Port definitions (copied from registration on creation).
    pub ports: Vec<PortDef<W>>,
    /// Per-instance parameter overrides.
    pub params: Vec<ParamValue>,
}

// ── Errors ───────────────────────────────────────────────────────────

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GraphError {
    TypeMismatch {
        from_type: String,
        to_type: String,
    },
    CycleDetected,
    PortNotFound {
        node: NodeId,
        port: String,
    },
    NodeNotFound(NodeId),
    /// An input port may only have one incoming wire.
    InputAlreadyConnected {
        node: NodeId,
        port: String,
    },
    /// `exposed_ports` lookup by key (`"<node_id>.<port>"`) failed.
    ExposedPortNotFound {
        key: String,
    },
    /// Icon string contained a character outside the Iconify-name
    /// shape (`[a-zA-Z0-9-: ]`). Rejected so the value stays a safe,
    /// inert token (it is passed to `<Icon name={...}>`, never `{@html}`).
    InvalidIcon {
        icon: String,
    },
}

/// Accept only the byte shape Iconify names use (`prefix:name`):
/// letters, digits, hyphens, and the `:` separator (spaces tolerated for
/// legacy values). Keeping the value within this alphabet means the stored
/// string is an inert token — the frontend hands it to `<Icon name={...}>`,
/// which resolves it against the offline bundle and renders nothing for an
/// unknown name, so a hostile value can never become markup.
fn is_safe_icon_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'-' || b == b':' || b == b' '
}

impl std::fmt::Display for GraphError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::TypeMismatch { from_type, to_type } => {
                write!(f, "type mismatch: {from_type}{to_type}")
            }
            Self::CycleDetected => write!(f, "cycle detected"),
            Self::PortNotFound { node, port } => {
                write!(f, "port '{}' not found on node {:?}", port, node)
            }
            Self::NodeNotFound(id) => write!(f, "node {:?} not found", id),
            Self::InputAlreadyConnected { node, port } => {
                write!(f, "input '{}' on {:?} already connected", port, node)
            }
            Self::ExposedPortNotFound { key } => {
                write!(f, "exposed-port entry '{}' not found", key)
            }
            Self::InvalidIcon { icon } => {
                write!(
                    f,
                    "icon '{}' contains characters outside [a-zA-Z0-9- ]",
                    icon
                )
            }
        }
    }
}

impl std::error::Error for GraphError {}

/// Result of [`Graph::find_terminal`]. A graph has exactly one terminal
/// node by construction today; the API surfaces both violations of that
/// invariant so a regression that compiles two terminals (or none) into
/// a brush surfaces loudly rather than silently picking one.
#[derive(Debug, Clone, PartialEq)]
pub enum FindTerminalError {
    /// No node in the graph has `is_terminal: true` in its registration.
    NoTerminal,
    /// More than one node has `is_terminal: true`. Carries every
    /// offending id so the caller can report which.
    MultipleTerminals(Vec<NodeId>),
}

impl std::fmt::Display for FindTerminalError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NoTerminal => write!(f, "graph has no terminal node"),
            Self::MultipleTerminals(ids) => {
                write!(f, "graph has multiple terminal nodes: {ids:?}")
            }
        }
    }
}

impl std::error::Error for FindTerminalError {}

// ── Exposed port metadata ────────────────────────────────────────────

/// Per-placement metadata for an entry in a graph's `exposed_ports` map.
/// All fields are optional: empty strings fall back to the registration's
/// `PortDef::label` / `PortDef::description` / `PortDef::icon` when the
/// brush bar renders the entry.
///
/// Lives in `Graph::exposed_ports` rather than on `PortDef` per instance
/// because the brush bar is a single user-facing surface — centralizing
/// "what the user sees" in one ordered dict makes display order natural
/// (map iteration order is the brush-bar order) and gives the
/// brush-author editor one canonical place to read and write.
#[derive(Clone, Default, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExposedPortMeta {
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub label: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub description: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub icon: String,
}

/// Format the canonical key for an exposed-port entry. Keys are
/// `"<node_id>.<port_name>"` strings so the dict round-trips through
/// JSON/YAML without needing tuple-key encoding.
pub fn exposed_port_key(node: NodeId, port: &str) -> String {
    format!("{}.{}", node.0, port)
}

// ── Graph ────────────────────────────────────────────────────────────

/// A directed acyclic graph of nodes connected by typed wires.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(bound = "")]
pub struct Graph<W: WireKind> {
    nodes: HashMap<NodeId, NodeInstance<W>>,
    pub connections: Vec<Connection>,
    next_id: u64,
    /// Ordered set of exposed-port entries. Insertion order is the
    /// brush-bar display order — `IndexMap` preserves it through every
    /// mutation and JSON/YAML round-trip. Keys come from
    /// [`exposed_port_key`].
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub exposed_ports: IndexMap<String, ExposedPortMeta>,
}

impl<W: WireKind> Default for Graph<W> {
    fn default() -> Self {
        Self::new()
    }
}

impl<W: WireKind> Graph<W> {
    pub fn new() -> Self {
        Self {
            nodes: HashMap::new(),
            connections: Vec::new(),
            next_id: 1,
            exposed_ports: IndexMap::new(),
        }
    }

    /// Read-only access to the node map. The graph owns id assignment
    /// (via [`add_node`](Self::add_node)) and the invariant that every
    /// connection references existing nodes, so external code must go
    /// through the graph's methods to mutate the set.
    pub fn nodes(&self) -> &HashMap<NodeId, NodeInstance<W>> {
        &self.nodes
    }

    /// Add a node and return its assigned id. Any input port whose
    /// registration `PortDef` declares `.exposed()` is auto-appended to
    /// `exposed_ports` with empty meta — preserves the "size etc. are
    /// exposed by default" affordance.
    pub fn add_node(
        &mut self,
        type_id: impl Into<String>,
        ports: Vec<PortDef<W>>,
        params: Vec<ParamValue>,
    ) -> NodeId {
        let id = NodeId(self.next_id);
        self.next_id += 1;
        // Walk before move: every input port flagged exposed gets a
        // default brush-bar entry.
        for port in ports.iter() {
            if port.dir == PortDir::Input && port.exposed {
                let key = exposed_port_key(id, &port.name);
                self.exposed_ports.insert(key, ExposedPortMeta::default());
            }
        }
        self.nodes.insert(
            id,
            NodeInstance {
                id,
                type_id: type_id.into(),
                ports,
                params,
            },
        );
        id
    }

    /// Remove a node, all its connections, and every brush-bar entry
    /// referencing one of its ports.
    pub fn remove_node(&mut self, id: NodeId) -> Result<(), GraphError> {
        if self.nodes.remove(&id).is_none() {
            return Err(GraphError::NodeNotFound(id));
        }
        self.connections
            .retain(|c| c.from.node != id && c.to.node != id);
        let prefix = format!("{}.", id.0);
        self.exposed_ports
            .retain(|key, _| !key.starts_with(&prefix));
        Ok(())
    }

    /// Add a brush-bar entry for an input port, no-op if already present.
    /// The entry starts with empty meta (registration values are used as
    /// fallback at render time).
    pub fn expose_port(&mut self, id: NodeId, port_name: &str) -> Result<(), GraphError> {
        // Validate that the port exists and is an input.
        let node = self.nodes.get(&id).ok_or(GraphError::NodeNotFound(id))?;
        if !node
            .ports
            .iter()
            .any(|p| p.name == port_name && p.dir == PortDir::Input)
        {
            return Err(GraphError::PortNotFound {
                node: id,
                port: port_name.to_string(),
            });
        }
        let key = exposed_port_key(id, port_name);
        self.exposed_ports.entry(key).or_default();
        Ok(())
    }

    /// Drop a brush-bar entry by `(node, port)`. Idempotent — missing
    /// entries are not an error.
    pub fn unexpose_port(&mut self, id: NodeId, port_name: &str) {
        let key = exposed_port_key(id, port_name);
        self.exposed_ports.shift_remove(&key);
    }

    /// Returns true when the named input port has a live brush-bar entry.
    pub fn is_port_exposed(&self, id: NodeId, port_name: &str) -> bool {
        self.exposed_ports
            .contains_key(&exposed_port_key(id, port_name))
    }

    /// Overwrite all three meta fields on a brush-bar entry in one call.
    /// The icon field is restricted to FontAwesome-friendly characters
    /// (`[a-zA-Z0-9- ]*`) — keeps the value safe to bind directly into
    /// an HTML `class=` attribute on the frontend without further
    /// sanitization. Out-of-shape icon strings are rejected loudly so
    /// the caller learns about the constraint rather than seeing the
    /// icon silently dropped.
    pub fn set_exposed_port_meta(
        &mut self,
        key: &str,
        label: String,
        description: String,
        icon: String,
    ) -> Result<(), GraphError> {
        if !icon.bytes().all(is_safe_icon_byte) {
            return Err(GraphError::InvalidIcon { icon });
        }
        let entry =
            self.exposed_ports
                .get_mut(key)
                .ok_or_else(|| GraphError::ExposedPortNotFound {
                    key: key.to_string(),
                })?;
        entry.label = label;
        entry.description = description;
        entry.icon = icon;
        Ok(())
    }

    /// Move an exposed-port entry to position `new_index`. The map's
    /// iteration order is the brush-bar display order, so this is how
    /// drag-reorder is realised. `new_index` is clamped to the map's
    /// length.
    pub fn reorder_exposed_port(&mut self, key: &str, new_index: usize) -> Result<(), GraphError> {
        let from = self.exposed_ports.get_index_of(key).ok_or_else(|| {
            GraphError::ExposedPortNotFound {
                key: key.to_string(),
            }
        })?;
        let target = new_index.min(self.exposed_ports.len().saturating_sub(1));
        self.exposed_ports.move_index(from, target);
        Ok(())
    }

    /// Connect an output port to an input port, checking types and cycles.
    pub fn connect(&mut self, from: PortRef, to: PortRef) -> Result<(), GraphError> {
        // Resolve port defs.
        let from_def = self.find_port(&from, PortDir::Output)?;
        let to_def = self.find_port(&to, PortDir::Input)?;

        // Type check.
        if !W::compatible(from_def, to_def) {
            return Err(GraphError::TypeMismatch {
                from_type: format!("{:?}", from_def),
                to_type: format!("{:?}", to_def),
            });
        }

        // Input-already-connected check.
        if self.connections.iter().any(|c| c.to == to) {
            return Err(GraphError::InputAlreadyConnected {
                node: to.node,
                port: to.port.clone(),
            });
        }

        // Cycle check: would adding from→to create a cycle?
        // A cycle exists iff `from.node` is reachable from `to.node`
        // through existing connections (i.e., to is upstream of from).
        if self.is_reachable(to.node, from.node) {
            return Err(GraphError::CycleDetected);
        }

        self.connections.push(Connection { from, to });
        Ok(())
    }

    /// Disconnect a specific wire.
    pub fn disconnect(&mut self, from: &PortRef, to: &PortRef) {
        self.connections.retain(|c| &c.from != from || &c.to != to);
    }

    /// All connections whose destination is a port on `node_id`.
    pub fn inputs_for(&self, node_id: NodeId) -> impl Iterator<Item = &Connection> {
        self.connections
            .iter()
            .filter(move |c| c.to.node == node_id)
    }

    /// All connections whose source is a port on `node_id`.
    pub fn outputs_for(&self, node_id: NodeId) -> impl Iterator<Item = &Connection> {
        self.connections
            .iter()
            .filter(move |c| c.from.node == node_id)
    }

    /// Neutralize ports annotated with [`PortDef::preview_value`] so
    /// the graph compiles to a cursor-overlay-friendly preview shader.
    ///
    /// For each port carrying a `preview_value`, this drops any incoming
    /// wire on the port and replaces its `default` with the annotated
    /// constant. Ports without a `preview_value` are left alone.
    ///
    /// Called by every renderer that wants brush-identity output rather
    /// than the user's momentary scrub state:
    /// - the WGSL compiler, on a clone, before emitting
    ///   `CompiledBrush::cursor_preview_wgsl` (the cursor halo);
    /// - the brush-editor stroke preview;
    /// - the library thumbnail bake (`brush_save`, `brush_thumbnail`).
    ///
    /// The picker dab tile uses a different, more aggressive neutralizer
    /// (`reset_exposed_scrubs`) that resets every exposed scrub to its
    /// registration default. Both kinds of preview want the same end:
    /// scrubbing any `preview_value`-tagged port shouldn't redraw the
    /// preview, because the rendered output is identical by construction.
    pub(crate) fn apply_preview_overrides(&mut self) {
        let mut overrides: Vec<(NodeId, String, f32)> = Vec::new();
        for node in self.nodes.values() {
            for port in &node.ports {
                if let Some(value) = port.preview_value {
                    overrides.push((node.id, port.name.clone(), value));
                }
            }
        }
        for (node_id, port_name, value) in overrides {
            // Drop incoming wires so the spoofed default is what the
            // compiler reads.
            self.connections
                .retain(|c| !(c.to.node == node_id && c.to.port == port_name));
            if let Some(node) = self.nodes.get_mut(&node_id) {
                if let Some(port) = node.ports.iter_mut().find(|p| p.name == port_name) {
                    port.default = value;
                }
            }
        }
    }

    /// Update a port's default value on a node instance.
    ///
    /// This changes the value used when the port is disconnected.
    pub fn set_port_default(
        &mut self,
        id: NodeId,
        port_name: &str,
        value: f32,
    ) -> Result<(), GraphError> {
        let node = self
            .nodes
            .get_mut(&id)
            .ok_or(GraphError::NodeNotFound(id))?;
        let port = node
            .ports
            .iter_mut()
            .find(|p| p.name == port_name && p.dir == PortDir::Input)
            .ok_or_else(|| GraphError::PortNotFound {
                node: id,
                port: port_name.to_string(),
            })?;
        port.default = value;
        Ok(())
    }

    // Note: brush-bar exposure / label / description / icon overrides
    // live in `Graph::exposed_ports` now. Use `expose_port`,
    // `unexpose_port`, `set_exposed_port_meta`, and `reorder_exposed_port`.

    /// Update a single parameter value on a node.
    pub fn set_param(
        &mut self,
        id: NodeId,
        index: usize,
        value: ParamValue,
    ) -> Result<(), GraphError> {
        let node = self
            .nodes
            .get_mut(&id)
            .ok_or(GraphError::NodeNotFound(id))?;
        if index >= node.params.len() {
            return Err(GraphError::PortNotFound {
                node: id,
                port: format!("param[{}]", index),
            });
        }
        node.params[index] = value;
        Ok(())
    }

    /// Find the unique node in this graph whose registration declares
    /// `is_terminal: true`. By today's invariant a brush graph contains
    /// exactly one terminal; deviations are reported via
    /// [`FindTerminalError`] rather than silently arbitrated.
    pub fn find_terminal(
        &self,
        registry: &HashMap<String, NodeRegistration<W>>,
    ) -> Result<NodeId, FindTerminalError> {
        let mut terminals: Vec<NodeId> = self
            .nodes
            .iter()
            .filter_map(|(id, node)| {
                registry
                    .get(&node.type_id)
                    .filter(|r| r.is_terminal)
                    .map(|_| *id)
            })
            .collect();
        match terminals.len() {
            0 => Err(FindTerminalError::NoTerminal),
            1 => Ok(terminals.remove(0)),
            _ => {
                terminals.sort_by_key(|id| id.0);
                Err(FindTerminalError::MultipleTerminals(terminals))
            }
        }
    }

    // ── helpers ──────────────────────────────────────────────────────

    /// Find the wire type of a port, returning an error if the node or
    /// port doesn't exist or has the wrong direction.
    fn find_port(&self, pr: &PortRef, expected_dir: PortDir) -> Result<W, GraphError> {
        let node = self
            .nodes
            .get(&pr.node)
            .ok_or(GraphError::NodeNotFound(pr.node))?;
        let def = node
            .ports
            .iter()
            .find(|p| p.name == pr.port && p.dir == expected_dir)
            .ok_or_else(|| GraphError::PortNotFound {
                node: pr.node,
                port: pr.port.clone(),
            })?;
        Ok(def.wire_type)
    }

    /// DFS reachability: can we get from `start` to `target` following
    /// existing connection edges (from.node → to.node)?
    fn is_reachable(&self, start: NodeId, target: NodeId) -> bool {
        let mut visited = HashSet::new();
        let mut stack = vec![start];
        while let Some(current) = stack.pop() {
            if current == target {
                return true;
            }
            if !visited.insert(current) {
                continue;
            }
            for conn in &self.connections {
                if conn.from.node == current {
                    stack.push(conn.to.node);
                }
            }
        }
        false
    }
}

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

    fn scalar_in(name: &str) -> PortDef<TestWireKind> {
        PortDef::input(name, TestWireKind::Scalar)
    }
    fn scalar_out(name: &str) -> PortDef<TestWireKind> {
        PortDef::output(name, TestWireKind::Scalar)
    }
    fn color_out(name: &str) -> PortDef<TestWireKind> {
        PortDef::output(name, TestWireKind::Color)
    }

    #[test]
    fn add_connect_disconnect_remove() {
        let mut g = Graph::<TestWireKind>::new();
        let a = g.add_node("source", vec![scalar_out("out")], vec![]);
        let b = g.add_node("sink", vec![scalar_in("in")], vec![]);

        let from = PortRef {
            node: a,
            port: "out".into(),
        };
        let to = PortRef {
            node: b,
            port: "in".into(),
        };

        g.connect(from.clone(), to.clone()).unwrap();
        assert_eq!(g.connections.len(), 1);

        g.disconnect(&from, &to);
        assert_eq!(g.connections.len(), 0);

        g.remove_node(a).unwrap();
        assert!(!g.nodes.contains_key(&a));
    }

    #[test]
    fn cycle_detection() {
        let mut g = Graph::<TestWireKind>::new();
        let a = g.add_node("a", vec![scalar_in("in"), scalar_out("out")], vec![]);
        let b = g.add_node("b", vec![scalar_in("in"), scalar_out("out")], vec![]);

        g.connect(
            PortRef {
                node: a,
                port: "out".into(),
            },
            PortRef {
                node: b,
                port: "in".into(),
            },
        )
        .unwrap();

        let err = g
            .connect(
                PortRef {
                    node: b,
                    port: "out".into(),
                },
                PortRef {
                    node: a,
                    port: "in".into(),
                },
            )
            .unwrap_err();

        assert_eq!(err, GraphError::CycleDetected);
    }

    #[test]
    fn type_mismatch() {
        let mut g = Graph::<TestWireKind>::new();
        let a = g.add_node("a", vec![color_out("out")], vec![]);
        let b = g.add_node("b", vec![scalar_in("in")], vec![]);

        let err = g
            .connect(
                PortRef {
                    node: a,
                    port: "out".into(),
                },
                PortRef {
                    node: b,
                    port: "in".into(),
                },
            )
            .unwrap_err();

        matches!(err, GraphError::TypeMismatch { .. });
    }

    #[test]
    fn input_already_connected() {
        let mut g = Graph::<TestWireKind>::new();
        let a = g.add_node("a", vec![scalar_out("out")], vec![]);
        let b = g.add_node("b", vec![scalar_out("out")], vec![]);
        let c = g.add_node("c", vec![scalar_in("in")], vec![]);

        g.connect(
            PortRef {
                node: a,
                port: "out".into(),
            },
            PortRef {
                node: c,
                port: "in".into(),
            },
        )
        .unwrap();

        let err = g
            .connect(
                PortRef {
                    node: b,
                    port: "out".into(),
                },
                PortRef {
                    node: c,
                    port: "in".into(),
                },
            )
            .unwrap_err();

        matches!(err, GraphError::InputAlreadyConnected { .. });
    }

    #[test]
    fn remove_node_cleans_connections() {
        let mut g = Graph::<TestWireKind>::new();
        let a = g.add_node("a", vec![scalar_out("out")], vec![]);
        let b = g.add_node("b", vec![scalar_in("in"), scalar_out("out")], vec![]);
        let c = g.add_node("c", vec![scalar_in("in")], vec![]);

        g.connect(
            PortRef {
                node: a,
                port: "out".into(),
            },
            PortRef {
                node: b,
                port: "in".into(),
            },
        )
        .unwrap();
        g.connect(
            PortRef {
                node: b,
                port: "out".into(),
            },
            PortRef {
                node: c,
                port: "in".into(),
            },
        )
        .unwrap();

        g.remove_node(b).unwrap();
        assert!(g.connections.is_empty());
    }

    #[test]
    fn serde_round_trip() {
        let mut g = Graph::<TestWireKind>::new();
        let a = g.add_node("source", vec![scalar_out("out")], vec![]);
        let b = g.add_node("sink", vec![scalar_in("in")], vec![]);
        g.connect(
            PortRef {
                node: a,
                port: "out".into(),
            },
            PortRef {
                node: b,
                port: "in".into(),
            },
        )
        .unwrap();

        let json = serde_json::to_string(&g).unwrap();
        let g2: Graph<TestWireKind> = serde_json::from_str(&json).unwrap();
        assert_eq!(g2.nodes.len(), 2);
        assert_eq!(g2.connections.len(), 1);
    }

    // ── UnitType tests ──────────────────────────────────────────────

    #[test]
    fn unit_type_conversion_round_trip() {
        for unit in [
            UnitType::Normalized,
            UnitType::Percent,
            UnitType::Degrees,
            UnitType::Raw,
        ] {
            for &val in &[0.0, 0.25, 0.5, 0.75, 1.0] {
                let display = unit.to_display(val);
                let back = unit.from_display(display);
                assert!(
                    (back - val).abs() < 1e-6,
                    "{:?}: to_display({}) = {}, from_display({}) = {} (expected {})",
                    unit,
                    val,
                    display,
                    display,
                    back,
                    val,
                );
            }
        }
    }

    #[test]
    fn unit_type_display_values() {
        use std::f32::consts::PI;
        assert!((UnitType::Percent.to_display(0.5) - 50.0).abs() < 1e-6);
        // Degrees: wire unit is radians, display is degrees.
        assert!((UnitType::Degrees.to_display(PI) - 180.0).abs() < 1e-4);
        assert!((UnitType::Degrees.to_display(PI / 2.0) - 90.0).abs() < 1e-4);
        assert!((UnitType::Degrees.to_display(0.0) - 0.0).abs() < 1e-6);
        assert!((UnitType::Degrees.from_display(90.0) - PI / 2.0).abs() < 1e-4);
        assert!((UnitType::Normalized.to_display(0.5) - 0.5).abs() < 1e-6);
        assert!((UnitType::Raw.to_display(0.5) - 0.5).abs() < 1e-6);
    }

    #[test]
    fn unit_type_suffix() {
        assert_eq!(UnitType::Percent.suffix(), "%");
        assert_eq!(UnitType::Degrees.suffix(), "°");
        assert_eq!(UnitType::Normalized.suffix(), "");
        assert_eq!(UnitType::Raw.suffix(), "");
    }

    #[test]
    fn unit_type_serde_round_trip() {
        for unit in [
            UnitType::Normalized,
            UnitType::Percent,
            UnitType::Degrees,
            UnitType::Raw,
        ] {
            let json = serde_json::to_string(&unit).unwrap();
            let back: UnitType = serde_json::from_str(&json).unwrap();
            assert_eq!(unit, back);
        }
    }

    #[test]
    fn port_def_natural_range_round_trip() {
        let port = PortDef::input("seed", TestWireKind::Scalar)
            .with_range(0.0, 1024.0, 0.0)
            .with_natural_range(0.0, 1024.0);
        let json = serde_json::to_string(&port).unwrap();
        let back: PortDef<TestWireKind> = serde_json::from_str(&json).unwrap();
        assert_eq!(back.natural_range, Some((0.0, 1024.0)));

        // Default builder leaves natural_range unset — opt-in only.
        let bare = PortDef::input("x", TestWireKind::Scalar);
        assert_eq!(bare.natural_range, None);
    }

    #[test]
    fn port_def_step_round_trip() {
        let port = PortDef::input("frequency", TestWireKind::Scalar)
            .with_range(1.0, 16.0, 6.0)
            .with_step(1.0);
        let json = serde_json::to_string(&port).unwrap();
        let back: PortDef<TestWireKind> = serde_json::from_str(&json).unwrap();
        assert_eq!(back.step, 1.0);
    }

    #[test]
    fn port_def_serde_with_new_fields() {
        let port = PortDef::input("opacity", TestWireKind::Scalar)
            .with_range(0.0, 1.0, 1.0)
            .with_unit(UnitType::Percent)
            .with_icon("fa6-solid:sun")
            .with_label("Opacity")
            .exposed()
            .with_description("Per-dab opacity");

        let json = serde_json::to_string(&port).unwrap();
        let back: PortDef<TestWireKind> = serde_json::from_str(&json).unwrap();
        assert_eq!(back.unit_type, UnitType::Percent);
        assert_eq!(back.icon, "fa6-solid:sun");
        assert_eq!(back.label, "Opacity");
        assert!(back.exposed);
        assert_eq!(back.description, "Per-dab opacity");
    }

    // ── exposed_ports ──────────────────────────────────────────────

    #[test]
    fn expose_then_unexpose_round_trips() {
        let mut g = Graph::<TestWireKind>::new();
        let id = g.add_node("node", vec![scalar_in("val")], vec![]);

        assert!(!g.is_port_exposed(id, "val"));
        g.expose_port(id, "val").unwrap();
        assert!(g.is_port_exposed(id, "val"));
        // Idempotent — double-expose doesn't add a duplicate.
        g.expose_port(id, "val").unwrap();
        assert_eq!(g.exposed_ports.len(), 1);
        g.unexpose_port(id, "val");
        assert!(!g.is_port_exposed(id, "val"));
    }

    #[test]
    fn expose_port_rejects_output_port() {
        let mut g = Graph::<TestWireKind>::new();
        let id = g.add_node("node", vec![scalar_out("out")], vec![]);
        let err = g.expose_port(id, "out").unwrap_err();
        assert!(matches!(err, GraphError::PortNotFound { .. }));
    }

    #[test]
    fn add_node_seeds_exposed_from_registration_flag() {
        let mut g = Graph::<TestWireKind>::new();
        // Two inputs: only the second is flagged `.exposed()` at the
        // registration level. add_node should auto-append it to
        // exposed_ports with empty meta.
        let mut a = scalar_in("a");
        let mut b = scalar_in("b");
        a.exposed = false;
        b.exposed = true;
        let id = g.add_node("node", vec![a, b], vec![]);
        assert!(!g.is_port_exposed(id, "a"));
        assert!(g.is_port_exposed(id, "b"));
        // Empty meta — falls back to registration at render time.
        let key = exposed_port_key(id, "b");
        assert_eq!(g.exposed_ports[&key], ExposedPortMeta::default());
    }

    #[test]
    fn remove_node_drops_exposed_entries() {
        let mut g = Graph::<TestWireKind>::new();
        let a = g.add_node("node", vec![scalar_in("x"), scalar_in("y")], vec![]);
        let b = g.add_node("node", vec![scalar_in("x")], vec![]);
        g.expose_port(a, "x").unwrap();
        g.expose_port(a, "y").unwrap();
        g.expose_port(b, "x").unwrap();
        assert_eq!(g.exposed_ports.len(), 3);

        g.remove_node(a).unwrap();
        // Only b.x survives.
        assert_eq!(g.exposed_ports.len(), 1);
        assert!(g.is_port_exposed(b, "x"));
    }

    #[test]
    fn reorder_moves_entry_to_target_index() {
        let mut g = Graph::<TestWireKind>::new();
        let id = g.add_node(
            "node",
            vec![scalar_in("a"), scalar_in("b"), scalar_in("c")],
            vec![],
        );
        g.expose_port(id, "a").unwrap();
        g.expose_port(id, "b").unwrap();
        g.expose_port(id, "c").unwrap();
        let keys: Vec<&str> = g.exposed_ports.keys().map(String::as_str).collect();
        assert_eq!(keys.len(), 3);

        // Move b to index 0.
        let b_key = exposed_port_key(id, "b");
        g.reorder_exposed_port(&b_key, 0).unwrap();

        let order: Vec<&str> = g.exposed_ports.keys().map(String::as_str).collect();
        let a_key = exposed_port_key(id, "a");
        let c_key = exposed_port_key(id, "c");
        assert_eq!(order, vec![b_key.as_str(), a_key.as_str(), c_key.as_str()]);
    }

    #[test]
    fn set_meta_rejects_unsafe_icon() {
        let mut g = Graph::<TestWireKind>::new();
        let id = g.add_node("node", vec![scalar_in("val")], vec![]);
        g.expose_port(id, "val").unwrap();
        let key = exposed_port_key(id, "val");

        // Safe icon class — accepted.
        g.set_exposed_port_meta(&key, "Label".into(), "Desc".into(), "fa6-solid:sun".into())
            .unwrap();
        assert_eq!(g.exposed_ports[&key].icon, "fa6-solid:sun");

        // Unsafe icon (contains `<`) — rejected; previous value retained.
        let err = g
            .set_exposed_port_meta(
                &key,
                "Label2".into(),
                "Desc2".into(),
                "<script>x</script>".into(),
            )
            .unwrap_err();
        assert!(matches!(err, GraphError::InvalidIcon { .. }));
        assert_eq!(g.exposed_ports[&key].icon, "fa6-solid:sun");
        assert_eq!(g.exposed_ports[&key].label, "Label");
    }

    #[test]
    fn exposed_ports_round_trip_preserves_order() {
        let mut g = Graph::<TestWireKind>::new();
        let id = g.add_node(
            "node",
            vec![scalar_in("a"), scalar_in("b"), scalar_in("c")],
            vec![],
        );
        g.expose_port(id, "c").unwrap();
        g.expose_port(id, "a").unwrap();
        g.expose_port(id, "b").unwrap();
        let before: Vec<String> = g.exposed_ports.keys().cloned().collect();

        let json = serde_json::to_string(&g).unwrap();
        let back: Graph<TestWireKind> = serde_json::from_str(&json).unwrap();
        let after: Vec<String> = back.exposed_ports.keys().cloned().collect();
        assert_eq!(before, after);
    }
}