disposition_input_ir_rt 0.3.0

Logic to map `disposition` input model to intermediate representation.
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
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
use disposition_input_ir_model::IrDiagramAndIssues;
use disposition_input_model::{
    edge::{EdgeGroup as InputEdgeGroup, EdgeKind},
    entity::EntityTypes,
    process::{ProcessDiagram, Processes},
    tag::TagNames,
    theme::{ThemeDefault, ThemeTypesStyles},
    thing::{
        ThingCopyText, ThingDependencies, ThingHierarchy as InputThingHierarchy, ThingId,
        ThingInteractions, ThingLayouts, ThingNames,
    },
    InputDiagram,
};
use disposition_ir_model::{
    edge::{Edge, EdgeGroup, EdgeGroups},
    entity::EntityType,
    enum_iterator,
    layout::{FlexDirection, FlexLayout, LeafLayout, NodeLayout, NodeLayouts},
    node::{
        NodeCopyText, NodeFaceEdges, NodeHierarchy, NodeId, NodeInbuilt, NodeNames, NodeOrdering,
        NodeShapes,
    },
    process::{ProcessStepEdges, ProcessStepEntities, ProcessStepRank, ProcessStepRanks},
    IrDiagram,
};
use disposition_model_common::{edge::EdgeGroupId, theme::Css, Id, Map, RankDir, Set};

use crate::{
    edge_face_assigner::EdgeFaceAssigner, node_ranks_calculator::NodeRanksCalculator,
    process_step_graph_calculator::ProcessStepGraphCalculator,
};

use self::{
    css_theme_vars::CssThemeVars, node_nesting_infos_builder::NodeNestingInfosBuilder,
    tailwind_classes_builder::TailwindClassesBuilder, theme_attr_resolver::ThemeAttrResolver,
};

mod css_theme_vars;
mod node_nesting_infos_builder;
mod tailwind_class_state;
mod tailwind_classes_builder;
pub(crate) mod tailwind_color_shade;
pub(crate) mod tailwind_colors;
mod theme_attr_resolver;

/// Maps an input diagram to an intermediate representation diagram.
#[derive(Clone, Copy, Debug)]
pub struct InputToIrDiagramMapper;

/// Immutable theme lookup context threaded through the node-layout builders.
///
/// Bundles the three theme sources that every `ThemeAttrResolver` call needs,
/// so the layout builders take a single `Copy` context instead of repeating the
/// same trio of parameters.
#[derive(Clone, Copy)]
struct ThemeResolveCtx<'a, 'id> {
    entity_types: &'a EntityTypes<'id>,
    theme_default: &'a ThemeDefault<'id>,
    theme_types_styles: &'a ThemeTypesStyles<'id>,
}

impl InputToIrDiagramMapper {
    /// Maps an input diagram to an intermediate representation diagram.
    pub fn map<'f, 'id>(input_diagram: &'f InputDiagram<'id>) -> IrDiagramAndIssues<'id>
    where
        'id: 'f,
    {
        let issues = Vec::new();

        let InputDiagram {
            things,
            thing_names,
            thing_copy_text,
            thing_layouts,
            thing_dependencies,
            thing_interactions,
            thing_descs,
            processes,
            tags,
            tag_things,
            edge_descs,
            edge_labels,
            entity_tooltips,
            entity_types,
            theme_default,
            theme_types_styles,
            theme_thing_dependencies_styles: _,
            theme_tag_things_focus,
            render_options,
            css,
        } = input_diagram;

        // 1. Build NodeNames from the things hierarchy (with thing_names labels), tags,
        //    processes, and process steps
        let nodes = Self::build_node_names(things, thing_names, tags, processes);

        // 2. Build NodeCopyText from thing_copy_text
        let node_copy_text = Self::build_node_copy_text(thing_copy_text);

        // 3. Build NodeHierarchy from tags, processes (with steps), and the things
        //    hierarchy
        let node_hierarchy = Self::build_node_hierarchy(tags, processes, things);

        // 4. Build NodeOrdering from the things hierarchy, tags, and processes
        let node_ordering = Self::build_node_ordering(things, tags, processes);

        // 5. Build EdgeGroups from thing_dependencies and thing_interactions
        let edge_groups = Self::build_edge_groups(thing_dependencies, thing_interactions);

        // 6. Clone ThingDescs from input thing_descs
        let thing_descs = thing_descs.clone();

        // 7. Build EdgeLabels from input edge_labels
        let edge_labels = edge_labels.clone();

        // 8. Clone EdgeDescs from input edge_descs
        let edge_descs = edge_descs.clone();

        // 9. Build EntityTooltips from input entity_tooltips
        let entity_tooltips = entity_tooltips.clone();

        // 10. Build EntityTypes with defaults for each node type
        let ir_entity_types = Self::build_entity_types(
            things,
            tags,
            processes,
            entity_types,
            thing_dependencies,
            thing_interactions,
        );

        // 11. Build NodeLayouts from node_hierarchy and theme
        let flex_direction_default = match render_options.rank_dir {
            RankDir::LeftToRight => FlexDirection::Column,
            RankDir::RightToLeft => FlexDirection::ColumnReverse,
            RankDir::TopToBottom => FlexDirection::Row,
            RankDir::BottomToTop => FlexDirection::RowReverse,
        };
        let theme_resolve_ctx = ThemeResolveCtx {
            entity_types: &ir_entity_types,
            theme_default,
            theme_types_styles,
        };
        let node_layouts = Self::build_node_layouts(
            &node_hierarchy,
            flex_direction_default,
            theme_resolve_ctx,
            tags,
            processes,
            thing_layouts,
        );

        // 12. Build NodeShapes from theme
        let node_shapes =
            Self::build_node_shapes(&nodes, &ir_entity_types, theme_default, theme_types_styles);

        // 13. Build TailwindClasses from theme
        //
        // Process steps are hidden (until focused) only when processes are
        // rendered collapsed.
        let process_render_expanded = render_options
            .process_render_collapse
            .process_render_expanded(processes.len());
        let tailwind_classes_build_result = TailwindClassesBuilder::build(
            &nodes,
            &edge_groups,
            &ir_entity_types,
            theme_default,
            theme_types_styles,
            theme_tag_things_focus,
            tags,
            tag_things,
            processes,
            process_render_expanded,
        );
        let mut tailwind_classes = tailwind_classes_build_result.tailwind_classes;
        let mut css_theme_vars = tailwind_classes_build_result.css_theme_vars;

        // 14. Build ProcessStepEntities from step_thing_interactions
        let process_step_entities = Self::build_process_step_entities(processes);

        // 14a. Build ProcessStepEdges from process_step_dependencies
        let process_step_edges = Self::build_process_step_edges(processes);

        // 14b. Compute ProcessStepRanks from process steps and their edges
        let process_step_ranks = Self::build_process_step_ranks(processes, &process_step_edges);

        // 14c. Compute ProcessStepGraphs (git-graph lane layout) from ranks and edges
        let process_step_graphs = ProcessStepGraphCalculator::calculate(
            processes,
            &process_step_ranks,
            &process_step_edges,
        );

        // 14d. Style process step connectors like dependency edges, sharing one
        //      resolved `edge_defaults` class string across all of them.
        if !process_step_graphs.is_empty() {
            let connector_classes = TailwindClassesBuilder::build_process_step_connector_classes(
                theme_default,
                theme_types_styles,
                &mut css_theme_vars,
            );
            process_step_graphs
                .values()
                .flat_map(|process_step_graph| &process_step_graph.edges)
                .for_each(|process_step_graph_edge| {
                    tailwind_classes.insert(
                        process_step_graph_edge.edge_id().into_inner(),
                        connector_classes.clone(),
                    );
                });
        }

        // 15. Compute NodeNestingInfos from node_hierarchy
        let node_nesting_infos = NodeNestingInfosBuilder::build(&node_hierarchy);

        // 16. Compute NodeRanksNested from dependency edges, using nesting infos to
        //     attribute cross-container edges to the correct level
        let node_ranks_nested =
            NodeRanksCalculator::calculate(&edge_groups, &ir_entity_types, &node_nesting_infos);

        // 17. Compute EdgeFaceAssignments from rank/sibling data before layout
        let edge_face_assignments = EdgeFaceAssigner::compute(
            &edge_groups,
            &ir_entity_types,
            &node_nesting_infos,
            &node_ranks_nested,
            render_options.rank_dir,
        );

        // 18. Derive NodeFaceEdges from edge_face_assignments and edge_groups
        let node_face_edges = NodeFaceEdges::from_assignments(&edge_face_assignments, &edge_groups);

        let diagram = IrDiagram {
            nodes,
            node_copy_text,
            node_hierarchy,
            node_ordering,
            edge_groups,
            thing_descs,
            edge_descs,
            edge_labels,
            entity_tooltips,
            entity_types: ir_entity_types,
            tailwind_classes,
            node_layouts,
            node_ranks_nested,
            node_nesting_infos,
            edge_face_assignments,
            node_face_edges,
            node_shapes,
            process_step_entities,
            process_step_edges,
            process_step_ranks,
            process_step_graphs,
            render_options: *render_options,
            css: Self::css_with_theme_vars(css, &css_theme_vars),
        };

        IrDiagramAndIssues { diagram, issues }
    }

    /// Prepend CSS theme variable definitions to the diagram's CSS.
    ///
    /// When `css_theme_vars` is empty the original CSS is returned unchanged.
    /// Otherwise the variable blocks are placed before any existing CSS so
    /// that the custom properties are available to all subsequent rules.
    fn css_with_theme_vars(css: &Css, css_theme_vars: &CssThemeVars) -> Css {
        if css_theme_vars.is_empty() {
            return css.clone();
        }

        let vars_css = css_theme_vars.to_css();
        if css.is_empty() {
            Css::from_string(vars_css)
        } else {
            Css::from_string(format!("{vars_css}\n{}", css.as_str()))
        }
    }

    /// Creates an Id from a String.
    fn id_from_string(s: String) -> Id<'static> {
        // Use TryFrom<String> to create an Id from an owned String.
        // This will validate the ID format and create a Cow::Owned internally.
        Id::try_from(s).expect("valid ID string")
    }

    // === Node Names === //

    /// Build NodeNames from the things hierarchy, tags, processes, and process
    /// steps.
    ///
    /// A node is created for every `ThingId` in the `things` hierarchy. Its
    /// display label is looked up in `thing_names`, defaulting to the
    /// `ThingId` string when no entry exists.
    fn build_node_names<'id>(
        things: &InputThingHierarchy<'id>,
        thing_names: &ThingNames<'id>,
        tags: &TagNames<'id>,
        processes: &Processes<'id>,
    ) -> NodeNames<'id> {
        // Add things from the hierarchy, defaulting the name to the ThingId.
        let thing_nodes = things.thing_ids_recursive().into_iter().map(|thing_id| {
            let node_id = NodeId::from(thing_id.as_ref().clone());
            let name = thing_names
                .get(thing_id.as_ref())
                .cloned()
                .unwrap_or_else(|| thing_id.as_str().to_string());
            (node_id, name)
        });

        // Add tags
        let tag_nodes = tags.iter().map(|(tag_id, name)| {
            let node_id = NodeId::from(tag_id.as_ref().clone());
            (node_id, name.clone())
        });

        // Add processes and their steps
        let process_and_step_nodes = processes.iter().flat_map(|(process_id, process_diagram)| {
            // Add process name
            let process_node_id = NodeId::from(process_id.as_ref().clone());
            let process_name = process_diagram
                .name
                .clone()
                .unwrap_or_else(|| process_id.as_str().to_string());

            // Add process steps
            let step_nodes = process_diagram.steps.iter().map(|(step_id, step_name)| {
                let step_node_id = NodeId::from(step_id.as_ref().clone());
                (step_node_id, step_name.clone())
            });

            std::iter::once((process_node_id, process_name)).chain(step_nodes)
        });

        thing_nodes
            .chain(tag_nodes)
            .chain(process_and_step_nodes)
            .collect()
    }

    // === Node Copy Text === //

    /// Build NodeCopyText from thing_copy_text.
    fn build_node_copy_text<'id>(thing_copy_text: &ThingCopyText<'id>) -> NodeCopyText<'id> {
        thing_copy_text
            .iter()
            .map(|(thing_id, text)| {
                let node_id = NodeId::from(thing_id.as_ref().clone());
                (node_id, text.clone())
            })
            .collect()
    }

    // === Node Hierarchy === //

    /// Build NodeHierarchy from tags, processes (with steps), and
    /// thing_hierarchy.
    fn build_node_hierarchy<'id>(
        tags: &TagNames<'id>,
        processes: &Processes<'id>,
        thing_hierarchy: &InputThingHierarchy<'id>,
    ) -> NodeHierarchy<'id> {
        // Add tags first (for CSS peer selector ordering)
        let tag_entries = tags.keys().map(|tag_id| {
            let node_id = NodeId::from(tag_id.as_ref().clone());
            (node_id, NodeHierarchy::new())
        });

        // Add processes with their steps
        let process_entries = processes.iter().map(|(process_id, process_diagram)| {
            let process_node_id = NodeId::from(process_id.as_ref().clone());
            let process_children: NodeHierarchy = process_diagram
                .steps
                .keys()
                .map(|step_id| {
                    let step_node_id = NodeId::from(step_id.as_ref().clone());
                    (step_node_id, NodeHierarchy::new())
                })
                .collect();

            (process_node_id, process_children)
        });

        // Add things hierarchy
        let thing_hierarchy = Self::convert_thing_hierarchy_to_node_hierarchy(thing_hierarchy);

        tag_entries
            .chain(process_entries)
            .chain(thing_hierarchy)
            .collect()
    }

    /// Recursively convert ThingHierarchy to NodeHierarchy.
    fn convert_thing_hierarchy_to_node_hierarchy<'id>(
        thing_hierarchy: &InputThingHierarchy<'id>,
    ) -> NodeHierarchy<'id> {
        thing_hierarchy
            .iter()
            .map(|(thing_id, children)| {
                let node_id = NodeId::from(thing_id.as_ref().clone());
                let child_hierarchy = Self::convert_thing_hierarchy_to_node_hierarchy(children);
                (node_id, child_hierarchy)
            })
            .collect()
    }

    // === Node Ordering === //

    /// Build NodeOrdering from things, tags, and processes.
    ///
    /// The map order defines the rendering order in the SVG:
    /// 1. Tags (for CSS peer selector ordering)
    /// 2. Processes (must come before process steps for peer styling)
    /// 3. Process steps
    /// 4. Things (in hierarchy order)
    ///
    /// The tab indices are calculated for keyboard navigation:
    /// 1. Things (starting from 1, in declaration order)
    /// 2. Processes and their steps (process first, then its steps)
    /// 3. Tags (at the end)
    fn build_node_ordering<'id>(
        things: &InputThingHierarchy<'id>,
        tags: &TagNames<'id>,
        processes: &Processes<'id>,
    ) -> NodeOrdering<'id> {
        // First, calculate tab indices in the user-expected order:
        // things, then processes with their steps, then tags
        let mut tab_index: u32 = 1;

        // Collect things tab indices in hierarchy order (depth-first)
        let mut tab_indices = Map::<&Id<'id>, u32>::new();
        Self::collect_thing_tab_indices_recursive(things, &mut tab_index, &mut tab_indices);

        // Collect process and step tab indices
        let mut process_step_count = 0;
        processes.iter().for_each(|(process_id, process_diagram)| {
            tab_indices.insert(process_id.as_ref(), tab_index);
            tab_index += 1;

            process_diagram.steps.keys().for_each(|step_id| {
                tab_indices.insert(step_id.as_ref(), tab_index);
                tab_index += 1;
            });

            process_step_count += process_diagram.steps.len();
        });

        // Collect tag tab indices
        tags.keys().for_each(|tag_id| {
            tab_indices.insert(tag_id.as_ref(), tab_index);
            tab_index += 1;
        });

        // Now build the NodeOrdering map in rendering order:
        // tags, then process steps, then processes, then things
        let mut node_ordering = NodeOrdering::with_capacity(
            tags.len() + processes.len() + process_step_count + things.total_descendants(),
        );

        // 1. Tags first (for CSS peer selector ordering)
        tags.keys().for_each(|tag_id| {
            let tab_idx = tab_indices.get(tag_id.as_ref()).copied().unwrap_or(0);
            let tag_node_id = NodeId::from(tag_id.as_ref().clone());
            node_ordering.insert(tag_node_id, tab_idx);
        });

        // 2. Processes (must come before process steps for peer styling)
        processes.keys().for_each(|process_id| {
            let process_node_id = NodeId::from(process_id.as_ref().clone());
            let tab_idx = tab_indices
                .get(process_node_id.as_ref())
                .copied()
                .unwrap_or(0);
            node_ordering.insert(process_node_id, tab_idx);
        });

        // 3. Process steps
        processes.values().for_each(|process_diagram| {
            process_diagram.steps.keys().for_each(|step_id| {
                let process_step_node_id = NodeId::from(step_id.as_ref().clone());
                let tab_idx = tab_indices
                    .get(process_step_node_id.as_ref())
                    .copied()
                    .unwrap_or(0);
                node_ordering.insert(process_step_node_id, tab_idx);
            });
        });

        // 4. Things (in hierarchy order)
        Self::add_things_to_ordering_recursive(things, &tab_indices, &mut node_ordering);

        node_ordering
    }

    /// Recursively collect tab indices for things in hierarchy order.
    fn collect_thing_tab_indices_recursive<'f, 'id>(
        thing_hierarchy: &'f InputThingHierarchy<'id>,
        tab_index: &mut u32,
        tab_indices: &mut Map<&'f Id<'id>, u32>,
    ) {
        thing_hierarchy.iter().for_each(|(thing_id, children)| {
            tab_indices.insert(thing_id.as_ref(), *tab_index);
            *tab_index += 1;

            // Recurse into children
            Self::collect_thing_tab_indices_recursive(children, tab_index, tab_indices);
        });
    }

    /// Recursively add things to ordering in hierarchy order.
    fn add_things_to_ordering_recursive<'f, 'id>(
        thing_hierarchy: &'f InputThingHierarchy<'id>,
        thing_tab_indices: &Map<&'f Id<'id>, u32>,
        node_ordering: &mut NodeOrdering<'id>,
    ) {
        thing_hierarchy.iter().for_each(|(thing_id, children)| {
            let thing_node_id = NodeId::from(thing_id.as_ref().clone());
            let tab_idx = thing_tab_indices
                .get(thing_node_id.as_ref())
                .copied()
                .unwrap_or(0);
            node_ordering.insert(thing_node_id, tab_idx);

            // Recurse into children
            Self::add_things_to_ordering_recursive(children, thing_tab_indices, node_ordering);
        });
    }

    // === Edge Groups === //

    /// Build EdgeGroups from thing_dependencies and thing_interactions.
    fn build_edge_groups<'id>(
        thing_dependencies: &ThingDependencies<'id>,
        thing_interactions: &ThingInteractions<'id>,
    ) -> EdgeGroups<'id> {
        // Process thing_dependencies
        let dependency_entries =
            thing_dependencies
                .iter()
                .map(|(edge_group_id, input_edge_group)| {
                    (
                        edge_group_id.clone(),
                        Self::input_edge_group_to_edges(input_edge_group),
                    )
                });

        // Process thing_interactions (only add if not already present from
        // dependencies)
        let interaction_entries = thing_interactions
            .iter()
            .filter(|(edge_group_id, _)| !thing_dependencies.contains_key(edge_group_id))
            .map(|(edge_group_id, input_edge_group)| {
                (
                    edge_group_id.clone(),
                    Self::input_edge_group_to_edges(input_edge_group),
                )
            });

        dependency_entries.chain(interaction_entries).collect()
    }

    /// Convert an [`InputEdgeGroup`] to a list of [`Edge`]s.
    fn input_edge_group_to_edges<'id>(input_edge_group: &InputEdgeGroup<'id>) -> EdgeGroup<'id> {
        let things = &input_edge_group.things;
        let edges: Vec<Edge> = Self::edge_kind_to_edges(input_edge_group.kind, things);

        EdgeGroup::from(edges)
    }

    /// Convert an [`EdgeKind`] and a list of things to a list of [`Edge`]s.
    fn edge_kind_to_edges<'id>(edge_kind: EdgeKind, things: &[ThingId<'id>]) -> Vec<Edge<'id>> {
        match edge_kind {
            EdgeKind::Cyclic => {
                // Create edges from each thing to the next, and from last back to first
                things
                    .iter()
                    .enumerate()
                    .map(|(index, thing)| {
                        let from_id = NodeId::from(thing.as_ref().clone());
                        let to_idx = (index + 1) % things.len();
                        let to_id = NodeId::from(things[to_idx].as_ref().clone());
                        Edge::new(from_id, to_id)
                    })
                    .collect()
            }
            EdgeKind::Sequence => {
                // Create edges from each thing to the next (no cycle back)
                things
                    .windows(2)
                    .map(|pair| {
                        let from_id = NodeId::from(pair[0].as_ref().clone());
                        let to_id = NodeId::from(pair[1].as_ref().clone());
                        Edge::new(from_id, to_id)
                    })
                    .collect()
            }
            EdgeKind::Symmetric => {
                // Create edges from each thing to the next, then back from last to first
                // For [A, B, C]: A -> B -> C -> B -> A
                // For [A] (1 thing): A -> A (request), A -> A (response)
                if things.len() == 1 {
                    // Special case: 1 thing creates 2 self-loop edges (request and response)
                    let node_id = NodeId::from(things[0].as_ref().clone());
                    vec![
                        Edge::new(node_id.clone(), node_id.clone()),
                        Edge::new(node_id.clone(), node_id),
                    ]
                } else {
                    let forward: Vec<Edge> = things
                        .windows(2)
                        .map(|pair| {
                            let from_id = NodeId::from(pair[0].as_ref().clone());
                            let to_id = NodeId::from(pair[1].as_ref().clone());
                            Edge::new(from_id, to_id)
                        })
                        .collect();

                    let reverse: Vec<Edge> = things
                        .windows(2)
                        .rev()
                        .map(|pair| {
                            let from_id = NodeId::from(pair[1].as_ref().clone());
                            let to_id = NodeId::from(pair[0].as_ref().clone());
                            Edge::new(from_id, to_id)
                        })
                        .collect();

                    forward.into_iter().chain(reverse).collect()
                }
            }
        }
    }

    // === Entity Types === //

    /// Build EntityTypes with defaults for each node type.
    fn build_entity_types<'id>(
        things: &InputThingHierarchy<'id>,
        tags: &TagNames<'id>,
        processes: &Processes<'id>,
        input_entity_types: &EntityTypes<'id>,
        thing_dependencies: &ThingDependencies<'id>,
        thing_interactions: &ThingInteractions<'id>,
    ) -> EntityTypes<'id> {
        // Helper to build types vector with default and optional custom types
        let build_types = |id: &Id<'id>, default_type: EntityType| {
            let mut types = Set::new();
            types.insert(default_type);
            if let Some(custom_types) = input_entity_types.get(id) {
                types.extend(custom_types.iter().cloned());
            }
            types
        };

        // Add things with type_thing_default + any custom type
        let thing_entries = things.thing_ids_recursive().into_iter().map(|thing_id| {
            let id: Id = thing_id.as_ref().clone();
            let types = build_types(&id, EntityType::ThingDefault);
            (id, types)
        });

        // Add tags with tag_type_default
        let tag_entries = tags.keys().map(|tag_id| {
            let id: Id = tag_id.as_ref().clone();
            let types = build_types(&id, EntityType::TagDefault);
            (id, types)
        });

        // Add processes with type_process_default and their steps
        let process_entries = processes.iter().flat_map(|(process_id, process_diagram)| {
            let process_id_inner: Id = process_id.as_ref().clone();
            let process_types = build_types(&process_id_inner, EntityType::ProcessDefault);

            // Add process steps with type_process_step_default
            let step_entries = process_diagram.steps.keys().map(|step_id| {
                let id: Id = step_id.as_ref().clone();
                let types = build_types(&id, EntityType::ProcessStepDefault);
                (id, types)
            });

            std::iter::once((process_id_inner, process_types)).chain(step_entries)
        });

        // node inbuilt types
        let node_inbuilt_types = enum_iterator::all::<NodeInbuilt>().map(|node_inbuilt| {
            let mut entity_types = Set::with_capacity(1);
            entity_types.insert(node_inbuilt.entity_type());

            (node_inbuilt.id(), entity_types)
        });

        let mut entity_types: Map<Id<'id>, Set<EntityType>> = node_inbuilt_types
            .chain(thing_entries)
            .chain(tag_entries)
            .chain(process_entries)
            .collect();

        // Add edge types from thing_dependencies
        Self::build_entity_types_dependencies(
            &mut entity_types,
            thing_dependencies,
            input_entity_types,
        );

        // Add edge types from thing_interactions (will merge with existing)
        Self::build_entity_types_interactions(
            &mut entity_types,
            thing_interactions,
            input_entity_types,
        );

        EntityTypes::from(entity_types)
    }

    /// Add edge types from dependencies.
    fn build_entity_types_dependencies<'id>(
        entity_types: &mut Map<Id<'id>, Set<EntityType>>,
        thing_deps: &ThingDependencies<'id>,
        input_entity_types: &EntityTypes<'id>,
    ) {
        let edge_group_entries = thing_deps
            .iter()
            .flat_map(|(edge_group_id, input_edge_group)| {
                let edge_kind = input_edge_group.kind;
                let things = &input_edge_group.things;

                // edge group entity types
                let edge_group_entity_types = Self::build_entity_types_for_edge_groups(
                    input_entity_types,
                    edge_group_id,
                    edge_kind,
                    Self::edge_group_default_type_dependency,
                );

                // edge entity types
                let edge_entity_types = Self::build_entity_types_for_edges(
                    input_entity_types,
                    edge_group_id,
                    edge_kind,
                    things,
                    Self::edge_default_type_dependency,
                );
                std::iter::once(edge_group_entity_types).chain(edge_entity_types)
            });

        entity_types.extend(edge_group_entries);
    }

    /// Add interaction types to existing edge types.
    fn build_entity_types_interactions<'id>(
        entity_types: &mut Map<Id<'id>, Set<EntityType>>,
        thing_interactions: &ThingInteractions<'id>,
        input_entity_types: &EntityTypes<'id>,
    ) {
        let edge_group_entries =
            thing_interactions
                .iter()
                .flat_map(|(edge_group_id, input_edge_group)| {
                    let edge_kind = input_edge_group.kind;
                    let things = &input_edge_group.things;

                    // edge group entity types
                    let edge_group_entity_types = Self::build_entity_types_for_edge_groups(
                        input_entity_types,
                        edge_group_id,
                        edge_kind,
                        Self::edge_group_default_type_interaction,
                    );

                    // edge entity types
                    let edge_entity_types = Self::build_entity_types_for_edges(
                        input_entity_types,
                        edge_group_id,
                        edge_kind,
                        things,
                        Self::edge_default_type_interaction,
                    );
                    std::iter::once(edge_group_entity_types).chain(edge_entity_types)
                });

        entity_types.extend(edge_group_entries);
    }

    fn build_entity_types_for_edge_groups<'id>(
        input_entity_types: &EntityTypes<'id>,
        edge_group_id: &EdgeGroupId<'id>,
        edge_kind: EdgeKind,
        edge_group_default_type_fn: fn(EdgeKind) -> EntityType,
    ) -> (Id<'id>, Set<EntityType>) {
        let edge_group_id: Id<'id> = edge_group_id.as_ref().clone();

        let edge_group_default_type = edge_group_default_type_fn(edge_kind);

        let mut types = Set::new();
        types.insert(edge_group_default_type);

        if let Some(custom_types) = input_entity_types.get(&edge_group_id) {
            types.extend(custom_types.iter().cloned());
        }

        (edge_group_id, types)
    }

    fn edge_group_default_type_dependency(edge_kind: EdgeKind) -> EntityType {
        match edge_kind {
            EdgeKind::Cyclic => EntityType::DependencyEdgeCyclicDefault,
            EdgeKind::Sequence => EntityType::DependencyEdgeSequenceDefault,
            EdgeKind::Symmetric => EntityType::DependencyEdgeSymmetricDefault,
        }
    }

    fn edge_default_type_dependency(
        edge_kind: EdgeKind,
        forward_count: usize,
        i: usize,
    ) -> EntityType {
        match edge_kind {
            EdgeKind::Cyclic => EntityType::DependencyEdgeCyclicForwardDefault,
            EdgeKind::Sequence => EntityType::DependencyEdgeSequenceForwardDefault,
            EdgeKind::Symmetric => {
                // First half are forward, second half are reverse
                if i < forward_count {
                    EntityType::DependencyEdgeSymmetricForwardDefault
                } else {
                    EntityType::DependencyEdgeSymmetricReverseDefault
                }
            }
        }
    }

    fn edge_group_default_type_interaction(edge_kind: EdgeKind) -> EntityType {
        match edge_kind {
            EdgeKind::Cyclic => EntityType::InteractionEdgeCyclicDefault,
            EdgeKind::Sequence => EntityType::InteractionEdgeSequenceDefault,
            EdgeKind::Symmetric => EntityType::InteractionEdgeSymmetricDefault,
        }
    }

    fn edge_default_type_interaction(
        edge_kind: EdgeKind,
        forward_count: usize,
        i: usize,
    ) -> EntityType {
        match edge_kind {
            EdgeKind::Cyclic => EntityType::InteractionEdgeCyclicForwardDefault,
            EdgeKind::Sequence => EntityType::InteractionEdgeSequenceForwardDefault,
            EdgeKind::Symmetric => {
                // First half are forward, second half are reverse
                if i < forward_count {
                    EntityType::InteractionEdgeSymmetricForwardDefault
                } else {
                    EntityType::InteractionEdgeSymmetricReverseDefault
                }
            }
        }
    }

    fn build_entity_types_for_edges<'id>(
        input_entity_types: &EntityTypes<'id>,
        edge_group_id: &EdgeGroupId<'id>,
        edge_kind: EdgeKind,
        things: &[ThingId<'id>],
        edge_default_type_fn: fn(EdgeKind, usize, usize) -> EntityType,
    ) -> impl Iterator<Item = (Id<'id>, Set<EntityType>)> {
        let (edge_count, forward_count) = match edge_kind {
            EdgeKind::Cyclic => (things.len(), things.len()),
            EdgeKind::Sequence => {
                let count = things.len().saturating_sub(1);
                (count, count)
            }
            EdgeKind::Symmetric => {
                // Forward edges + reverse edges
                // For 1 thing: 2 edges (1 request, 1 response)
                // For n things: (n-1) forward + (n-1) reverse
                let forward = things.len().max(1).saturating_sub(1).max(1);
                let total = if things.len() <= 1 { 2 } else { forward * 2 };
                (total, forward)
            }
        };

        (0..edge_count).map(move |i| {
            // Edge ID format: edge_group_id__index
            let edge_id_str = format!("{edge_group_id}__{i}");
            let edge_id = Self::id_from_string(edge_id_str);

            let edge_default_type = edge_default_type_fn(edge_kind, forward_count, i);

            let mut types = Set::new();
            types.insert(edge_default_type);

            if let Some(custom_types) = input_entity_types.get(&edge_id) {
                types.extend(custom_types.iter().cloned());
            }

            (edge_id, types)
        })
    }

    // === Node Layouts === //

    /// Build NodeLayouts from node_hierarchy and theme data.
    #[allow(clippy::too_many_arguments)]
    fn build_node_layouts<'id>(
        node_hierarchy: &NodeHierarchy<'id>,
        flex_direction_default: FlexDirection,
        theme_ctx: ThemeResolveCtx<'_, 'id>,
        tags: &TagNames<'id>,
        processes: &Processes<'id>,
        thing_layouts: &ThingLayouts<'id>,
    ) -> NodeLayouts<'id> {
        let mut node_layouts = NodeLayouts::new();

        // Helper to determine if a node is a tag
        let is_tag = |node_id: &NodeId<'id>| tags.contains_key(node_id);

        // Helper to determine if a node is a process
        let is_process = |node_id: &NodeId<'id>| processes.contains_key(node_id);

        // 1-3. Inbuilt top-level containers.
        Self::inbuilt_container_layout_insert(
            &mut node_layouts,
            NodeInbuilt::Root,
            FlexDirection::ColumnReverse,
            thing_layouts,
            theme_ctx,
        );
        Self::inbuilt_container_layout_insert(
            &mut node_layouts,
            NodeInbuilt::ThingsAndProcessesContainer,
            FlexDirection::RowReverse,
            thing_layouts,
            theme_ctx,
        );
        Self::inbuilt_container_layout_insert(
            &mut node_layouts,
            NodeInbuilt::ProcessesContainer,
            FlexDirection::Column,
            thing_layouts,
            theme_ctx,
        );

        // 4. Build layouts for all processes and their steps.
        node_layouts.extend(Self::process_node_layouts_build(processes, theme_ctx));

        // 5. Tags container.
        Self::inbuilt_container_layout_insert(
            &mut node_layouts,
            NodeInbuilt::TagsContainer,
            FlexDirection::Row,
            thing_layouts,
            theme_ctx,
        );

        // 6. Tags are always leaves.
        node_layouts.extend(Self::tag_node_layouts_build(tags, theme_ctx));

        // 7. Things container.
        Self::inbuilt_container_layout_insert(
            &mut node_layouts,
            NodeInbuilt::ThingsContainer,
            flex_direction_default,
            thing_layouts,
            theme_ctx,
        );

        // 8. Build layouts for all things in hierarchy.
        Self::build_thing_layouts(
            node_hierarchy,
            flex_direction_default,
            theme_ctx,
            &mut node_layouts,
            &is_tag,
            &is_process,
            thing_layouts,
        );

        node_layouts
    }

    /// Builds and inserts the flex layout for an inbuilt container node.
    ///
    /// The container's flex direction comes from `thing_layouts` if the user
    /// specified one, otherwise `direction_default`.
    fn inbuilt_container_layout_insert<'id>(
        node_layouts: &mut NodeLayouts<'id>,
        inbuilt: NodeInbuilt,
        direction_default: FlexDirection,
        thing_layouts: &ThingLayouts<'id>,
        theme_ctx: ThemeResolveCtx<'_, 'id>,
    ) {
        let container_id = inbuilt.id();
        let direction = thing_layouts
            .get(&container_id)
            .copied()
            .unwrap_or(direction_default);
        let layout = Self::build_container_layout(&container_id, direction, false, theme_ctx);
        node_layouts.insert(NodeId::from(container_id), layout);
    }

    /// Builds the layouts for every process node and its step nodes.
    ///
    /// Processes with steps get a flex (column) layout; step nodes are always
    /// leaves.
    fn process_node_layouts_build<'id>(
        processes: &Processes<'id>,
        theme_ctx: ThemeResolveCtx<'_, 'id>,
    ) -> Vec<(NodeId<'id>, NodeLayout)> {
        processes
            .iter()
            .flat_map(|(process_id, process_diagram)| {
                let process_node_id = NodeId::from(process_id.as_ref().clone());

                // Processes with steps get flex layout (column direction)
                let process_layout = if !process_diagram.steps.is_empty() {
                    Self::build_node_flex_layout(
                        process_node_id.clone().into_inner(),
                        FlexDirection::Column,
                        false,
                        theme_ctx,
                    )
                } else {
                    Self::build_node_leaf_layout(process_node_id.clone().into_inner(), theme_ctx)
                };

                // Process steps are always leaves (no children)
                let step_layouts = process_diagram.steps.keys().map(move |step_id| {
                    let step_node_id = NodeId::from(step_id.as_ref().clone());
                    let step_node_layout =
                        Self::build_node_leaf_layout(step_id.clone().into_inner(), theme_ctx);
                    (step_node_id, step_node_layout)
                });

                std::iter::once((process_node_id, process_layout)).chain(step_layouts)
            })
            .collect()
    }

    /// Builds the leaf layouts for every tag node.
    fn tag_node_layouts_build<'id>(
        tags: &TagNames<'id>,
        theme_ctx: ThemeResolveCtx<'_, 'id>,
    ) -> Vec<(NodeId<'id>, NodeLayout)> {
        tags.keys()
            .map(|tag_id| {
                let tag_node_id = NodeId::from(tag_id.as_ref().clone());
                let tag_node_layout =
                    Self::build_node_leaf_layout(tag_id.clone().into_inner(), theme_ctx);
                (tag_node_id, tag_node_layout)
            })
            .collect()
    }

    /// Build a container layout with specified direction.
    fn build_container_layout<'id>(
        container_id: &Id<'id>,
        direction: FlexDirection,
        wrap: bool,
        theme_ctx: ThemeResolveCtx<'_, 'id>,
    ) -> NodeLayout {
        let ThemeResolveCtx {
            entity_types,
            theme_default,
            theme_types_styles,
        } = theme_ctx;
        let (padding_top, padding_right, padding_bottom, padding_left) =
            ThemeAttrResolver::resolve_padding(
                Some(container_id),
                entity_types,
                theme_default,
                theme_types_styles,
            );
        let (margin_top, margin_right, margin_bottom, margin_left) =
            ThemeAttrResolver::resolve_margin(
                Some(container_id),
                entity_types,
                theme_default,
                theme_types_styles,
            );
        let gap = ThemeAttrResolver::resolve_gap(
            Some(container_id),
            entity_types,
            theme_default,
            theme_types_styles,
        );

        NodeLayout::Flex(FlexLayout {
            direction,
            wrap,
            padding_top,
            padding_right,
            padding_bottom,
            padding_left,
            margin_top,
            margin_right,
            margin_bottom,
            margin_left,
            gap,
        })
    }

    /// Build a flex layout for a specific node.
    fn build_node_flex_layout<'id>(
        id: Id<'id>,
        direction: FlexDirection,
        wrap: bool,
        theme_ctx: ThemeResolveCtx<'_, 'id>,
    ) -> NodeLayout {
        let ThemeResolveCtx {
            entity_types,
            theme_default,
            theme_types_styles,
        } = theme_ctx;
        let (padding_top, padding_right, padding_bottom, padding_left) =
            ThemeAttrResolver::resolve_padding(
                Some(&id),
                entity_types,
                theme_default,
                theme_types_styles,
            );
        let (margin_top, margin_right, margin_bottom, margin_left) =
            ThemeAttrResolver::resolve_margin(
                Some(&id),
                entity_types,
                theme_default,
                theme_types_styles,
            );
        let gap = ThemeAttrResolver::resolve_gap(
            Some(&id),
            entity_types,
            theme_default,
            theme_types_styles,
        );

        NodeLayout::Flex(FlexLayout {
            direction,
            wrap,
            padding_top,
            padding_right,
            padding_bottom,
            padding_left,
            margin_top,
            margin_right,
            margin_bottom,
            margin_left,
            gap,
        })
    }

    /// Build a leaf layout for a specific node.
    fn build_node_leaf_layout<'id>(id: Id<'id>, theme_ctx: ThemeResolveCtx<'_, 'id>) -> NodeLayout {
        let ThemeResolveCtx {
            entity_types,
            theme_default,
            theme_types_styles,
        } = theme_ctx;
        let (padding_top, padding_right, padding_bottom, padding_left) =
            ThemeAttrResolver::resolve_padding(
                Some(&id),
                entity_types,
                theme_default,
                theme_types_styles,
            );
        let (margin_top, margin_right, margin_bottom, margin_left) =
            ThemeAttrResolver::resolve_margin(
                Some(&id),
                entity_types,
                theme_default,
                theme_types_styles,
            );

        NodeLayout::Leaf(LeafLayout {
            padding_top,
            padding_right,
            padding_bottom,
            padding_left,
            margin_top,
            margin_right,
            margin_bottom,
            margin_left,
        })
    }

    /// Recursively build layouts for things in the hierarchy.
    fn build_thing_layouts<'id, F, G>(
        hierarchy: &NodeHierarchy<'id>,
        flex_direction_default: FlexDirection,
        theme_ctx: ThemeResolveCtx<'_, 'id>,
        node_layouts: &mut NodeLayouts<'id>,
        is_tag: &F,
        is_process: &G,
        thing_layouts: &ThingLayouts<'id>,
    ) where
        F: Fn(&NodeId<'id>) -> bool,
        G: Fn(&NodeId<'id>) -> bool,
    {
        let thing_layout_entries: Vec<_> = hierarchy
            .iter()
            // Skip tags and processes (already handled)
            .filter(|(node_id, _)| !is_tag(node_id) && !is_process(node_id))
            .flat_map(|(node_id, children)| {
                let layout = if children.is_empty() {
                    // Leaf node
                    Self::build_node_leaf_layout(node_id.clone().into_inner(), theme_ctx)
                } else {
                    // Container node -- use flex layout.
                    //
                    // If the user specified a direction in `thing_layouts`, use
                    // that. Otherwise alternate based on depth: column at even
                    // depths, row at odd depths.
                    let thing_id = node_id.as_ref().clone();
                    let direction = thing_layouts
                        .get(&thing_id)
                        .copied()
                        .unwrap_or(flex_direction_default);

                    Self::build_node_flex_layout(
                        node_id.clone().into_inner(),
                        direction,
                        false,
                        theme_ctx,
                    )
                };

                // Collect children info for recursive processing
                let children_to_process = if !children.is_empty() {
                    Some(children.clone())
                } else {
                    None
                };

                std::iter::once((node_id.clone(), layout, children_to_process))
            })
            .collect();

        // Insert layouts and recursively process children
        thing_layout_entries
            .into_iter()
            .for_each(|(node_id, layout, children_opt)| {
                node_layouts.insert(node_id, layout);

                if let Some(children) = children_opt {
                    Self::build_thing_layouts(
                        &children,
                        flex_direction_default,
                        theme_ctx,
                        node_layouts,
                        is_tag,
                        is_process,
                        thing_layouts,
                    );
                }
            });
    }

    // === Node Shapes === //

    /// Build NodeShapes for all nodes from theme data.
    ///
    /// This extracts the corner radius values from the theme configuration
    /// for each node and creates a `NodeShape` (currently `Rect` with corner
    /// radii).
    fn build_node_shapes<'id>(
        nodes: &NodeNames<'id>,
        entity_types: &EntityTypes<'id>,
        theme_default: &ThemeDefault<'id>,
        theme_types_styles: &ThemeTypesStyles<'id>,
    ) -> NodeShapes<'id> {
        nodes
            .iter()
            .map(|(node_id, _name)| {
                let id: Id<'id> = node_id.as_ref().clone();
                let shape = ThemeAttrResolver::resolve_node_shape(
                    &id,
                    entity_types,
                    theme_default,
                    theme_types_styles,
                );
                (node_id.clone(), shape)
            })
            .collect()
    }

    // === Process Step Entities === //

    /// Build [`ProcessStepEntities`] from the process step thing interactions.
    ///
    /// For each process step, collects the edge group IDs it interacts with
    /// and stores them as `Id`s keyed by the process step's `NodeId`.
    fn build_process_step_entities<'id>(processes: &Processes<'id>) -> ProcessStepEntities<'id> {
        processes
            .iter()
            .flat_map(|(_process_id, process_diagram)| {
                process_diagram
                    .step_thing_interactions
                    .iter()
                    .map(|(step_id, edge_group_ids)| {
                        let node_id = NodeId::from(step_id.as_ref().clone());
                        let entity_ids: Vec<Id<'id>> = edge_group_ids
                            .iter()
                            .map(|edge_group_id| edge_group_id.as_ref().clone())
                            .collect();
                        (node_id, entity_ids)
                    })
            })
            .collect()
    }

    // === Process Step Edges === //

    /// Build [`ProcessStepEdges`] from each process's
    /// `process_step_dependencies`.
    fn build_process_step_edges<'id>(processes: &Processes<'id>) -> ProcessStepEdges<'id> {
        processes
            .values()
            .flat_map(Self::process_step_edges_for_process)
            .collect()
    }

    /// Returns the process step edges for a single process.
    ///
    /// When `process_step_dependencies` is defined, an edge is created from
    /// each dependency (prerequisite) to the dependent step, so the dependent
    /// step is ranked after its prerequisites.
    ///
    /// When `process_step_dependencies` is empty, linear dependencies are
    /// assumed in process step declaration order -- each step depends on the
    /// step declared immediately before it.
    fn process_step_edges_for_process<'id>(
        process_diagram: &ProcessDiagram<'id>,
    ) -> Vec<Edge<'id>> {
        if process_diagram.process_step_dependencies.is_empty() {
            let step_node_ids: Vec<NodeId<'id>> = process_diagram
                .steps
                .keys()
                .map(|step_id| NodeId::from(step_id.as_ref().clone()))
                .collect();

            step_node_ids
                .windows(2)
                .map(|pair| Edge::new(pair[0].clone(), pair[1].clone()))
                .collect()
        } else {
            process_diagram
                .process_step_dependencies
                .iter()
                .flat_map(|(step_id, dependency_ids)| {
                    let to_id = NodeId::from(step_id.as_ref().clone());
                    dependency_ids.iter().map(move |dependency_id| {
                        let from_id = NodeId::from(dependency_id.as_ref().clone());
                        Edge::new(from_id, to_id.clone())
                    })
                })
                .collect()
        }
    }

    // === Process Step Ranks === //

    /// Build [`ProcessStepRanks`] from process steps and their edges.
    ///
    /// Steps that depend on other steps receive a higher rank. Steps with no
    /// dependencies default to rank `0`. Ranks are computed via a longest-path
    /// topological ordering (Kahn's algorithm) over the process step edges.
    fn build_process_step_ranks<'id>(
        processes: &Processes<'id>,
        process_step_edges: &ProcessStepEdges<'id>,
    ) -> ProcessStepRanks<'id> {
        // Collect all process step node IDs in declaration order so that steps
        // without dependencies still receive a rank.
        let step_node_ids: Vec<NodeId<'id>> = processes
            .values()
            .flat_map(|process_diagram| process_diagram.steps.keys())
            .map(|step_id| NodeId::from(step_id.as_ref().clone()))
            .collect();
        let node_count = step_node_ids.len();

        // Assign each step node a numeric index.
        let node_to_index: Map<NodeId<'id>, usize> = step_node_ids
            .iter()
            .enumerate()
            .map(|(index, node_id)| (node_id.clone(), index))
            .collect();

        // Build adjacency list and in-degrees from the process step edges.
        let (adjacency, mut in_degree) = process_step_edges.iter().fold(
            (vec![Vec::new(); node_count], vec![0usize; node_count]),
            |(mut adjacency, mut in_degree), edge| {
                if let (Some(&from_idx), Some(&to_idx)) =
                    (node_to_index.get(&edge.from), node_to_index.get(&edge.to))
                {
                    adjacency[from_idx].push(to_idx);
                    in_degree[to_idx] += 1;
                }
                (adjacency, in_degree)
            },
        );

        // Longest-path ranks via Kahn's algorithm. Nodes that remain part of a
        // cycle are never dequeued and keep their default rank of `0`.
        let mut ranks: Vec<u32> = vec![0; node_count];
        let mut queue: std::collections::VecDeque<usize> = in_degree
            .iter()
            .enumerate()
            .filter(|(_index, in_degree_item)| **in_degree_item == 0)
            .map(|(index, _in_degree_item)| index)
            .collect();
        while let Some(from_idx) = queue.pop_front() {
            for &to_idx in &adjacency[from_idx] {
                let candidate_rank = ranks[from_idx] + 1;
                if candidate_rank > ranks[to_idx] {
                    ranks[to_idx] = candidate_rank;
                }
                in_degree[to_idx] -= 1;
                if in_degree[to_idx] == 0 {
                    queue.push_back(to_idx);
                }
            }
        }

        step_node_ids
            .into_iter()
            .enumerate()
            .map(|(index, node_id)| (node_id, ProcessStepRank::new(ranks[index])))
            .collect()
    }
}