chartlet 0.23.0

Compile structured data into deterministic, accessible static charts
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
//! The words of diagrams of nodes and edges: sequences, flows, networks, dendrograms, states
//! and trees, and what they share.

use super::{listed, plural};
use crate::spec::{
    AreaKind, DiagramRole, FragmentSpec, ItemKind, Linkage, Locale, MessageKind, NodeKind,
    ParticipantKind,
};
use std::fmt::Write as _;

/// A participant of a sequence diagram by its label, and by its kind where that is not a plain
/// system.
pub(crate) fn participant(locale: Locale, label: &str, kind: ParticipantKind) -> String {
    let kind = match (locale, kind) {
        (_, ParticipantKind::Service) => return label.to_owned(),
        (Locale::En, ParticipantKind::Actor) => "actor",
        (Locale::En, ParticipantKind::Database) => "database",
        (Locale::En, ParticipantKind::Queue) => "queue",
        (Locale::En, ParticipantKind::External) => "external",
        (Locale::De, ParticipantKind::Actor) => "Akteur",
        (Locale::De, ParticipantKind::Database) => "Datenbank",
        (Locale::De, ParticipantKind::Queue) => "Warteschlange",
        (Locale::De, ParticipantKind::External) => "extern",
    };
    format!("{label} ({kind})")
}

/// The opening sentence of a sequence diagram: its participants and how many messages follow.
pub(crate) fn sequence_opening(locale: Locale, participants: &[String], messages: usize) -> String {
    let count = participants.len();
    let names = listed(locale, participants);
    match locale {
        Locale::En => format!(
            "Sequence diagram with {count} participant{}: {names}. {messages} message{}, in order:",
            plural(count, "", "s"),
            plural(messages, "", "s"),
        ),
        Locale::De => format!(
            "Sequenzdiagramm mit {count} {}: {names}. {messages} {}, in Reihenfolge:",
            plural(count, "Beteiligtem", "Beteiligten"),
            plural(messages, "Nachricht", "Nachrichten"),
        ),
    }
}

/// One message of a sequence diagram as a sentence; `receiver` is `None` for a message to its
/// sender.
pub(crate) fn sequence_message(
    locale: Locale,
    number: usize,
    sender: &str,
    receiver: Option<&str>,
    label: &str,
    kind: MessageKind,
) -> String {
    let kind = match (locale, kind) {
        (_, MessageKind::Call) => "",
        (Locale::En, MessageKind::Reply) => " (reply)",
        (Locale::En, MessageKind::Async) => " (asynchronous)",
        (Locale::De, MessageKind::Reply) => " (Antwort)",
        (Locale::De, MessageKind::Async) => " (asynchron)",
    };
    match (locale, receiver) {
        (Locale::En, Some(receiver)) => format!("{number}. {sender} to {receiver}: {label}{kind}."),
        (Locale::En, None) => format!("{number}. {sender} to itself: {label}{kind}."),
        (Locale::De, Some(receiver)) => format!("{number}. {sender} an {receiver}: {label}{kind}."),
        (Locale::De, None) => format!("{number}. {sender} an sich selbst: {label}{kind}."),
    }
}

/// How a message is sent, for the data table.
pub(crate) const fn message_kind(locale: Locale, kind: MessageKind) -> &'static str {
    match (locale, kind) {
        (Locale::En, MessageKind::Call) => "call",
        (Locale::En, MessageKind::Reply) => "reply",
        (Locale::En, MessageKind::Async) => "asynchronous",
        (Locale::De, MessageKind::Call) => "Aufruf",
        (Locale::De, MessageKind::Reply) => "Antwort",
        (Locale::De, MessageKind::Async) => "asynchron",
    }
}

/// The branch of an `alt` fragment that has no label of its own.
pub(crate) const fn otherwise(locale: Locale) -> &'static str {
    match locale {
        Locale::En => "else",
        Locale::De => "sonst",
    }
}

/// Messages counted from 1: `message 3` or `messages 2–4`.
fn message_range(locale: Locale, from: usize, to: usize) -> String {
    match (locale, from == to) {
        (Locale::En, true) => format!("message {}", from + 1),
        (Locale::En, false) => format!("messages {}–{}", from + 1, to + 1),
        (Locale::De, true) => format!("Nachricht {}", from + 1),
        (Locale::De, false) => format!("Nachrichten {}–{}", from + 1, to + 1),
    }
}

/// A fragment of a sequence diagram as a sentence: its kind and label, the messages it frames,
/// and where each further branch begins.
pub(crate) fn fragment(locale: Locale, fragment: &FragmentSpec) -> String {
    let label = fragment
        .label
        .as_ref()
        .map_or_else(String::new, |label| match locale {
            Locale::En => format!(" \"{label}\""),
            Locale::De => format!(" „{label}“"),
        });
    let range = message_range(locale, fragment.from, fragment.to);
    let branches: String = fragment
        .branches
        .iter()
        .map(|branch| {
            let label = branch.label.as_deref().unwrap_or(otherwise(locale));
            match locale {
                Locale::En => format!(", else \"{label}\" from message {}", branch.from + 1),
                Locale::De => format!(", sonst „{label}“ ab Nachricht {}", branch.from + 1),
            }
        })
        .collect();
    let keyword = fragment.kind.keyword();
    match locale {
        Locale::En => format!("Fragment {keyword}{label} spans {range}{branches}."),
        Locale::De => format!("Abschnitt {keyword}{label} umfasst {range}{branches}."),
    }
}

/// The opening sentence of a flow chart: how many steps and edges, and its lanes.
pub(crate) fn flow_opening(locale: Locale, steps: usize, edges: usize, lanes: &[String]) -> String {
    let lanes = match (locale, lanes.len()) {
        (_, 0) => String::new(),
        (Locale::En, count) => format!(
            " in {count} lane{}: {}",
            plural(count, "", "s"),
            listed(locale, lanes)
        ),
        (Locale::De, count) => format!(
            " in {count} {}: {}",
            plural(count, "Bahn", "Bahnen"),
            listed(locale, lanes)
        ),
    };
    match locale {
        Locale::En => format!(
            "Flow chart with {steps} step{} and {edges} connection{}{lanes}.",
            plural(steps, "", "s"),
            plural(edges, "", "s"),
        ),
        Locale::De => format!(
            "Ablaufdiagramm mit {steps} {} und {edges} {}{lanes}.",
            plural(steps, "Schritt", "Schritten"),
            plural(edges, "Verbindung", "Verbindungen"),
        ),
    }
}

/// The main path of a flow chart, as step labels.
pub(crate) fn main_path(locale: Locale, steps: &[&str]) -> String {
    let path = steps.join(" → ");
    match locale {
        Locale::En => format!("Main path: {path}."),
        Locale::De => format!("Hauptweg: {path}."),
    }
}

/// The most connected nodes of a diagram and how many connections each has.
pub(crate) fn most_connected(locale: Locale, nodes: &[String], degree: usize) -> String {
    let names = listed(locale, nodes);
    match (locale, nodes.len()) {
        (Locale::En, 1) => format!("Most connected: {names} ({degree} connections)."),
        (Locale::En, _) => format!("Most connected: {names} ({degree} connections each)."),
        (Locale::De, 1) => format!("Am stärksten verbunden: {names} ({degree} Verbindungen)."),
        (Locale::De, _) => format!("Am stärksten verbunden: {names} (je {degree} Verbindungen)."),
    }
}

/// The nodes nothing leads into, other than those marked as a start.
pub(crate) fn sources(locale: Locale, nodes: &[String]) -> String {
    let names = listed(locale, nodes);
    match locale {
        Locale::En => format!("Nothing leads into {names}."),
        Locale::De => format!("In {names} führt nichts hinein."),
    }
}

/// The nodes nothing leads out of, other than those marked as an end.
pub(crate) fn sinks(locale: Locale, nodes: &[String]) -> String {
    let names = listed(locale, nodes);
    match locale {
        Locale::En => format!("Nothing leads out of {names}."),
        Locale::De => format!("Aus {names} führt nichts heraus."),
    }
}

/// The loops of a diagram, each as `A → B → A`.
pub(crate) fn loops(locale: Locale, loops: &[String]) -> String {
    let joined = loops.join("; ");
    match (locale, loops.len()) {
        (Locale::En, 1) => format!("Loop: {joined}."),
        (Locale::En, _) => format!("Loops: {joined}."),
        (Locale::De, 1) => format!("Schleife: {joined}."),
        (Locale::De, _) => format!("Schleifen: {joined}."),
    }
}

/// How many unconnected parts a diagram has.
pub(crate) fn unconnected_parts(locale: Locale, parts: usize) -> String {
    match locale {
        Locale::En => format!("The diagram has {parts} unconnected parts."),
        Locale::De => format!("Das Diagramm hat {parts} unverbundene Teile."),
    }
}

/// The nodes without which a diagram falls apart.
pub(crate) fn bottlenecks(locale: Locale, nodes: &[String]) -> String {
    let names = listed(locale, nodes);
    match (locale, nodes.len()) {
        (Locale::En, 1) => format!("Bottleneck: {names}; without it the diagram falls apart."),
        (Locale::En, _) => {
            format!("Bottlenecks: {names}; without either the diagram falls apart.")
        }
        (Locale::De, 1) => format!("Engstelle: {names}; ohne sie zerfällt das Diagramm."),
        (Locale::De, _) => {
            format!("Engstellen: {names}; ohne eine davon zerfällt das Diagramm.")
        }
    }
}

/// The weight of an edge in a note: `weight 120`.
pub(crate) fn edge_weight(locale: Locale, weight: &str) -> String {
    match locale {
        Locale::En => format!("weight {weight}"),
        Locale::De => format!("Gewicht {weight}"),
    }
}

/// The edge that carries most, as `A → B`, with its weight.
pub(crate) fn heaviest_edge(locale: Locale, edge: &str, weight: &str) -> String {
    match locale {
        Locale::En => format!("Heaviest connection: {edge} ({weight})."),
        Locale::De => format!("Stärkste Verbindung: {edge} ({weight})."),
    }
}

/// The opening sentence of a network: how many nodes and connections, and its groups.
pub(crate) fn network_opening(
    locale: Locale,
    (nodes, edges): (usize, usize),
    groups: &[String],
) -> String {
    let groups = match (locale, groups.len()) {
        (_, 0) => String::new(),
        (Locale::En, count) => format!(
            " in {count} group{}: {}",
            plural(count, "", "s"),
            listed(locale, groups)
        ),
        (Locale::De, count) => format!(
            " in {count} {}: {}",
            plural(count, "Gruppe", "Gruppen"),
            listed(locale, groups)
        ),
    };
    match locale {
        Locale::En => format!(
            "Network with {nodes} node{} and {edges} connection{}{groups}.",
            plural(nodes, "", "s"),
            plural(edges, "", "s"),
        ),
        Locale::De => format!(
            "Netzwerk mit {nodes} Knoten und {edges} {}{groups}.",
            plural(edges, "Verbindung", "Verbindungen"),
        ),
    }
}

/// The rings of a network around its center: which nodes stand how many steps away, and which
/// no way reaches (the ring without a distance).
pub(crate) fn network_rings(
    locale: Locale,
    center: &str,
    rings: &[(Option<usize>, Vec<String>)],
) -> String {
    let rings: Vec<String> = rings
        .iter()
        .map(|(distance, members)| {
            let members = listed(locale, members);
            match (locale, distance) {
                (Locale::En, Some(1)) => format!("1 step away: {members}"),
                (Locale::En, Some(steps)) => format!("{steps} steps away: {members}"),
                (Locale::En, None) => format!("not connected: {members}"),
                (Locale::De, Some(1)) => format!("1 Schritt entfernt: {members}"),
                (Locale::De, Some(steps)) => format!("{steps} Schritte entfernt: {members}"),
                (Locale::De, None) => format!("nicht verbunden: {members}"),
            }
        })
        .collect();
    let rings = rings.join("; ");
    match locale {
        Locale::En => format!("In rings around {center}: {rings}."),
        Locale::De => format!("In Ringen um {center}: {rings}."),
    }
}

/// One node of a network with its group and the nodes it leads to or is connected with.
pub(crate) fn network_node(
    locale: Locale,
    label: &str,
    group: Option<&str>,
    directed: bool,
    neighbours: &[String],
) -> String {
    let group = match (locale, group) {
        (_, None) => String::new(),
        (Locale::En, Some(group)) => format!(" (group {group})"),
        (Locale::De, Some(group)) => format!(" (Gruppe {group})"),
    };
    let names = listed(locale, neighbours);
    match (locale, directed, neighbours.is_empty()) {
        (Locale::En, false, true) => format!("{label}{group}: no connection."),
        (Locale::En, true, true) => format!("{label}{group}: no outgoing connection."),
        (Locale::En, false, false) => format!("{label}{group}: connected to {names}."),
        (Locale::En, true, false) => format!("{label}{group}: leads to {names}."),
        (Locale::De, false, true) => format!("{label}{group}: keine Verbindung."),
        (Locale::De, true, true) => format!("{label}{group}: keine ausgehende Verbindung."),
        (Locale::De, false, false) => format!("{label}{group}: verbunden mit {names}."),
        (Locale::De, true, false) => format!("{label}{group}: führt zu {names}."),
    }
}

/// The ring of a node in a network's table: the center, a distance, or none.
pub(crate) fn ring_name(locale: Locale, distance: Option<usize>) -> String {
    match (locale, distance) {
        (Locale::En, Some(0)) => "Center".to_owned(),
        (Locale::De, Some(0)) => "Mitte".to_owned(),
        (_, Some(distance)) => distance.to_string(),
        (Locale::En, None) => "not connected".to_owned(),
        (Locale::De, None) => "nicht verbunden".to_owned(),
    }
}

/// What the colors of a diagram's nodes show, the values at both ends of the scale, and every
/// node's value as `label value`.
pub(crate) fn node_values(
    locale: Locale,
    name: &str,
    (low, high): (&str, &str),
    nodes: &[String],
) -> String {
    let nodes = nodes.join(", ");
    match locale {
        Locale::En => {
            format!("Color shows {name}, from {low} (lightest) to {high} (darkest): {nodes}.")
        }
        Locale::De => format!(
            "Die Farbe zeigt {name}, von {low} (am hellsten) bis {high} (am dunkelsten): {nodes}."
        ),
    }
}

/// The parts of the nodes that have some, each as `label: part value (share), …`.
pub(crate) fn node_parts(locale: Locale, nodes: &[String]) -> String {
    let nodes = nodes.join("; ");
    match locale {
        Locale::En => format!("Parts: {nodes}."),
        Locale::De => format!("Anteile: {nodes}."),
    }
}

/// The name of a role of a diagram's nodes and edges.
pub(crate) const fn role(locale: Locale, role: DiagramRole) -> &'static str {
    match (locale, role) {
        (Locale::En, DiagramRole::Critical) => "critical",
        (Locale::En, DiagramRole::Planned) => "planned",
        (Locale::En, DiagramRole::Deprecated) => "deprecated",
        (Locale::De, DiagramRole::Critical) => "kritisch",
        (Locale::De, DiagramRole::Planned) => "geplant",
        (Locale::De, DiagramRole::Deprecated) => "veraltet",
    }
}

/// The sentence with the roles of a diagram, each as `role: what has it`.
pub(crate) fn roles(locale: Locale, roles: &[String]) -> String {
    let roles = roles.join("; ");
    match locale {
        Locale::En => format!("Roles: {roles}."),
        Locale::De => format!("Rollen: {roles}."),
    }
}

/// How a linkage measures the distance between two clusters, as a phrase.
const fn linkage_phrase(locale: Locale, linkage: Linkage) -> &'static str {
    match (locale, linkage) {
        (Locale::En, Linkage::Average) => {
            "average linkage (the mean distance between two clusters)"
        }
        (Locale::En, Linkage::Complete) => {
            "complete linkage (the largest distance between two clusters)"
        }
        (Locale::En, Linkage::Single) => {
            "single linkage (the smallest distance between two clusters)"
        }
        (Locale::De, Linkage::Average) => "mittleren Abstand zwischen zwei Gruppen",
        (Locale::De, Linkage::Complete) => "größten Abstand zwischen zwei Gruppen",
        (Locale::De, Linkage::Single) => "kleinsten Abstand zwischen zwei Gruppen",
    }
}

/// The opening sentence of a dendrogram: how many items and by which linkage.
pub(crate) fn dendrogram_opening(locale: Locale, items: usize, linkage: Linkage) -> String {
    let phrase = linkage_phrase(locale, linkage);
    match locale {
        Locale::En => format!("Dendrogram of {items} items, joined by {phrase}."),
        Locale::De => format!("Dendrogramm aus {items} Elementen, verbunden nach dem {phrase}."),
    }
}

/// The first join of a dendrogram: the two closest items (or clusters, at a tie of several).
pub(crate) fn closest_pair(
    locale: Locale,
    (left, right): (&[String], &[String]),
    distance: &str,
) -> String {
    let (left, right) = (listed(locale, left), listed(locale, right));
    match locale {
        Locale::En => format!("Closest: {left} and {right} ({distance})."),
        Locale::De => format!("Am nächsten: {left} und {right} ({distance})."),
    }
}

/// The last join of a dendrogram: the two groups it brings together.
pub(crate) fn last_join(
    locale: Locale,
    (left, right): (&[String], &[String]),
    distance: &str,
) -> String {
    let (left, right) = (listed(locale, left), listed(locale, right));
    match locale {
        Locale::En => {
            format!("The last join, at {distance}, brings together two groups: {left}; {right}.")
        }
        Locale::De => format!(
            "Die letzte Verbindung, bei {distance}, führt zwei Gruppen zusammen: {left}; {right}."
        ),
    }
}

/// The items of a dendrogram in the order of the tree.
pub(crate) fn dendrogram_order(locale: Locale, items: &[String]) -> String {
    let items = listed(locale, items);
    match locale {
        Locale::En => format!("Order of the items: {items}."),
        Locale::De => format!("Reihenfolge der Elemente: {items}."),
    }
}

/// The title of a dendrogram's distance axis.
pub(crate) fn distance_axis(locale: Locale, linkage: Linkage) -> String {
    let how = match (locale, linkage) {
        (Locale::En, Linkage::Average) => "average",
        (Locale::En, Linkage::Complete) => "complete",
        (Locale::En, Linkage::Single) => "single",
        (Locale::De, Linkage::Average) => "mittlerer",
        (Locale::De, Linkage::Complete) => "größter",
        (Locale::De, Linkage::Single) => "kleinster",
    };
    match locale {
        Locale::En => format!("Distance at the join ({how} linkage)"),
        Locale::De => format!("Abstand bei der Verbindung ({how} Abstand)"),
    }
}

/// What a step of a flow chart is, for the description and the data table.
pub(crate) const fn node_kind(locale: Locale, kind: NodeKind) -> &'static str {
    match (locale, kind) {
        (Locale::En, NodeKind::Start) => "start",
        (Locale::En, NodeKind::End) => "end",
        (Locale::En, NodeKind::Process) => "step",
        (Locale::En, NodeKind::Decision) => "decision",
        (Locale::En, NodeKind::Io) => "input or output",
        (Locale::En, NodeKind::Subprocess) => "subprocess",
        (Locale::En, NodeKind::Store) => "data store",
        (Locale::En, NodeKind::External) => "external",
        (Locale::De, NodeKind::Start) => "Start",
        (Locale::De, NodeKind::End) => "Ende",
        (Locale::De, NodeKind::Process) => "Schritt",
        (Locale::De, NodeKind::Decision) => "Entscheidung",
        (Locale::De, NodeKind::Io) => "Ein- oder Ausgabe",
        (Locale::De, NodeKind::Subprocess) => "Teilprozess",
        (Locale::De, NodeKind::Store) => "Datenspeicher",
        (Locale::De, NodeKind::External) => "extern",
    }
}

/// One step of a flow chart as a sentence: its label, its kind unless it is a plain step, its
/// lane, and where it leads.
pub(crate) fn flow_step(
    locale: Locale,
    label: &str,
    kind: NodeKind,
    lane: Option<&str>,
    next: &[String],
) -> String {
    let kind = if kind == NodeKind::Process {
        String::new()
    } else {
        format!(" ({})", node_kind(locale, kind))
    };
    // "in" in both languages.
    let lane = lane.map_or_else(String::new, |lane| format!(" in {lane}"));
    let next = match (locale, next.is_empty()) {
        (Locale::En, true) => "no further step".to_owned(),
        (Locale::De, true) => "kein weiterer Schritt".to_owned(),
        (Locale::En, false) => format!("leads to {}", listed(locale, next)),
        (Locale::De, false) => format!("führt zu {}", listed(locale, next)),
    };
    format!("{label}{kind}{lane}: {next}.")
}

/// A group of a flow chart as a sentence.
pub(crate) fn flow_group(locale: Locale, label: &str, members: &[&str]) -> String {
    let members = members.join(", ");
    match locale {
        Locale::En => format!("Group \"{label}\": {members}."),
        Locale::De => format!("Gruppe „{label}“: {members}."),
    }
}

/// The opening sentence of a state diagram: how many states and transitions, where it starts and
/// which states it ends in.
pub(crate) fn state_opening(
    locale: Locale,
    states: usize,
    transitions: usize,
    initial: Option<&str>,
    finals: &[String],
) -> String {
    let mut opening = match locale {
        Locale::En => format!(
            "State diagram with {states} state{} and {transitions} transition{}.",
            plural(states, "", "s"),
            plural(transitions, "", "s"),
        ),
        Locale::De => format!(
            "Zustandsdiagramm mit {states} {} und {transitions} {}.",
            plural(states, "Zustand", "Zuständen"),
            plural(transitions, "Übergang", "Übergängen"),
        ),
    };
    if let Some(initial) = initial {
        let starts = match locale {
            Locale::En => "It starts in",
            Locale::De => "Es beginnt in",
        };
        write!(opening, " {starts} {initial}.").expect("writing to String cannot fail");
    }
    if !finals.is_empty() {
        let noun = match (locale, finals.len()) {
            (Locale::En, 1) => "Final state",
            (Locale::En, _) => "Final states",
            (Locale::De, 1) => "Endzustand",
            (Locale::De, _) => "Endzustände",
        };
        write!(opening, " {noun}: {}.", listed(locale, finals))
            .expect("writing to String cannot fail");
    }
    opening
}

/// One transition as a sentence; `to` is `None` for a transition to the same state.
pub(crate) fn transition(
    locale: Locale,
    from: &str,
    to: Option<&str>,
    label: Option<&str>,
) -> String {
    let on = label.map_or_else(String::new, |label| match locale {
        Locale::En => format!(" on {label}"),
        Locale::De => format!(" bei {label}"),
    });
    match (locale, to) {
        (Locale::En, Some(to)) => format!("{from} to {to}{on}."),
        (Locale::En, None) => format!("{from} to itself{on}."),
        (Locale::De, Some(to)) => format!("{from} nach {to}{on}."),
        (Locale::De, None) => format!("{from} zu sich selbst{on}."),
    }
}

/// A composite state and the states directly inside it, as a sentence.
pub(crate) fn composite(locale: Locale, label: &str, members: &[&str]) -> String {
    let members = members.join(", ");
    match locale {
        Locale::En => format!("Composite state {label} contains {members}."),
        Locale::De => format!("Zusammengesetzter Zustand {label} enthält {members}."),
    }
}

/// The choices of a state diagram, as a sentence.
pub(crate) fn choices(locale: Locale, labels: &[&str]) -> String {
    let labels = labels.join(", ");
    match locale {
        Locale::En => format!("Choices: {labels}."),
        Locale::De => format!("Auswahlpunkte: {labels}."),
    }
}

/// The opening sentence of a tree: how many nodes it has and how many levels they lie in. A
/// radial tree says it is a mind map.
pub(crate) fn tree_opening(locale: Locale, nodes: usize, levels: usize, radial: bool) -> String {
    let kind = match (locale, radial) {
        (Locale::En, false) => "Tree",
        (Locale::En, true) => "Mind map (radial tree)",
        (Locale::De, false) => "Baum",
        (Locale::De, true) => "Mindmap (radialer Baum)",
    };
    match locale {
        Locale::En => format!(
            "{kind} with {nodes} node{} in {levels} level{}.",
            plural(nodes, "", "s"),
            plural(levels, "", "s"),
        ),
        Locale::De => format!(
            "{kind} mit {nodes} {} in {levels} {}.",
            plural(nodes, "Knoten", "Knoten"),
            plural(levels, "Ebene", "Ebenen"),
        ),
    }
}

/// The root of a tree, as a sentence; a radial tree has it in the centre.
pub(crate) fn tree_root(locale: Locale, root: &str, radial: bool) -> String {
    match (locale, radial) {
        (Locale::En, false) => format!("Root: {root}."),
        (Locale::En, true) => format!("Centre: {root}."),
        (Locale::De, false) => format!("Wurzel: {root}."),
        (Locale::De, true) => format!("Mitte: {root}."),
    }
}

/// The nodes of a tree that are drawn collapsed.
pub(crate) fn tree_collapsed(locale: Locale, labels: &[&str]) -> String {
    let labels = labels.join(", ");
    match locale {
        Locale::En => {
            format!("Collapsed in the drawing, with everything below them listed here: {labels}.")
        }
        Locale::De => format!("In der Grafik eingeklappt, alles darunter steht hier: {labels}."),
    }
}

/// The notes of a diagram, one sentence each with the element or frame it explains, if any:
/// `Note on Order: only for existing customers.`, `Note: prices are net.`
pub(crate) fn notes(locale: Locale, notes: &[(Option<&str>, &str)]) -> String {
    let sentences: Vec<String> = notes
        .iter()
        .map(|(on, text)| {
            let text = text.trim();
            let stop = if text.ends_with(['.', '!', '?']) {
                ""
            } else {
                "."
            };
            match (locale, on) {
                (Locale::En, Some(on)) => format!("Note on {on}: {text}{stop}"),
                (Locale::De, Some(on)) => format!("Notiz zu {on}: {text}{stop}"),
                (Locale::En, None) => format!("Note: {text}{stop}"),
                (Locale::De, None) => format!("Notiz: {text}{stop}"),
            }
        })
        .collect();
    sentences.join(" ")
}

/// The opening sentence of a cycle: its steps in order, each as `number label`, and the way back
/// from the last to the first.
pub(crate) fn cycle_opening(locale: Locale, steps: &[String], first: &str) -> String {
    let count = steps.len();
    let noted = steps.iter().any(|step| step.contains('('));
    let steps = if noted {
        steps.join("; ")
    } else {
        steps.join(", ")
    };
    match locale {
        Locale::En => format!("Cycle of {count} steps: {steps}; the last leads back to {first}."),
        Locale::De => {
            format!("Kreislauf aus {count} Schritten: {steps}; der letzte führt zurück zu {first}.")
        }
    }
}

/// The hub of a cycle and the links of the steps to it, each as `label` or `label (hub label)`.
pub(crate) fn cycle_hub(locale: Locale, hub: &str, links: &[String]) -> String {
    let links = if links.is_empty() {
        String::new()
    } else {
        match locale {
            Locale::En => format!(" Links: {}.", links.join("; ")),
            Locale::De => format!(" Verbindungen: {}.", links.join("; ")),
        }
    };
    match locale {
        Locale::En => format!("Every step feeds the hub {hub}.{links}"),
        Locale::De => format!("Jeder Schritt speist die Mitte {hub}.{links}"),
    }
}

/// One layer for the description: `number label`, and in parentheses what it holds.
pub(crate) fn layers_entry(
    locale: Locale,
    (number, label): (usize, &str),
    items: &[String],
    note: Option<&str>,
) -> String {
    let mut details: Vec<String> = Vec::new();
    if !items.is_empty() {
        details.push(match locale {
            Locale::En => format!("items: {}", listed(locale, items)),
            Locale::De => format!("Elemente: {}", listed(locale, items)),
        });
    }
    if let Some(note) = note {
        details.push(match locale {
            Locale::En => format!("note: {note}"),
            Locale::De => format!("Hinweis: {note}"),
        });
    }
    if details.is_empty() {
        format!("{number} {label}")
    } else {
        format!("{number} {label} ({})", details.join("; "))
    }
}

/// The sentence of a layer diagram: how many layers and in which direction they are read.
pub(crate) fn layers_opening(locale: Locale, nested: bool, entries: &[String]) -> String {
    let count = entries.len();
    let entries = entries.join("; ");
    match (locale, nested) {
        (Locale::En, false) => format!(
            "Layer stack of {count} layer{}, from the bottom: {entries}.",
            plural(count, "", "s")
        ),
        (Locale::En, true) => format!(
            "{count} nested scope{}, from the outermost to the innermost: {entries}.",
            plural(count, "", "s")
        ),
        (Locale::De, false) => format!(
            "Schichtenstapel aus {count} {}, von unten nach oben: {entries}.",
            plural(count, "Schicht", "Schichten")
        ),
        (Locale::De, true) => format!(
            "{count} ineinander liegende {}, vom äußersten zum innersten: {entries}.",
            plural(count, "Bereich", "Bereiche")
        ),
    }
}

/// The name of the kind of an area.
pub(crate) const fn area_kind(locale: Locale, kind: AreaKind) -> &'static str {
    match (locale, kind) {
        (Locale::En, AreaKind::Room) => "room",
        (Locale::En, AreaKind::Building) => "building",
        (Locale::En, AreaKind::Outdoor) => "outdoor",
        (Locale::De, AreaKind::Room) => "Raum",
        (Locale::De, AreaKind::Building) => "Gebäude",
        (Locale::De, AreaKind::Outdoor) => "Außenbereich",
    }
}

/// The name of a piece of furniture.
pub(crate) const fn item_kind(locale: Locale, kind: ItemKind) -> &'static str {
    match (locale, kind) {
        (Locale::En, ItemKind::Desk) => "desk",
        (Locale::En, ItemKind::Shelf) => "shelf",
        (Locale::En, ItemKind::Table) => "table",
        (Locale::En, ItemKind::Bed) => "bed",
        (Locale::En, ItemKind::Sofa) => "sofa",
        (Locale::En, ItemKind::Plant) => "plant",
        (Locale::De, ItemKind::Desk) => "Schreibtisch",
        (Locale::De, ItemKind::Shelf) => "Regal",
        (Locale::De, ItemKind::Table) => "Tisch",
        (Locale::De, ItemKind::Bed) => "Bett",
        (Locale::De, ItemKind::Sofa) => "Sofa",
        (Locale::De, ItemKind::Plant) => "Pflanze",
    }
}

/// The line under the label of an area: its kind, its size and its phase.
pub(crate) fn plan_detail(
    locale: Locale,
    kind: AreaKind,
    (width, depth): (&str, &str),
    phase: Option<&str>,
) -> String {
    let mut line = format!("{}, {width} × {depth}", area_kind(locale, kind));
    if let Some(phase) = phase {
        line.push_str(", ");
        line.push_str(phase);
    }
    line
}

/// One area for the description: label, kind, size, phase and furniture.
pub(crate) fn plan_area(
    locale: Locale,
    label: &str,
    kind: AreaKind,
    size: (&str, &str),
    phase: Option<&str>,
    items: &[ItemKind],
) -> String {
    let mut line = format!("{label} ({}", plan_detail(locale, kind, size, phase));
    if !items.is_empty() {
        let names: Vec<String> = items
            .iter()
            .map(|item| item_kind(locale, *item).to_owned())
            .collect();
        match locale {
            Locale::En => write!(line, ", with {}", listed(locale, &names)),
            Locale::De => write!(line, ", mit {}", listed(locale, &names)),
        }
        .expect("writing to String cannot fail");
    }
    line.push(')');
    line
}

/// The opening sentence of a plan: how many areas on how large a grid, and the areas.
pub(crate) fn plan_opening(
    locale: Locale,
    areas: usize,
    (width, depth): (&str, &str),
    entries: &[String],
) -> String {
    let entries = entries.join("; ");
    match locale {
        Locale::En => format!(
            "Plan with {areas} area{} on a grid of {width} × {depth} units, seen at an angle: {entries}.",
            plural(areas, "", "s")
        ),
        Locale::De => format!(
            "Grundriss mit {areas} {} auf einem Raster von {width} × {depth} Einheiten, schräg von oben gesehen: {entries}.",
            plural(areas, "Bereich", "Bereichen")
        ),
    }
}

/// What each phase holds.
pub(crate) fn plan_phases(locale: Locale, phases: &[(String, Vec<String>)]) -> String {
    let phases: Vec<String> = phases
        .iter()
        .map(|(phase, areas)| format!("{phase}: {}", listed(locale, areas)))
        .collect();
    let phases = phases.join("; ");
    match locale {
        Locale::En => format!("Phases: {phases}."),
        Locale::De => format!("Phasen: {phases}."),
    }
}

/// What about a component can change between two states.
#[derive(Debug, Clone, Copy)]
pub(crate) enum DeltaField {
    Label,
    Technology,
    Kind,
}

/// One changed field of a component: `label: Old → New`.
pub(crate) fn delta_field(locale: Locale, field: DeltaField, old: &str, new: &str) -> String {
    let name = match (locale, field) {
        (Locale::En, DeltaField::Label) => "label",
        (Locale::En, DeltaField::Technology) => "technology",
        (Locale::En, DeltaField::Kind) => "kind",
        (Locale::De, DeltaField::Label) => "Bezeichnung",
        (Locale::De, DeltaField::Technology) => "Technologie",
        (Locale::De, DeltaField::Kind) => "Art",
    };
    format!("{name}: {old} → {new}")
}

/// The place of a component that is in no boundary.
pub(crate) const fn delta_unbounded(locale: Locale) -> &'static str {
    match locale {
        Locale::En => "no boundary",
        Locale::De => "keine Grenze",
    }
}

/// A component that moved: `from A to B`.
pub(crate) fn delta_moved(locale: Locale, from: &str, to: &str) -> String {
    match locale {
        Locale::En => format!("from {from} to {to}"),
        Locale::De => format!("von {from} nach {to}"),
    }
}

/// A connection one state has and the other lacks.
pub(crate) fn delta_connection(locale: Locale, added: bool) -> String {
    match (locale, added) {
        (Locale::En, true) => "added".to_owned(),
        (Locale::En, false) => "removed".to_owned(),
        (Locale::De, true) => "hinzugefügt".to_owned(),
        (Locale::De, false) => "entfernt".to_owned(),
    }
}

/// A connection whose text changed: `old → new`, an empty text written as a dash.
pub(crate) fn delta_connection_text(locale: Locale, old: &str, new: &str) -> String {
    let dash = |text: &str| {
        if text.is_empty() {
            "–".to_owned()
        } else {
            text.to_owned()
        }
    };
    match locale {
        Locale::En => format!("text: {} → {}", dash(old), dash(new)),
        Locale::De => format!("Text: {} → {}", dash(old), dash(new)),
    }
}

/// The name of a kind of change.
pub(crate) const fn delta_kind(locale: Locale, kind: DeltaKind) -> &'static str {
    match (locale, kind) {
        (Locale::En, DeltaKind::Added) => "added",
        (Locale::En, DeltaKind::Removed) => "removed",
        (Locale::En, DeltaKind::Changed) => "changed",
        (Locale::En, DeltaKind::Moved) => "moved",
        (Locale::En, DeltaKind::Rewired) => "rewired",
        (Locale::De, DeltaKind::Added) => "hinzugefügt",
        (Locale::De, DeltaKind::Removed) => "entfernt",
        (Locale::De, DeltaKind::Changed) => "geändert",
        (Locale::De, DeltaKind::Moved) => "verschoben",
        (Locale::De, DeltaKind::Rewired) => "umverdrahtet",
    }
}

/// The kinds of change, for [`delta_kind`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DeltaKind {
    Added,
    Removed,
    Changed,
    Moved,
    Rewired,
}

/// The opening sentence of a delta: the two states and how many changes lie between them.
pub(crate) fn delta_opening(
    locale: Locale,
    (before, after): (&str, &str),
    changes: usize,
) -> String {
    match (locale, changes) {
        (Locale::En, 0) => format!("Architecture change from {before} to {after}: no changes."),
        (Locale::En, count) => format!(
            "Architecture change from {before} to {after}: {count} change{}.",
            plural(count, "", "s")
        ),
        (Locale::De, 0) => {
            format!("Architekturänderung von {before} zu {after}: keine Änderungen.")
        }
        (Locale::De, count) => format!(
            "Architekturänderung von {before} zu {after}: {count} {}.",
            plural(count, "Änderung", "Änderungen")
        ),
    }
}

/// One group of the ledger: `Added: A, B.`; entries with a detail read `A (detail)`.
pub(crate) fn delta_group(locale: Locale, kind: DeltaKind, entries: &[String]) -> String {
    let name = delta_kind(locale, kind);
    let mut name = name.to_owned();
    if let Some(first) = name.get_mut(0..1) {
        first.make_ascii_uppercase();
    }
    format!("{name}: {}.", entries.join("; "))
}

/// The heading of one panel: `Before: Today`.
pub(crate) fn delta_state(locale: Locale, after: bool, title: &str) -> String {
    match (locale, after) {
        (Locale::En, false) => format!("Before: {title}"),
        (Locale::En, true) => format!("After: {title}"),
        (Locale::De, false) => format!("Vorher: {title}"),
        (Locale::De, true) => format!("Nachher: {title}"),
    }
}

/// The heading of the ledger.
pub(crate) const fn delta_ledger(locale: Locale) -> &'static str {
    match locale {
        Locale::En => "Changes",
        Locale::De => "Änderungen",
    }
}

/// The ledger of a delta without changes.
pub(crate) const fn delta_none(locale: Locale) -> &'static str {
    match locale {
        Locale::En => "No changes.",
        Locale::De => "Keine Änderungen.",
    }
}