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
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
use std::{borrow::Cow, collections::BTreeMap};
use disposition_ir_model::{
edge::{EdgeFaceAssignments, EdgeGroups, EdgeId},
entity::{EntityDescs, EntityType, EntityTypes},
layout::{FlexDirection as ModelFlexDirection, NodeLayout, NodeLayouts},
node::{
NodeFace, NodeFaceEdges, NodeHierarchy, NodeId, NodeInbuilt, NodeNames, NodeNestingInfos,
NodeRank, NodeRanksNested, NodeShape, NodeShapes,
},
IrDiagram,
};
use disposition_model_common::{Id, Map};
use disposition_taffy_model::{
taffy::{
self,
style::{FlexDirection, LengthPercentageAuto},
AlignContent, AlignItems, AvailableSpace, Display, FlexWrap, LengthPercentage, Rect, Size,
Style, TaffyTree,
},
DiagramLod, DiagramNodeCtx, Dimension, DimensionAndLod, EdgeLabelCtx, EdgeLabelTaffyNodeIds,
EdgeSpacerTaffyNodes, EntityHighlightedSpan, EntityHighlightedSpans, IrToTaffyError,
NodeToTaffyNodeIds, ProcessesIncluded, TaffyNodeCtx, TaffyNodeMappings, TEXT_FONT_SIZE,
TEXT_LINE_HEIGHT,
};
use taffy::{prelude::TaffyZero, JustifyContent, JustifyItems};
use typed_builder::TypedBuilder;
use self::{
edge_lca_sibling_distance::EdgeLcaSiblingDistance,
edge_spacer_builder::EdgeSpacerBuilder,
taffy_node_build_context::{
EdgeLabelLeafBuilt, NodeMeasureContext, TaffyNodeBuildContext, TaffyWrapperNodeStyles,
},
text_measure::{
compute_text_dimensions, line_width_measure, wrap_text_monospace,
MONOSPACE_CHAR_WIDTH_RATIO,
},
};
mod edge_lca_sibling_distance;
mod edge_spacer_builder;
mod taffy_node_build_context;
mod text_measure;
type NodeRankToTaffyNodeId = BTreeMap<NodeRank, Vec<taffy::NodeId>>;
/// Converts a model [`FlexDirection`](ModelFlexDirection) to a
/// [`taffy::style::FlexDirection`].
fn flex_direction_to_taffy(direction: ModelFlexDirection) -> FlexDirection {
match direction {
ModelFlexDirection::Row => FlexDirection::Row,
ModelFlexDirection::RowReverse => FlexDirection::RowReverse,
ModelFlexDirection::Column => FlexDirection::Column,
ModelFlexDirection::ColumnReverse => FlexDirection::ColumnReverse,
}
}
/// Maps an intermediate representation diagram to a `TaffyNodeMappings`.
///
/// # Examples
///
/// ```rust
/// # use disposition_input_ir_rt::IrToTaffyBuilder;
/// # use disposition_ir_model::IrDiagram;
/// # use disposition_taffy_model::DimensionAndLod;
/// #
/// let ir_diagram = IrDiagram::new();
/// let dimension_and_lods = vec![DimensionAndLod::default_lg()];
///
/// let mut taffy_trees = IrToTaffyBuilder::builder()
/// .with_ir_diagram(&ir_diagram)
/// .with_dimension_and_lods(dimension_and_lods)
/// .build();
/// ```
#[derive(Debug, TypedBuilder)]
pub struct IrToTaffyBuilder<'builder> {
/// The intermediate representation of the diagram to render the taffy trees
/// for.
#[builder(setter(prefix = "with_"))]
ir_diagram: &'builder IrDiagram<'static>,
/// The dimensions at which elements should be repositioned.
#[builder(setter(prefix = "with_"), default = vec![
DimensionAndLod::default_sm(),
DimensionAndLod::default_md(),
DimensionAndLod::default_lg(),
])]
dimension_and_lods: Vec<DimensionAndLod>,
/// What processes to create diagrams for.
#[builder(setter(prefix = "with_"), default = ProcessesIncluded::All)]
processes_included: ProcessesIncluded,
}
impl IrToTaffyBuilder<'_> {
/// Returns an iterator over `TaffyNodeMappings` instances for each
/// dimension.
pub fn build(
&self,
) -> Result<impl Iterator<Item = TaffyNodeMappings<'static>>, IrToTaffyError> {
let IrToTaffyBuilder {
ir_diagram,
dimension_and_lods,
processes_included,
} = self;
let taffy_node_mappings_iter =
dimension_and_lods
.iter()
.flat_map(move |dimension_and_lod| {
Self::build_taffy_trees_for_dimension(
ir_diagram,
dimension_and_lod,
processes_included,
)
});
Ok(taffy_node_mappings_iter)
}
/// Returns a `TaffyNodeMappings` with all processes as part of the diagram.
///
/// This includes the processes container. Clicking on each process node
/// reveals the process steps.
fn build_taffy_trees_for_dimension(
ir_diagram: &IrDiagram<'static>,
dimension_and_lod: &DimensionAndLod,
processes_included: &ProcessesIncluded,
) -> impl Iterator<Item = TaffyNodeMappings<'static>> {
let IrDiagram {
nodes,
node_copy_text: _,
node_hierarchy,
node_ordering: _,
edge_groups,
entity_descs,
entity_tooltips: _,
entity_types,
tailwind_classes: _,
node_layouts,
node_ranks_nested,
node_nesting_infos,
edge_face_assignments,
node_face_edges,
node_shapes,
process_step_entities: _,
render_options: _,
css: _,
} = ir_diagram;
let DimensionAndLod { dimension, lod } = dimension_and_lod;
let mut taffy_tree = TaffyTree::new();
let mut node_id_to_taffy = Map::new();
let mut taffy_id_to_node = Map::new();
let mut node_id_to_envelope_taffy_node: Map<NodeId<'static>, taffy::NodeId> = Map::new();
let mut edge_label_leaves: Vec<EdgeLabelLeafBuilt> = Vec::new();
let taffy_node_build_context = TaffyNodeBuildContext {
taffy_tree: &mut taffy_tree,
nodes,
node_layouts,
node_hierarchy,
entity_types,
node_shapes,
node_ranks_nested,
node_nesting_infos,
node_id_to_taffy: &mut node_id_to_taffy,
taffy_id_to_node: &mut taffy_id_to_node,
node_face_edges,
node_id_to_envelope_taffy_node: &mut node_id_to_envelope_taffy_node,
edge_label_leaves: &mut edge_label_leaves,
};
let (node_rank_to_nodes_by_entity_type, nested_edge_spacer_taffy_nodes) =
Self::build_taffy_nodes_for_first_level_nodes(
taffy_node_build_context,
processes_included,
edge_groups,
);
let mut thing_rank_to_taffy_ids = node_rank_to_nodes_by_entity_type
.get(&EntityType::ThingDefault)
.cloned()
.unwrap_or_default();
let mut tag_rank_to_taffy_ids = node_rank_to_nodes_by_entity_type
.get(&EntityType::TagDefault)
.cloned()
.unwrap_or_default();
let mut process_rank_to_taffy_ids = node_rank_to_nodes_by_entity_type
.get(&EntityType::ProcessDefault)
.cloned()
.unwrap_or_default();
// === Insert spacer taffy nodes for cross-rank edges === //
//
// For each edge that crosses multiple ranks, we insert small spacer
// leaf nodes at every intermediate rank. The edge path will later
// be routed through these spacer positions to avoid overlapping
// other nodes.
let mut edge_spacer_taffy_nodes: Map<EdgeId<'static>, EdgeSpacerTaffyNodes> = Map::new();
edge_spacer_taffy_nodes.extend(nested_edge_spacer_taffy_nodes);
edge_spacer_taffy_nodes.extend(EdgeSpacerBuilder::build(
&mut taffy_tree,
edge_groups,
node_nesting_infos,
node_ranks_nested,
entity_types,
&EntityType::ThingDefault,
&mut thing_rank_to_taffy_ids,
None,
));
edge_spacer_taffy_nodes.extend(EdgeSpacerBuilder::build(
&mut taffy_tree,
edge_groups,
node_nesting_infos,
node_ranks_nested,
entity_types,
&EntityType::TagDefault,
&mut tag_rank_to_taffy_ids,
None,
));
edge_spacer_taffy_nodes.extend(EdgeSpacerBuilder::build(
&mut taffy_tree,
edge_groups,
node_nesting_infos,
node_ranks_nested,
entity_types,
&EntityType::ProcessDefault,
&mut process_rank_to_taffy_ids,
None,
));
// Create rank sub-containers for top-level nodes, mirroring the
// rank-based child container logic used inside
// `build_taffy_nodes_for_node_with_child_hierarchy`.
//
// Each entity type gets its own set of rank containers using the
// style of its parent container.
let thing_rank_container_ids = Self::build_taffy_rank_containers_for_first_level_nodes(
&mut taffy_tree,
node_layouts,
NodeInbuilt::ThingsContainer,
thing_rank_to_taffy_ids,
);
let tag_rank_container_ids = Self::build_taffy_rank_containers_for_first_level_nodes(
&mut taffy_tree,
node_layouts,
NodeInbuilt::TagsContainer,
tag_rank_to_taffy_ids,
);
let process_rank_container_ids = Self::build_taffy_rank_containers_for_first_level_nodes(
&mut taffy_tree,
node_layouts,
NodeInbuilt::ProcessesContainer,
process_rank_to_taffy_ids,
);
let node_inbuilt_to_taffy = Self::build_taffy_container_nodes(
&mut taffy_tree,
&mut taffy_id_to_node,
node_layouts,
dimension,
&thing_rank_container_ids,
&process_rank_container_ids,
&tag_rank_container_ids,
);
let Some(root) = node_inbuilt_to_taffy.get(&NodeInbuilt::Root).copied() else {
panic!("`root` node not present in `node_inbuilt_to_taffy`.");
};
// Precompute monospace character width
let char_width = TEXT_FONT_SIZE * MONOSPACE_CHAR_WIDTH_RATIO;
// Compute layout (size measurement only, no syntax highlighting)
let mut node_measure_context = NodeMeasureContext {
nodes,
entity_descs,
char_width,
lod,
};
taffy_tree
.compute_layout_with_measure(
root,
Size::<AvailableSpace> {
width: AvailableSpace::Definite(dimension.width()),
height: AvailableSpace::Definite(dimension.height()),
},
|known_dimensions, available_space, _taffy_node_id, taffy_node_ctx, style| {
Self::node_size_measure(
&mut node_measure_context,
known_dimensions,
available_space,
taffy_node_ctx,
style,
)
},
)
.expect("Expected layout computation to succeed.");
// Merge collected edge label leaf nodes into the edge label taffy node
// map now that all envelope nodes have been built.
let edge_label_taffy_nodes = Self::edge_label_taffy_nodes_build(
edge_label_leaves,
edge_face_assignments,
edge_groups,
);
// Compute highlighted spans *after* layout is complete.
//
// This is done once per node instead of multiple times during layout
// measurement
let entity_highlighted_spans = Self::highlighted_spans_compute(
&taffy_tree,
&node_id_to_taffy,
&edge_label_taffy_nodes,
nodes,
entity_descs,
char_width,
lod,
);
std::iter::once(TaffyNodeMappings {
taffy_tree,
node_inbuilt_to_taffy,
node_id_to_taffy,
taffy_id_to_node,
edge_spacer_taffy_nodes,
entity_highlighted_spans,
edge_label_taffy_nodes,
node_id_to_envelope_taffy_node,
})
}
/// Compute highlighted spans for all nodes after layout is complete.
/// This is much more efficient than doing it during measure() which gets
/// called multiple times.
fn highlighted_spans_compute(
taffy_tree: &TaffyTree<TaffyNodeCtx>,
node_id_to_taffy: &Map<NodeId<'static>, NodeToTaffyNodeIds>,
edge_label_taffy_nodes: &Map<EdgeId<'static>, EdgeLabelTaffyNodeIds>,
nodes: &NodeNames<'static>,
entity_descs: &EntityDescs<'static>,
char_width: f32,
lod: &DiagramLod,
) -> EntityHighlightedSpans<'static> {
let mut entity_highlighted_spans = EntityHighlightedSpans::with_capacity(
node_id_to_taffy.len() + edge_label_taffy_nodes.len(),
);
let line_height = TEXT_LINE_HEIGHT;
node_id_to_taffy
.iter()
.for_each(|(node_id, &taffy_node_ids)| {
let (wrapper_node_layout, text_node_layout, diagram_node_ctx) = match taffy_node_ids
{
NodeToTaffyNodeIds::Leaf { text_node_id } => {
let Ok(text_node_layout) = taffy_tree.layout(text_node_id) else {
return;
};
let Some(TaffyNodeCtx::DiagramNode(diagram_node_ctx)) =
taffy_tree.get_node_context(text_node_id)
else {
return;
};
(text_node_layout, text_node_layout, diagram_node_ctx)
}
NodeToTaffyNodeIds::Wrapper {
wrapper_node_id,
text_node_id,
}
| NodeToTaffyNodeIds::LeafWithCircle {
wrapper_node_id,
circle_node_id: _,
text_node_id,
}
| NodeToTaffyNodeIds::WrapperCircle {
wrapper_node_id,
label_wrapper_node_id: _,
circle_node_id: _,
text_node_id,
} => {
let Ok(wrapper_node_layout) = taffy_tree.layout(wrapper_node_id) else {
return;
};
let Ok(text_node_layout) = taffy_tree.layout(text_node_id) else {
return;
};
let Some(TaffyNodeCtx::DiagramNode(diagram_node_ctx)) =
taffy_tree.get_node_context(text_node_id)
else {
return;
};
(wrapper_node_layout, text_node_layout, diagram_node_ctx)
}
};
let text_label_offset = match taffy_node_ids {
NodeToTaffyNodeIds::Leaf { .. } | NodeToTaffyNodeIds::Wrapper { .. } => 0.0f32,
NodeToTaffyNodeIds::LeafWithCircle {
wrapper_node_id: _,
circle_node_id,
text_node_id: _,
}
| NodeToTaffyNodeIds::WrapperCircle {
wrapper_node_id: _,
label_wrapper_node_id: _,
circle_node_id,
text_node_id: _,
} => taffy_tree
.layout(circle_node_id)
.map(|circle_node_layout| {
// This could be:
//
// ```rust
// circle_node_layout.size.width + gap
// ```
//
// but we don't have the gap value
text_node_layout.location.x - circle_node_layout.location.x
})
.unwrap_or_default(),
};
let entity_id = &diagram_node_ctx.entity_id;
// Build the text content
let node_name = nodes
.get(entity_id)
.map(String::as_str)
.unwrap_or_else(|| entity_id.as_str());
let text: Cow<'_, str> = match lod {
DiagramLod::Simple => Cow::Borrowed(node_name),
DiagramLod::Normal => {
let node_desc = entity_descs.get(entity_id).map(String::as_str);
match node_desc {
Some(desc) => Cow::Owned(format!("# {node_name}\n\n{desc}")),
None => Cow::Borrowed(node_name),
}
}
};
if text.is_empty() {
return;
}
// Use the computed layout width as constraint
let max_width = text_node_layout.size.width;
// Compute line wrapping using simple monospace calculation
let wrapped_lines = wrap_text_monospace(&text, char_width, max_width);
// Get style info for padding calculations
let padding_left = text_node_layout.padding.left;
let padding_top = wrapper_node_layout.padding.top;
// Note: we shift the text by half a character width because even though we have
// padding, the text still reaches the left and right edges of the node.
//
// The half a character width (at each end) is added to the node's width in
// `line_width_measure`.
let text_leftmost_x = text_label_offset + padding_left + 0.5 * char_width;
let highlighted_spans: Vec<EntityHighlightedSpan> = {
wrapped_lines
.iter()
.enumerate()
.flat_map(|(line_index, line)| {
let x = text_leftmost_x;
let y = (line_index + 1) as f32 * line_height + padding_top;
let width = line_width_measure(line, char_width);
let entity_highlighted_span = EntityHighlightedSpan {
x,
y,
width,
height: line_height,
// style,
text: line.to_string(),
};
vec![entity_highlighted_span]
})
.collect()
};
entity_highlighted_spans.insert(node_id.as_ref().clone(), highlighted_spans);
});
// === Edge label spans === //
//
// For DiagramLod::Normal, compute highlighted spans for edge label
// slots. Both the from_label and to_label slots for a given edge show
// the same description text, so a single span set is computed and
// stored per edge, keyed by the edge's raw Id. The width of the
// from_label slot is used as the line-wrapping constraint (falling
// back to the to_label slot when from_label is absent).
if matches!(lod, DiagramLod::Normal) {
edge_label_taffy_nodes
.iter()
.for_each(|(edge_id, edge_label_taffy_node_ids)| {
let Some(desc) = entity_descs.get(edge_id.as_ref()).map(String::as_str) else {
return;
};
// Pick whichever label slot is present to get the layout width.
let edge_label_taffy_node_id = edge_label_taffy_node_ids
.from_label_taffy_node_id
.or(edge_label_taffy_node_ids.to_label_taffy_node_id);
let Some(edge_label_taffy_node_id) = edge_label_taffy_node_id else {
return;
};
let Ok(edge_label_node_layout) = taffy_tree.layout(edge_label_taffy_node_id)
else {
return;
};
let max_width = edge_label_node_layout.size.width;
let wrapped_lines = wrap_text_monospace(desc, char_width, max_width);
let padding_left = edge_label_node_layout.padding.left;
let padding_top = edge_label_node_layout.padding.top;
let text_leftmost_x = padding_left + 0.5 * char_width;
let highlighted_spans: Vec<EntityHighlightedSpan> = wrapped_lines
.iter()
.enumerate()
.map(|(line_index, line)| {
let x = text_leftmost_x;
let y = (line_index + 1) as f32 * line_height + padding_top;
let width = line_width_measure(line, char_width);
EntityHighlightedSpan {
x,
y,
width,
height: line_height,
text: line.to_string(),
}
})
.collect();
entity_highlighted_spans.insert(edge_id.as_ref().clone(), highlighted_spans);
});
}
entity_highlighted_spans
}
/// Creates rank sub-containers for first-level nodes of a given entity
/// type.
///
/// Each rank level gets its own flex container using the style of the
/// parent `NodeInbuilt` container. The returned `Vec` contains one taffy
/// node per rank, ordered by rank.
fn build_taffy_rank_containers_for_first_level_nodes(
taffy_tree: &mut TaffyTree<TaffyNodeCtx>,
node_layouts: &NodeLayouts,
node_inbuilt: NodeInbuilt,
rank_to_taffy_ids: NodeRankToTaffyNodeId,
) -> Vec<taffy::NodeId> {
// Not sure if this is the best way to handle the container styles, but we use
// the `NodeInbuilt` container style for the rank children containers, and
// invert the `FlexDirection` on the actual `NodeInbuilt` container style.
let rank_container_style =
Self::taffy_container_style(node_layouts, &node_inbuilt.id(), Size::auto());
// Creates a new taffy node for each rank to be placed in the container.
//
// i.e.
//
// ```yaml
// container_node:
// child_container_0: {} # nodes with rank n
// child_container_1: {} # nodes with rank n + 1
// child_container_2: {} # nodes with rank n + 2
// ```
rank_to_taffy_ids
.into_values()
.map(|taffy_ids| {
taffy_tree
.new_with_children(rank_container_style.clone(), &taffy_ids)
.unwrap_or_else(|e| {
panic!(
"Expected to create rank container node for \
top-level {node_inbuilt}. Error: {e}"
)
})
})
.collect()
}
/// Adds the inbuilt container nodes to the `TaffyTree`.
fn build_taffy_container_nodes(
taffy_tree: &mut TaffyTree<TaffyNodeCtx>,
taffy_id_to_node: &mut Map<taffy::NodeId, NodeId>,
node_layouts: &NodeLayouts,
dimension: &disposition_taffy_model::Dimension,
thing_rank_container_ids: &[taffy::NodeId],
process_rank_container_ids: &[taffy::NodeId],
tag_rank_container_ids: &[taffy::NodeId],
) -> Map<NodeInbuilt, taffy::NodeId> {
let things_container_style = {
let container_style = Self::taffy_container_style(
node_layouts,
&NodeInbuilt::ThingsContainer.id(),
Size::auto(),
);
Self::container_style_invert_and_stretch(container_style)
};
let things_container = taffy_tree
.new_with_children(things_container_style, thing_rank_container_ids)
.expect("`TaffyTree::new_with_children` should be infallible.");
let processes_container_style = {
let container_style = Self::taffy_container_style(
node_layouts,
&NodeInbuilt::ProcessesContainer.id(),
Size::auto(),
);
Self::container_style_invert_and_stretch(container_style)
};
let processes_container = taffy_tree
.new_with_children(processes_container_style, process_rank_container_ids)
.expect("`TaffyTree::new_with_children` should be infallible.");
let things_and_processes_container = Self::taffy_container_node(
taffy_tree,
node_layouts,
NodeInbuilt::ThingsAndProcessesContainer,
Size::auto(),
&[processes_container, things_container],
);
let tags_container_style = {
let container_style = Self::taffy_container_style(
node_layouts,
&NodeInbuilt::TagsContainer.id(),
Size::auto(),
);
Self::container_style_invert_and_stretch(container_style)
};
let tags_container = taffy_tree
.new_with_children(tags_container_style, tag_rank_container_ids)
.expect("`TaffyTree::new_with_children` should be infallible.");
let root = Self::taffy_container_node(
taffy_tree,
node_layouts,
NodeInbuilt::Root,
match dimension {
Dimension::NoLimit => Size::auto(),
_ => Size::from_lengths(dimension.width(), dimension.height()),
},
&[tags_container, things_and_processes_container],
);
let mut node_inbuilt_to_taffy = Map::new();
node_inbuilt_to_taffy.insert(NodeInbuilt::ThingsContainer, things_container);
node_inbuilt_to_taffy.insert(NodeInbuilt::ProcessesContainer, processes_container);
node_inbuilt_to_taffy.insert(
NodeInbuilt::ThingsAndProcessesContainer,
things_and_processes_container,
);
node_inbuilt_to_taffy.insert(NodeInbuilt::TagsContainer, tags_container);
node_inbuilt_to_taffy.insert(NodeInbuilt::Root, root);
taffy_id_to_node.insert(
things_container,
NodeId::from(NodeInbuilt::ThingsContainer.id()),
);
taffy_id_to_node.insert(
processes_container,
NodeId::from(NodeInbuilt::ProcessesContainer.id()),
);
taffy_id_to_node.insert(
things_and_processes_container,
NodeId::from(NodeInbuilt::ThingsAndProcessesContainer.id()),
);
taffy_id_to_node.insert(
tags_container,
NodeId::from(NodeInbuilt::TagsContainer.id()),
);
taffy_id_to_node.insert(root, NodeId::from(NodeInbuilt::Root.id()));
node_inbuilt_to_taffy
}
/// Sets the flex direction to the opposite of the container style.
///
/// The flex direction inversion is because the desired flex direction is
/// set on the rank container nodes, so when the user has requested `Row`,
/// each rank container uses the `Row` layout, and the parent of the ranked
/// containers should be `Column`.
fn container_style_invert_and_stretch(container_style: Style) -> Style {
let flex_direction = match container_style.flex_direction {
FlexDirection::Row => FlexDirection::Column,
FlexDirection::Column => FlexDirection::Row,
FlexDirection::RowReverse => FlexDirection::ColumnReverse,
FlexDirection::ColumnReverse => FlexDirection::RowReverse,
};
Style {
flex_direction,
..container_style
}
}
/// Adds the tags, things, and process nodes to the taffy tree.
///
/// This is different from `build_taffy_nodes_for_node` in that the parent
/// node is one of the container nodes.
///
/// Returns a map from `EntityType` to a `BTreeMap<NodeRank, Vec<NodeId>>`,
/// so that callers can create rank-based sub-containers for each entity
/// type (e.g. grouping top-level thing nodes by rank).
fn build_taffy_nodes_for_first_level_nodes(
taffy_node_build_context: TaffyNodeBuildContext<'_>,
processes_included: &ProcessesIncluded,
edge_groups: &EdgeGroups<'static>,
) -> (
Map<EntityType, NodeRankToTaffyNodeId>,
Map<EdgeId<'static>, EdgeSpacerTaffyNodes>,
) {
let TaffyNodeBuildContext {
nodes,
taffy_tree,
node_layouts,
node_hierarchy,
entity_types,
node_shapes,
node_ranks_nested,
node_nesting_infos,
node_id_to_taffy,
taffy_id_to_node,
node_face_edges,
node_id_to_envelope_taffy_node,
edge_label_leaves,
} = taffy_node_build_context;
let mut edge_spacer_taffy_nodes: Map<EdgeId<'static>, EdgeSpacerTaffyNodes> = Map::new();
let entity_type_to_node_rank_to_taffy_node_ids = node_hierarchy.iter().fold(
Map::<EntityType, NodeRankToTaffyNodeId>::new(),
|mut entity_type_to_node_rank_to_taffy_node_ids, (node_id, child_hierarchy)| {
let node_id: &Id = node_id.as_ref();
let Some(entity_type) = entity_types
.get(node_id)
.and_then(|entity_types| entity_types.first())
else {
// Skip nodes without an entity type -- probably something extra in the
// hierarchy without a node name.
return entity_type_to_node_rank_to_taffy_node_ids;
};
if matches!(entity_type, EntityType::ProcessDefault) {
match processes_included {
ProcessesIncluded::All => {}
ProcessesIncluded::Filter { process_ids } => {
if process_ids.contains(node_id) {
// Don't add this process.
return entity_type_to_node_rank_to_taffy_node_ids;
}
}
};
}
let wrapper_node_id = if child_hierarchy.is_empty() {
Self::build_taffy_nodes_for_node_without_child_hierarchy(
taffy_tree,
node_layouts,
node_shapes,
node_id_to_taffy,
taffy_id_to_node,
node_id,
entity_type,
node_face_edges,
node_id_to_envelope_taffy_node,
edge_label_leaves,
)
} else {
let (wrapper_node_id, nested_edge_spacer_taffy_nodes) =
Self::build_taffy_nodes_for_node_with_child_hierarchy(
nodes,
taffy_tree,
node_layouts,
node_shapes,
entity_types,
node_ranks_nested,
node_nesting_infos,
node_id_to_taffy,
taffy_id_to_node,
child_hierarchy,
node_id,
entity_type,
edge_groups,
node_face_edges,
node_id_to_envelope_taffy_node,
edge_label_leaves,
);
edge_spacer_taffy_nodes.extend(nested_edge_spacer_taffy_nodes);
wrapper_node_id
};
let ir_node_id = NodeId::from(node_id.clone());
let rank = node_ranks_nested
.node_rank_for(&ir_node_id, node_nesting_infos)
.unwrap_or(NodeRank::new(0));
entity_type_to_node_rank_to_taffy_node_ids
.entry(entity_type.clone())
.or_default()
.entry(rank)
.or_default()
.push(wrapper_node_id);
entity_type_to_node_rank_to_taffy_node_ids
},
);
(
entity_type_to_node_rank_to_taffy_node_ids,
edge_spacer_taffy_nodes,
)
}
/// Adds the child taffy nodes for a given IR diagram node, grouped by rank.
///
/// Returns a `BTreeMap` from `NodeRank` to the list of taffy node IDs at
/// that rank. This allows the caller to create separate child containers
/// for each rank level.
fn build_taffy_child_nodes_for_node_by_rank(
taffy_node_build_context: TaffyNodeBuildContext<'_>,
edge_groups: &EdgeGroups<'static>,
) -> (
NodeRankToTaffyNodeId,
Map<EdgeId<'static>, EdgeSpacerTaffyNodes>,
) {
let TaffyNodeBuildContext {
nodes,
taffy_tree,
node_layouts,
node_hierarchy,
entity_types,
node_shapes,
node_ranks_nested,
node_nesting_infos,
node_id_to_taffy,
taffy_id_to_node,
node_face_edges,
node_id_to_envelope_taffy_node,
edge_label_leaves,
} = taffy_node_build_context;
let mut rank_to_taffy_ids: NodeRankToTaffyNodeId = BTreeMap::new();
let mut edge_spacer_taffy_nodes: Map<EdgeId<'static>, EdgeSpacerTaffyNodes> = Map::new();
for (node_id, child_hierarchy) in node_hierarchy.iter() {
let node_id: &Id = node_id.as_ref();
let Some(entity_type) = entity_types
.get(node_id)
.and_then(|entity_types| entity_types.first())
else {
// Skip nodes without an entity type -- probably something extra in the
// hierarchy without a node name.
continue;
};
let taffy_node_id = if child_hierarchy.is_empty() {
Self::build_taffy_nodes_for_node_without_child_hierarchy(
taffy_tree,
node_layouts,
node_shapes,
node_id_to_taffy,
taffy_id_to_node,
node_id,
entity_type,
node_face_edges,
node_id_to_envelope_taffy_node,
edge_label_leaves,
)
} else {
let (wrapper_node_id, nested_edge_spacer_taffy_nodes) =
Self::build_taffy_nodes_for_node_with_child_hierarchy(
nodes,
taffy_tree,
node_layouts,
node_shapes,
entity_types,
node_ranks_nested,
node_nesting_infos,
node_id_to_taffy,
taffy_id_to_node,
child_hierarchy,
node_id,
entity_type,
edge_groups,
node_face_edges,
node_id_to_envelope_taffy_node,
edge_label_leaves,
);
edge_spacer_taffy_nodes.extend(nested_edge_spacer_taffy_nodes);
wrapper_node_id
};
let ir_node_id = NodeId::from(node_id.clone());
let rank = node_ranks_nested
.node_rank_for(&ir_node_id, node_nesting_infos)
.unwrap_or(NodeRank::new(0));
rank_to_taffy_ids
.entry(rank)
.or_default()
.push(taffy_node_id);
}
(rank_to_taffy_ids, edge_spacer_taffy_nodes)
}
#[allow(clippy::too_many_arguments)]
fn build_taffy_nodes_for_node_without_child_hierarchy(
taffy_tree: &mut TaffyTree<TaffyNodeCtx>,
node_layouts: &NodeLayouts<'static>,
node_shapes: &NodeShapes<'static>,
node_id_to_taffy: &mut Map<NodeId<'static>, NodeToTaffyNodeIds>,
taffy_id_to_node: &mut Map<taffy::NodeId, NodeId<'static>>,
node_id: &Id<'static>,
entity_type: &EntityType,
node_face_edges: &NodeFaceEdges<'static>,
node_id_to_envelope_taffy_node: &mut Map<NodeId<'static>, taffy::NodeId>,
edge_label_leaves: &mut Vec<EdgeLabelLeafBuilt>,
) -> taffy::NodeId {
let ir_node_id = NodeId::from(node_id.clone());
let node_shape = node_shapes
.get(&ir_node_id)
.unwrap_or_else(|| panic!("There was no node shape for {ir_node_id}."));
match node_shape {
NodeShape::Rect(_node_shape_rect) => {
let taffy_style = Self::taffy_container_style(node_layouts, node_id, Size::auto());
let taffy_text_node_id = taffy_tree
.new_leaf_with_context(
taffy_style,
TaffyNodeCtx::DiagramNode(DiagramNodeCtx {
entity_id: node_id.clone(),
entity_type: entity_type.clone(),
}),
)
.unwrap_or_else(|e| {
panic!("Expected to create text leaf node for {node_id}. Error: {e}")
});
node_id_to_taffy.insert(
ir_node_id.clone(),
NodeToTaffyNodeIds::Leaf {
text_node_id: taffy_text_node_id,
},
);
let (envelope_node_id, new_label_leaves) = Self::taffy_envelope_node_build(
taffy_tree,
&ir_node_id,
taffy_text_node_id,
node_face_edges,
);
edge_label_leaves.extend(new_label_leaves);
node_id_to_envelope_taffy_node.insert(ir_node_id.clone(), envelope_node_id);
taffy_id_to_node.insert(taffy_text_node_id, ir_node_id);
envelope_node_id
}
NodeShape::Circle(node_shape_circle) => {
// Circle leaf:
//
// ```yaml
// label_wrapper_node: # flex row
// - circle_node
// - text_node
// ```
let circle_radius = node_shape_circle.radius();
let circle_diameter = circle_radius * 2.0;
let circle_node_id = taffy_tree
.new_leaf(Style {
size: Size {
width: taffy::style::Dimension::length(circle_diameter),
height: taffy::style::Dimension::length(circle_diameter),
},
flex_shrink: 0.0,
..Default::default()
})
.unwrap_or_else(|e| {
panic!("Expected to create circle leaf node for {node_id}. Error: {e}")
});
let text_style = Style::default();
let taffy_text_node_id = taffy_tree
.new_leaf_with_context(
text_style,
TaffyNodeCtx::DiagramNode(DiagramNodeCtx {
entity_id: node_id.clone(),
entity_type: entity_type.clone(),
}),
)
.unwrap_or_else(|e| {
panic!("Expected to create text leaf node for {node_id}. Error: {e}")
});
let label_wrapper_style =
Self::taffy_container_style(node_layouts, node_id, Size::auto());
// Override to flex row for circle + text side by side
let label_wrapper_style = Style {
display: Display::Flex,
flex_direction: FlexDirection::Row,
align_items: Some(AlignItems::Center),
gap: Size::length(4.0f32),
..label_wrapper_style
};
let wrapper_node_id = taffy_tree
.new_with_children(label_wrapper_style, &[circle_node_id, taffy_text_node_id])
.unwrap_or_else(|e| {
panic!("Expected to create label wrapper node for {node_id}. Error: {e}")
});
node_id_to_taffy.insert(
ir_node_id.clone(),
NodeToTaffyNodeIds::LeafWithCircle {
wrapper_node_id,
circle_node_id,
text_node_id: taffy_text_node_id,
},
);
let (envelope_node_id, new_label_leaves) = Self::taffy_envelope_node_build(
taffy_tree,
&ir_node_id,
wrapper_node_id,
node_face_edges,
);
edge_label_leaves.extend(new_label_leaves);
node_id_to_envelope_taffy_node.insert(ir_node_id.clone(), envelope_node_id);
taffy_id_to_node.insert(wrapper_node_id, ir_node_id);
envelope_node_id
}
}
}
#[allow(clippy::too_many_arguments)]
fn build_taffy_nodes_for_node_with_child_hierarchy(
nodes: &NodeNames<'static>,
taffy_tree: &mut TaffyTree<TaffyNodeCtx>,
node_layouts: &NodeLayouts<'static>,
node_shapes: &NodeShapes<'static>,
entity_types: &EntityTypes<'static>,
node_ranks_nested: &NodeRanksNested<'static>,
node_nesting_infos: &NodeNestingInfos<'static>,
node_id_to_taffy: &mut Map<NodeId<'static>, NodeToTaffyNodeIds>,
taffy_id_to_node: &mut Map<taffy::NodeId, NodeId<'static>>,
child_hierarchy: &NodeHierarchy<'static>,
node_id: &Id<'static>,
entity_type: &EntityType,
edge_groups: &EdgeGroups<'static>,
node_face_edges: &NodeFaceEdges<'static>,
node_id_to_envelope_taffy_node: &mut Map<NodeId<'static>, taffy::NodeId>,
edge_label_leaves: &mut Vec<EdgeLabelLeafBuilt>,
) -> (taffy::NodeId, Map<EdgeId<'static>, EdgeSpacerTaffyNodes>) {
let ir_node_id = NodeId::from(node_id.clone());
let mut edge_spacer_taffy_nodes: Map<EdgeId<'static>, EdgeSpacerTaffyNodes> = Map::new();
let TaffyWrapperNodeStyles {
wrapper_style,
text_style,
child_container_style,
} = Self::taffy_wrapper_node_styles(node_layouts, node_id);
let taffy_text_node_id = taffy_tree
.new_leaf_with_context(
text_style,
TaffyNodeCtx::DiagramNode(DiagramNodeCtx {
entity_id: node_id.clone(),
entity_type: entity_type.clone(),
}),
)
.unwrap_or_else(|e| {
panic!("Expected to create text leaf node for {node_id}. Error: {e}")
});
let taffy_node_build_context = TaffyNodeBuildContext {
nodes,
taffy_tree,
node_layouts,
node_hierarchy: child_hierarchy,
entity_types,
node_shapes,
node_ranks_nested,
node_nesting_infos,
node_id_to_taffy,
taffy_id_to_node,
node_face_edges,
node_id_to_envelope_taffy_node,
edge_label_leaves,
};
let (mut rank_to_taffy_ids, nested_edge_spacer_taffy_nodes) =
Self::build_taffy_child_nodes_for_node_by_rank(taffy_node_build_context, edge_groups);
edge_spacer_taffy_nodes.extend(nested_edge_spacer_taffy_nodes);
// === Insert spacer nodes for edges nested within this node === //
let lca_node_id = NodeId::from(node_id.clone());
for target_entity_type in &[
EntityType::ThingDefault,
EntityType::TagDefault,
EntityType::ProcessDefault,
] {
edge_spacer_taffy_nodes.extend(EdgeSpacerBuilder::build(
taffy_tree,
edge_groups,
node_nesting_infos,
node_ranks_nested,
entity_types,
target_entity_type,
&mut rank_to_taffy_ids,
Some(&lca_node_id),
));
}
// === Insert spacer nodes for edges crossing this container === //
//
// When an edge has one endpoint outside this container and the
// other deeply nested inside, the edge path needs waypoints
// alongside the intermediate sibling children so it routes
// around them instead of drawing over them.
edge_spacer_taffy_nodes.extend(EdgeSpacerBuilder::build_cross_container_spacers(
taffy_tree,
edge_groups,
node_nesting_infos,
node_ranks_nested,
&mut rank_to_taffy_ids,
&ir_node_id,
child_hierarchy,
));
// === Build Rank-Based Child Containers === //
//
// Instead of a single child container with all children, we create one
// child container per rank level. This causes higher-ranked nodes to be
// positioned further along the wrapper's flex direction (down for
// column, right for row).
//
// ```yaml
// wrapper_node:
// text_node: 'node text'
// child_container_0: {} # nodes with rank n
// child_container_1: {} # nodes with rank n + 1
// child_container_2: {} # nodes with rank n + 2
// ```
let rank_container_ids: Vec<taffy::NodeId> = rank_to_taffy_ids
.into_values()
.map(|taffy_ids| {
taffy_tree
.new_with_children(child_container_style.clone(), &taffy_ids)
.unwrap_or_else(|e| {
panic!(
"Expected to create rank child container node for {node_id}. \
Error: {e}"
)
})
})
.collect();
let node_shape = node_shapes
.get(&ir_node_id)
.unwrap_or_else(|| panic!("There was no node shape for {ir_node_id}."));
match node_shape {
NodeShape::Rect(_node_shape_rect) => {
let mut wrapper_children = vec![taffy_text_node_id];
wrapper_children.extend(rank_container_ids);
let wrapper_node_id = taffy_tree
.new_with_children(wrapper_style, &wrapper_children)
.unwrap_or_else(|e| {
panic!("Expected to create wrapper node for {node_id}. Error: {e}")
});
node_id_to_taffy.insert(
ir_node_id.clone(),
NodeToTaffyNodeIds::Wrapper {
wrapper_node_id,
text_node_id: taffy_text_node_id,
},
);
let (envelope_node_id, new_label_leaves) = Self::taffy_envelope_node_build(
taffy_tree,
&ir_node_id,
wrapper_node_id,
node_face_edges,
);
edge_label_leaves.extend(new_label_leaves);
node_id_to_envelope_taffy_node.insert(ir_node_id.clone(), envelope_node_id);
taffy_id_to_node.insert(wrapper_node_id, ir_node_id);
(envelope_node_id, edge_spacer_taffy_nodes)
}
NodeShape::Circle(node_shape_circle) => {
// Circle wrapper:
//
// ```yaml
// wrapper_node:
// - label_wrapper_node: # flex row
// - circle_node
// - text_node
// - child_container_0 # rank n
// - child_container_1 # rank n + 1
// ```
let circle_radius = node_shape_circle.radius();
let circle_diameter = circle_radius * 2.0;
let circle_node_id = taffy_tree
.new_leaf(Style {
size: Size {
width: taffy::style::Dimension::length(circle_diameter),
height: taffy::style::Dimension::length(circle_diameter),
},
flex_shrink: 0.0,
..Default::default()
})
.unwrap_or_else(|e| {
panic!("Expected to create circle leaf node for {node_id}. Error: {e}")
});
let label_wrapper_style = Style {
display: Display::Flex,
flex_direction: FlexDirection::Row,
align_items: Some(AlignItems::Center),
gap: Size::length(4.0f32),
..Default::default()
};
let label_wrapper_node_id = taffy_tree
.new_with_children(label_wrapper_style, &[circle_node_id, taffy_text_node_id])
.unwrap_or_else(|e| {
panic!("Expected to create label wrapper node for {node_id}. Error: {e}")
});
let mut wrapper_children = vec![label_wrapper_node_id];
wrapper_children.extend(rank_container_ids);
let wrapper_node_id = taffy_tree
.new_with_children(wrapper_style, &wrapper_children)
.unwrap_or_else(|e| {
panic!("Expected to create wrapper node for {node_id}. Error: {e}")
});
node_id_to_taffy.insert(
ir_node_id.clone(),
NodeToTaffyNodeIds::WrapperCircle {
wrapper_node_id,
label_wrapper_node_id,
circle_node_id,
text_node_id: taffy_text_node_id,
},
);
let (envelope_node_id, new_label_leaves) = Self::taffy_envelope_node_build(
taffy_tree,
&ir_node_id,
wrapper_node_id,
node_face_edges,
);
edge_label_leaves.extend(new_label_leaves);
node_id_to_envelope_taffy_node.insert(ir_node_id.clone(), envelope_node_id);
taffy_id_to_node.insert(wrapper_node_id, ir_node_id);
(envelope_node_id, edge_spacer_taffy_nodes)
}
}
}
/// Adds a container node to the `TaffyTree` and returns its ID.
///
/// # Parameters
///
/// * `taffy_tree`: `TaffyTree` to add the node to.
/// * `node_layouts`: Flex layout / none computed when mapping the
/// `InputDiagram` to the `IrDiagram`.
/// * `node_inbuilt`: The `NodeInbuilt` struct representing the node.
/// * `max_size`: Maximum size of the node.
/// * `child_node_ids`: IDs of child nodes to add to the container.
fn taffy_container_node(
taffy_tree: &mut TaffyTree<TaffyNodeCtx>,
node_layouts: &NodeLayouts,
node_inbuilt: NodeInbuilt,
max_size: Size<taffy::Dimension>,
child_node_ids: &[taffy::NodeId],
) -> taffy::NodeId {
let tags_container_style =
Self::taffy_container_style(node_layouts, &node_inbuilt.id(), max_size);
taffy_tree
.new_with_children(tags_container_style, child_node_ids)
.expect("`TaffyTree::new_leaf_with_context` should be infallible.")
}
/// Returns the `taffy::Style` for container nodes.
fn taffy_container_style(
node_layouts: &NodeLayouts,
node_id: &Id,
max_size: Size<taffy::Dimension>,
) -> Style {
node_layouts
.get(node_id)
.map(|node_layout| match node_layout {
NodeLayout::Flex(flex_layout) => Style {
display: Display::Flex,
max_size,
margin: Rect {
left: LengthPercentageAuto::length(flex_layout.margin_left()),
right: LengthPercentageAuto::length(flex_layout.margin_right()),
top: LengthPercentageAuto::length(flex_layout.margin_top()),
bottom: LengthPercentageAuto::length(flex_layout.margin_bottom()),
},
padding: Rect {
left: LengthPercentage::length(flex_layout.padding_left()),
right: LengthPercentage::length(flex_layout.padding_right()),
top: LengthPercentage::length(flex_layout.padding_top()),
bottom: LengthPercentage::length(flex_layout.padding_bottom()),
},
border: Rect::length(1.0f32),
// We use `AlignItems::Stretch` because we want coordinates to be as close to
// the top-left corner as possible, as well as resizing each node to be as wide
// as the widest node which looks more visually aesthetic.
//
// If we use `AlignItems::Center`, the coordinates
// may be negative when the content width exceeds the diagram dimension, and
// starts outside the diagram bounds.
align_items: Some(AlignItems::Stretch),
align_content: Some(AlignContent::Start),
justify_items: Some(JustifyItems::Start),
justify_content: Some(JustifyContent::Start),
gap: Size::length(flex_layout.gap()),
flex_direction: flex_direction_to_taffy(flex_layout.direction()),
flex_wrap: if flex_layout.wrap() {
FlexWrap::Wrap
} else {
FlexWrap::NoWrap
},
..Default::default()
},
NodeLayout::Leaf(leaf_layout) => Style {
margin: Rect {
left: LengthPercentageAuto::length(leaf_layout.margin_left()),
right: LengthPercentageAuto::length(leaf_layout.margin_right()),
top: LengthPercentageAuto::length(leaf_layout.margin_top()),
bottom: LengthPercentageAuto::length(leaf_layout.margin_bottom()),
},
padding: Rect {
left: LengthPercentage::length(leaf_layout.padding_left()),
right: LengthPercentage::length(leaf_layout.padding_right()),
top: LengthPercentage::length(leaf_layout.padding_top()),
bottom: LengthPercentage::length(leaf_layout.padding_bottom()),
},
..Default::default()
},
})
.unwrap_or_default()
}
/// Returns the `taffy::Style` for a wrapper node and its text node.
fn taffy_wrapper_node_styles(
node_layouts: &NodeLayouts,
node_id: &Id,
) -> TaffyWrapperNodeStyles {
node_layouts
.get(node_id)
.map(|node_layout| match node_layout {
NodeLayout::Flex(flex_layout) => {
let wrapper_style = Style {
display: Display::Flex,
max_size: Size::auto(),
margin: Rect {
left: LengthPercentageAuto::length(flex_layout.margin_left()),
right: LengthPercentageAuto::length(flex_layout.margin_right()),
top: LengthPercentageAuto::length(flex_layout.margin_top()),
bottom: LengthPercentageAuto::length(flex_layout.margin_bottom()),
},
padding: Rect {
left: LengthPercentage::length(flex_layout.padding_left()),
right: LengthPercentage::length(flex_layout.padding_right()),
top: LengthPercentage::length(flex_layout.padding_top()),
bottom: LengthPercentage::length(flex_layout.padding_bottom()),
},
border: Rect::length(1.0f32),
align_items: Some(AlignItems::FlexStart),
align_content: Some(AlignContent::FlexStart),
justify_items: Some(JustifyItems::FlexStart),
justify_content: Some(JustifyContent::FlexStart),
gap: Size::length(flex_layout.gap()),
flex_direction: FlexDirection::Column,
flex_wrap: FlexWrap::NoWrap,
..Default::default()
};
// Leaf node doesn't need much difference from wrapper style
let text_style = Style {
padding: Rect {
left: LengthPercentage::length(flex_layout.padding_left()),
right: LengthPercentage::length(flex_layout.padding_right()),
top: LengthPercentage::ZERO,
bottom: LengthPercentage::ZERO,
},
..Default::default()
};
let child_container_style = Style {
display: Display::Flex,
max_size: Size::auto(),
// Rank sub-containers must not shrink below their
// content size; otherwise the column wrapper parent
// compresses them when space is tight, causing wrapped
// rows to overlap with the next rank container.
flex_shrink: 0.0,
gap: Size::length(flex_layout.gap()),
flex_direction: flex_direction_to_taffy(flex_layout.direction()),
flex_wrap: if flex_layout.wrap() {
FlexWrap::Wrap
} else {
FlexWrap::NoWrap
},
..Default::default()
};
TaffyWrapperNodeStyles {
wrapper_style,
text_style,
child_container_style,
}
}
NodeLayout::Leaf(leaf_layout) => TaffyWrapperNodeStyles::new(leaf_layout),
})
.unwrap_or_default()
}
/// Returns the size of a node based on its layout and available space.
/// This is called during layout computation and only computes sizes.
/// Syntax highlighting is deferred to a separate pass after layout.
fn node_size_measure(
node_measure_context: &mut NodeMeasureContext<'_>,
known_dimensions: Size<Option<f32>>,
available_space: Size<AvailableSpace>,
taffy_node_ctx: Option<&mut TaffyNodeCtx>,
style: &taffy::Style,
) -> Size<f32> {
if let Size {
width: Some(width),
height: Some(height),
} = known_dimensions
{
return Size { width, height };
}
let NodeMeasureContext {
nodes,
entity_descs,
char_width,
lod,
} = node_measure_context;
// Edge spacers, edge labels, and empty wrapper containers (no context)
// have no text to measure. Return zero size immediately so that
// empty face-wrapper rows/columns (e.g. `edge_wrapper_top` when a
// node has no top-face edges) do not contribute spurious height via
// the `(line_count + 0.5) * line_height` bias.
let text = match taffy_node_ctx
.as_ref()
.and_then(|taffy_node_ctx| match taffy_node_ctx {
TaffyNodeCtx::DiagramNode(diagram_node_ctx) => {
let entity_id = &diagram_node_ctx.entity_id;
let node_name = nodes
.get(entity_id)
.map(String::as_str)
.unwrap_or_else(|| entity_id.as_str());
match lod {
DiagramLod::Simple => Some(Cow::Borrowed(node_name)),
DiagramLod::Normal => {
let node_desc = entity_descs.get(entity_id).map(String::as_str);
match node_desc {
Some(desc) => Some(Cow::Owned(format!("# {node_name}\n\n{desc}"))),
None => Some(Cow::Borrowed(node_name)),
}
}
}
}
TaffyNodeCtx::EdgeSpacer(_) => None,
TaffyNodeCtx::EdgeLabel(ctx) => match lod {
DiagramLod::Simple => None,
DiagramLod::Normal => {
let edge_id = &ctx.edge_id;
entity_descs
.get(edge_id.as_ref())
.map(|desc| Cow::Borrowed(desc.as_str()))
}
},
}) {
Some(text) => text,
None => {
return Size {
width: 0.0,
height: 0.0,
}
}
};
// Set width constraint
let width_constraint = known_dimensions.width.or(match available_space.width {
AvailableSpace::MinContent => Some(0.0),
AvailableSpace::MaxContent => None,
AvailableSpace::Definite(width) => Some(width),
});
// Compute layout using simple monospace calculations
let (line_width_max, line_count) =
compute_text_dimensions(&text, *char_width, width_constraint);
let line_height = TEXT_LINE_HEIGHT;
let line_heights = (line_count as f32 + 0.5) * line_height;
taffy::Size {
width: line_width_max
+ style.border.left.into_raw().value()
+ style.border.right.into_raw().value()
+ style.padding.left.into_raw().value()
+ style.padding.right.into_raw().value(),
height: line_heights
+ style.border.top.into_raw().value()
+ style.border.bottom.into_raw().value()
+ style.padding.top.into_raw().value()
+ style.padding.bottom.into_raw().value(),
}
}
/// Builds the `edge_label_taffy_nodes` map by merging per-node label
/// leaves collected during envelope construction.
///
/// For each [`EdgeLabelLeafBuilt`], the raw edge endpoints are looked up
/// via `edge_groups` and compared against the leaf's `node_id` to
/// determine whether the leaf is the `from` or `to` slot for that edge.
/// Self-loop edges (where `from == to`) use only a `from_label` slot;
/// their `to_face` is `None`, so the `to_label` slot is never populated.
fn edge_label_taffy_nodes_build(
edge_label_leaves: Vec<EdgeLabelLeafBuilt>,
edge_face_assignments: &EdgeFaceAssignments<'static>,
edge_groups: &EdgeGroups<'static>,
) -> Map<EdgeId<'static>, EdgeLabelTaffyNodeIds> {
let edge_id_to_node_ids = Self::edge_id_to_node_ids_build(edge_groups);
let mut edge_label_taffy_nodes: Map<EdgeId<'static>, EdgeLabelTaffyNodeIds> = Map::new();
for built in edge_label_leaves {
let Some((from_node_id, to_node_id)) = edge_id_to_node_ids.get(&built.edge_id) else {
continue;
};
// Only create an entry when there is a face assignment to populate.
let Some(assignment) = edge_face_assignments.get(&built.edge_id) else {
continue;
};
let entry =
edge_label_taffy_nodes
.entry(built.edge_id)
.or_insert(EdgeLabelTaffyNodeIds {
from_label_taffy_node_id: None,
to_label_taffy_node_id: None,
});
if &built.node_id == from_node_id && assignment.from_face.is_some() {
entry.from_label_taffy_node_id = Some(built.taffy_node_id);
}
if &built.node_id == to_node_id && assignment.to_face.is_some() {
entry.to_label_taffy_node_id = Some(built.taffy_node_id);
}
}
edge_label_taffy_nodes
}
/// Builds a lookup from each edge ID to the node IDs of its endpoints.
///
/// The edge ID format mirrors `NodeFaceEdges::edge_id_generate`:
/// `"{edge_group_id}__{edge_index}"`.
fn edge_id_to_node_ids_build(
edge_groups: &EdgeGroups<'static>,
) -> Map<EdgeId<'static>, (NodeId<'static>, NodeId<'static>)> {
edge_groups
.iter()
.flat_map(|(edge_group_id, edge_group)| {
edge_group
.iter()
.enumerate()
.map(|(edge_index, edge)| {
let edge_id_str = format!("{edge_group_id}__{edge_index}");
let edge_id: EdgeId<'static> = Id::try_from(edge_id_str)
.expect("edge group ID and index should produce a valid edge ID")
.into();
(edge_id, (edge.from.clone(), edge.to.clone()))
})
.collect::<Vec<_>>()
})
.collect()
}
/// Builds an envelope taffy node around `diagram_node_wrapper_node`.
///
/// The envelope adds flex-row/column slots for edge label leaf nodes on
/// each face of the diagram node. The structure is:
///
/// ```text
/// envelope_node: (flex column, align_items: Stretch)
/// edge_wrapper_top: (flex row)
/// edge_and_diagram_wrapper: (flex row, align_items: Stretch)
/// edge_wrapper_left: (flex column)
/// diagram_node_wrapper_node
/// edge_wrapper_right: (flex column)
/// edge_wrapper_bottom: (flex row)
/// ```
///
/// # Parameters
///
/// * `taffy_tree`: The `TaffyTree` to insert nodes into.
/// * `node_id`: The diagram node ID for this envelope.
/// * `diagram_node_wrapper_node`: The existing wrapper node taffy ID to
/// wrap.
/// * `node_face_edges`: The per-node face-to-edge-IDs mapping from
/// `IrDiagram`.
fn taffy_envelope_node_build(
taffy_tree: &mut TaffyTree<TaffyNodeCtx>,
node_id: &NodeId<'static>,
diagram_node_wrapper_node: taffy::NodeId,
node_face_edges: &NodeFaceEdges<'static>,
) -> (taffy::NodeId, Vec<EdgeLabelLeafBuilt>) {
let mut edge_label_leaves = Vec::new();
let face_row_style = Style {
display: Display::Flex,
flex_direction: FlexDirection::Row,
..Default::default()
};
let face_column_style = Style {
display: Display::Flex,
flex_direction: FlexDirection::Column,
..Default::default()
};
let label_leaf_style = Style {
flex_shrink: 0.0,
..Default::default()
};
let top_leaf_ids = Self::taffy_envelope_node_build_face_leaves(
taffy_tree,
node_id,
NodeFace::Top,
node_face_edges.edges_for(node_id, NodeFace::Top),
&label_leaf_style,
&mut edge_label_leaves,
);
let bottom_leaf_ids = Self::taffy_envelope_node_build_face_leaves(
taffy_tree,
node_id,
NodeFace::Bottom,
node_face_edges.edges_for(node_id, NodeFace::Bottom),
&label_leaf_style,
&mut edge_label_leaves,
);
let left_leaf_ids = Self::taffy_envelope_node_build_face_leaves(
taffy_tree,
node_id,
NodeFace::Left,
node_face_edges.edges_for(node_id, NodeFace::Left),
&label_leaf_style,
&mut edge_label_leaves,
);
let right_leaf_ids = Self::taffy_envelope_node_build_face_leaves(
taffy_tree,
node_id,
NodeFace::Right,
node_face_edges.edges_for(node_id, NodeFace::Right),
&label_leaf_style,
&mut edge_label_leaves,
);
let edge_wrapper_top = taffy_tree
.new_with_children(face_row_style.clone(), &top_leaf_ids)
.unwrap_or_else(|e| {
panic!("Expected to create edge_wrapper_top for {node_id}. Error: {e}")
});
let edge_wrapper_bottom = taffy_tree
.new_with_children(face_row_style, &bottom_leaf_ids)
.unwrap_or_else(|e| {
panic!("Expected to create edge_wrapper_bottom for {node_id}. Error: {e}")
});
let edge_wrapper_left = taffy_tree
.new_with_children(face_column_style.clone(), &left_leaf_ids)
.unwrap_or_else(|e| {
panic!("Expected to create edge_wrapper_left for {node_id}. Error: {e}")
});
let edge_wrapper_right = taffy_tree
.new_with_children(face_column_style, &right_leaf_ids)
.unwrap_or_else(|e| {
panic!("Expected to create edge_wrapper_right for {node_id}. Error: {e}")
});
let edge_and_diagram_wrapper = taffy_tree
.new_with_children(
Style {
display: Display::Flex,
flex_direction: FlexDirection::Row,
align_items: Some(AlignItems::Stretch),
justify_content: Some(JustifyContent::SpaceBetween),
..Default::default()
},
&[
edge_wrapper_left,
diagram_node_wrapper_node,
edge_wrapper_right,
],
)
.unwrap_or_else(|e| {
panic!("Expected to create edge_and_diagram_wrapper for {node_id}. Error: {e}")
});
let envelope_node = taffy_tree
.new_with_children(
Style {
display: Display::Flex,
flex_direction: FlexDirection::Column,
align_items: Some(AlignItems::Stretch),
..Default::default()
},
&[
edge_wrapper_top,
edge_and_diagram_wrapper,
edge_wrapper_bottom,
],
)
.unwrap_or_else(|e| {
panic!("Expected to create envelope_node for {node_id}. Error: {e}")
});
(envelope_node, edge_label_leaves)
}
/// Builds the edge label leaf nodes for one face of an envelope node.
///
/// For each edge ID in `edge_ids`, a leaf node is created with
/// [`TaffyNodeCtx::EdgeLabel`] context and appended to `label_leaves`.
/// Returns the `taffy::NodeId`s of all created leaves in order.
///
/// # Parameters
///
/// * `taffy_tree`: The `TaffyTree` to insert nodes into.
/// * `node_id`: The diagram node ID that owns this face.
/// * `face`: Which face of the node these labels are on.
/// * `edge_ids`: The edge IDs that attach to `face` on `node_id`.
/// * `label_leaf_style`: The taffy `Style` applied to every label leaf.
/// * `label_leaves`: Output accumulator for the built leaves.
fn taffy_envelope_node_build_face_leaves(
taffy_tree: &mut TaffyTree<TaffyNodeCtx>,
node_id: &NodeId<'static>,
face: NodeFace,
edge_ids: &[EdgeId<'static>],
label_leaf_style: &Style,
label_leaves: &mut Vec<EdgeLabelLeafBuilt>,
) -> Vec<taffy::NodeId> {
edge_ids
.iter()
.map(|edge_id| {
let taffy_node_id = taffy_tree
.new_leaf_with_context(
label_leaf_style.clone(),
TaffyNodeCtx::EdgeLabel(EdgeLabelCtx {
edge_id: edge_id.clone(),
node_id: node_id.clone(),
face,
}),
)
.unwrap_or_else(|e| {
panic!(
"Expected to create edge label leaf for edge {edge_id} on \
face {face:?} of node {node_id}. Error: {e}"
)
});
label_leaves.push(EdgeLabelLeafBuilt {
edge_id: edge_id.clone(),
node_id: node_id.clone(),
face,
taffy_node_id,
});
taffy_node_id
})
.collect()
}
}