chartlet 0.18.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
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
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
//! The words chartlet writes itself, per locale: descriptions, legend additions, tooltips and
//! the HTML figure. Text from the specification is never translated.

use std::fmt::Write as _;

use crate::spec::{ComponentKind, FragmentSpec, Locale, MessageKind, NodeKind, ParticipantKind};

pub(crate) struct Words {
    pub value: &'static str,
    pub lower: &'static str,
    pub upper: &'static str,
    pub modeled: &'static str,
    pub from: &'static str,
    pub to: &'static str,
    pub range: &'static str,
    pub at: &'static str,
    pub highest: &'static str,
    pub lowest: &'static str,
    pub all_values: &'static str,
    pub reference_lines: &'static str,
    pub zones: &'static str,
    pub markers: &'static str,
    pub source: &'static str,
    pub show_data: &'static str,
    pub data_for: &'static str,
    pub time: &'static str,
    /// The first column of a chart along a numeric axis without a title.
    pub position: &'static str,
    pub missing: &'static str,
    pub series: &'static str,
    pub view: &'static str,
    pub category: &'static str,
    pub year: &'static str,
    pub date: &'static str,
    pub topic: &'static str,
    pub region: &'static str,
    pub area: &'static str,
    pub entries: &'static str,
    pub paths: &'static str,
    pub share: &'static str,
    pub places: &'static str,
    pub range_low: &'static str,
    pub range_mid: &'static str,
    pub range_high: &'static str,
    pub hatched_modeled: &'static str,
    pub no_value: &'static str,
    pub open: &'static str,
    pub high: &'static str,
    pub low: &'static str,
    pub close: &'static str,
    pub candle_key: &'static str,
    pub pane: &'static str,
    /// The columns of a sequence diagram's table.
    pub number: &'static str,
    pub sender: &'static str,
    pub receiver: &'static str,
    pub message: &'static str,
    pub message_kind: &'static str,
    pub fragment: &'static str,
    /// The columns of a flow chart's table.
    pub step: &'static str,
    pub lane: &'static str,
    pub group: &'static str,
    pub leads_to: &'static str,
    pub at_risk: &'static str,
    pub point: &'static str,
    pub number_at_risk: &'static str,
    pub survival: &'static str,
    /// The columns of a state diagram's table, and the name of its initial dot.
    pub event: &'static str,
    pub guard: &'static str,
    pub action: &'static str,
    pub next_state: &'static str,
    pub start: &'static str,
    /// The columns of an architecture diagram's table.
    pub component: &'static str,
    pub boundary: &'static str,
    pub connects_to: &'static str,
    /// The columns of a tree's table.
    pub node: &'static str,
    pub level: &'static str,
    pub parent: &'static str,
    pub link: &'static str,
    pub children: &'static str,
    pub collapsed: &'static str,
    pub partner: &'static str,
    /// The columns of a boxplot's table.
    pub minimum: &'static str,
    pub quartile_1: &'static str,
    pub median: &'static str,
    pub mean: &'static str,
    pub quartile_3: &'static str,
    pub maximum: &'static str,
    pub outliers: &'static str,
    pub observations: &'static str,
    pub interval: &'static str,
    pub weight: &'static str,
    pub summary: &'static str,
    /// The columns of a timeline's table.
    pub item: &'static str,
    pub phase: &'static str,
    pub attributes: &'static str,
    pub methods: &'static str,
    pub relations: &'static str,
    pub progress: &'static str,
    pub milestone: &'static str,
    pub begin: &'static str,
    pub finish: &'static str,
    pub follows: &'static str,
    /// The columns of a waterfall's table.
    pub total: &'static str,
    pub step_delta: &'static str,
    pub step_start: &'static str,
    /// The columns of a waffle's table, and the name of what its parts leave over.
    pub part: &'static str,
    pub squares: &'static str,
    pub rest: &'static str,
    /// The words of a parliament chart.
    pub party: &'static str,
    pub seats: &'static str,
    pub seat: &'static str,
    pub coalition: &'static str,
    pub majority: &'static str,
    pub yes: &'static str,
    /// The names of a diagram's focus links, and of the link that clears the focus.
    pub focus: &'static str,
    pub show_all: &'static str,
    pub months: [&'static str; 12],
    pub weekdays: [&'static str; 7],
}

const EN: Words = Words {
    value: "Value",
    lower: "lower",
    upper: "upper",
    modeled: "modelled",
    from: "from",
    to: "to",
    range: "range",
    at: "at",
    highest: "Highest",
    lowest: "Lowest",
    all_values: "All values",
    reference_lines: "Reference lines",
    zones: "Zones",
    markers: "Markers",
    source: "Source",
    show_data: "Show chart data",
    data_for: "Data for",
    time: "Time",
    position: "Position",
    missing: "Missing",
    series: "Series",
    view: "View",
    category: "Category",
    year: "Year",
    date: "Date",
    topic: "Topic",
    region: "Region",
    area: "Area",
    entries: "Entries",
    paths: "Paths",
    share: "Share",
    places: "Places",
    range_low: "Low",
    range_mid: "Mid",
    range_high: "High",
    hatched_modeled: "Hatched: modelled",
    no_value: "no value",
    open: "open",
    high: "high",
    low: "low",
    close: "close",
    candle_key: "hollow: rising, filled: falling",
    pane: "Pane",
    number: "No.",
    sender: "From",
    receiver: "To",
    message: "Message",
    message_kind: "Kind",
    fragment: "Fragment",
    step: "Step",
    lane: "Lane",
    group: "Group",
    leads_to: "Leads to",
    at_risk: "At risk",
    point: "Point",
    number_at_risk: "Number at risk",
    survival: "Survival",
    event: "Event",
    guard: "Guard",
    action: "Action",
    next_state: "To",
    start: "Start",
    component: "Component",
    node: "Node",
    level: "Level",
    parent: "Parent",
    link: "Link",
    children: "Children",
    collapsed: "Collapsed",
    partner: "Partner",
    minimum: "Minimum",
    quartile_1: "Q1",
    median: "Median",
    mean: "Mean",
    quartile_3: "Q3",
    maximum: "Maximum",
    outliers: "Outliers",
    observations: "Observations",
    interval: "Interval",
    weight: "Weight",
    summary: "summary",
    item: "Item",
    phase: "Phase",
    attributes: "Attributes",
    methods: "Methods",
    relations: "Relations",
    progress: "Progress",
    milestone: "Milestone",
    begin: "Start",
    finish: "End",
    follows: "After",
    total: "Total",
    step_delta: "Change",
    step_start: "Start",
    part: "Part",
    squares: "Squares",
    rest: "Rest",
    party: "Party",
    seats: "Seats",
    seat: "seat",
    coalition: "Coalition",
    majority: "majority",
    yes: "yes",
    boundary: "Boundary",
    connects_to: "Connects to",
    focus: "Focus",
    show_all: "Show all",
    months: [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
    ],
    weekdays: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
};

const DE: Words = Words {
    value: "Wert",
    lower: "unten",
    upper: "oben",
    modeled: "modelliert",
    from: "von",
    to: "bis",
    range: "Spanne",
    at: "bei",
    highest: "Höchster Wert",
    lowest: "Niedrigster Wert",
    all_values: "Alle Werte",
    reference_lines: "Bezugslinien",
    zones: "Bereiche",
    markers: "Markierungen",
    source: "Quelle",
    show_data: "Diagrammdaten anzeigen",
    data_for: "Daten zu",
    time: "Zeit",
    position: "Position",
    missing: "fehlt",
    series: "Reihen",
    view: "Ansicht",
    category: "Kategorie",
    year: "Jahr",
    date: "Datum",
    topic: "Thema",
    region: "Region",
    area: "Gebiet",
    entries: "Einträge",
    paths: "Pfade",
    share: "Anteil",
    places: "Orte",
    range_low: "Unterer Wert",
    range_mid: "Mittlerer Wert",
    range_high: "Oberer Wert",
    hatched_modeled: "Schraffiert: modelliert",
    no_value: "kein Wert",
    open: "Eröffnung",
    high: "Hoch",
    low: "Tief",
    close: "Schluss",
    candle_key: "hohl: steigend, gefüllt: fallend",
    pane: "Teildiagramm",
    number: "Nr.",
    sender: "Von",
    receiver: "An",
    message: "Nachricht",
    message_kind: "Art",
    fragment: "Abschnitt",
    step: "Schritt",
    lane: "Bahn",
    group: "Gruppe",
    leads_to: "Führt zu",
    at_risk: "Unter Risiko",
    point: "Punkt",
    number_at_risk: "Anzahl unter Risiko",
    survival: "Überleben",
    event: "Ereignis",
    guard: "Bedingung",
    action: "Aktion",
    next_state: "Nach",
    start: "Start",
    component: "Komponente",
    node: "Knoten",
    level: "Ebene",
    parent: "Übergeordnet",
    link: "Verknüpfung",
    children: "Untergeordnet",
    collapsed: "Eingeklappt",
    partner: "Partner",
    minimum: "Minimum",
    quartile_1: "Q1",
    median: "Median",
    mean: "Mittelwert",
    quartile_3: "Q3",
    maximum: "Maximum",
    outliers: "Ausreißer",
    observations: "Beobachtungen",
    interval: "Intervall",
    weight: "Gewicht",
    summary: "Gesamt",
    item: "Eintrag",
    phase: "Phase",
    attributes: "Attribute",
    methods: "Methoden",
    relations: "Beziehungen",
    progress: "Fortschritt",
    milestone: "Meilenstein",
    begin: "Beginn",
    finish: "Ende",
    follows: "Nach",
    total: "Summe",
    step_delta: "Änderung",
    step_start: "Start",
    part: "Teil",
    squares: "Felder",
    rest: "Rest",
    party: "Partei",
    seats: "Sitze",
    seat: "Sitz",
    coalition: "Koalition",
    majority: "Mehrheit",
    yes: "ja",
    boundary: "Grenze",
    connects_to: "Verbunden mit",
    focus: "Fokus",
    show_all: "Alle zeigen",
    months: [
        "Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez",
    ],
    weekdays: ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"],
};

impl Locale {
    pub(crate) const fn words(self) -> &'static Words {
        match self {
            Self::En => &EN,
            Self::De => &DE,
        }
    }
}

/// Where a value lies, for the extremes of a description: `Budget in Feb` or `Budget, Feb`.
pub(crate) fn series_at(locale: Locale, name: &str, category: &str) -> String {
    match locale {
        Locale::En => format!("{name} in {category}"),
        Locale::De => format!("{name}, {category}"),
    }
}

/// The span of time a zone covers: both ends, or the one that is given.
pub(crate) fn zone_times(locale: Locale, from: Option<&str>, to: Option<&str>) -> Option<String> {
    match (locale, from, to) {
        (Locale::En, Some(from), Some(to)) => Some(format!("{from} to {to}")),
        (Locale::De, Some(from), Some(to)) => Some(format!("{from} bis {to}")),
        (Locale::En, Some(from), None) => Some(format!("from {from}")),
        (Locale::De, Some(from), None) => Some(format!("ab {from}")),
        (Locale::En, None, Some(to)) => Some(format!("until {to}")),
        (Locale::De, None, Some(to)) => Some(format!("bis {to}")),
        (_, None, None) => None,
    }
}

/// The range of values a zone covers: both edges, or the one that is given.
pub(crate) fn zone_values(
    locale: Locale,
    bottom: Option<&str>,
    top: Option<&str>,
) -> Option<String> {
    match (locale, bottom, top) {
        (Locale::En, Some(bottom), Some(top)) => Some(format!("values {bottom} to {top}")),
        (Locale::De, Some(bottom), Some(top)) => Some(format!("Werte {bottom} bis {top}")),
        (Locale::En, Some(bottom), None) => Some(format!("values above {bottom}")),
        (Locale::De, Some(bottom), None) => Some(format!("Werte über {bottom}")),
        (Locale::En, None, Some(top)) => Some(format!("values below {top}")),
        (Locale::De, None, Some(top)) => Some(format!("Werte unter {top}")),
        (_, None, None) => None,
    }
}

/// The opening sentence of a time chart.
pub(crate) fn time_opening(
    locale: Locale,
    points: usize,
    range: &str,
    names: &[String],
    modeled: bool,
) -> String {
    let point = plural(points, "point", "points");
    let punkt = plural(points, "Punkt", "Punkten");
    match (locale, names.len() > 1) {
        (Locale::En, true) => format!(
            "Time chart with {points} {point} {range} and {} series ({}).",
            names.len(),
            names.join(", ")
        ),
        (Locale::De, true) => format!(
            "Zeitreihe mit {points} {punkt} {range} und {} Reihen ({}).",
            names.len(),
            names.join(", ")
        ),
        (Locale::En, false) if modeled => {
            format!("Time chart with {points} {point} {range}, modelled.")
        }
        (Locale::De, false) if modeled => {
            format!("Zeitreihe mit {points} {punkt} {range}, modelliert.")
        }
        (Locale::En, false) => format!("Time chart with {points} {point} {range}."),
        (Locale::De, false) => format!("Zeitreihe mit {points} {punkt} {range}."),
    }
}

/// An opening sentence for a chart along a numeric axis, which is a line chart rather than a time
/// chart: the noun is replaced, the rest stays.
pub(crate) fn axis_noun(locale: Locale, zone: crate::time::TimeZone, opening: String) -> String {
    if !zone.is_numeric() {
        return opening;
    }
    let (time, line) = match locale {
        Locale::En => ("Time chart", "Line chart"),
        Locale::De => ("Zeitreihe", "Liniendiagramm"),
    };
    match opening.strip_prefix(time) {
        Some(rest) => format!("{line}{rest}"),
        None => opening,
    }
}

/// The opening sentence of small multiples: a time chart in panels, laid out in a grid.
pub(crate) fn multiples_opening(
    locale: Locale,
    panels: &[String],
    range: &str,
    names: &[String],
    shared: bool,
) -> String {
    let axis = match (locale, shared) {
        (Locale::En, true) => "a shared value axis",
        (Locale::En, false) => "a value axis of their own",
        (Locale::De, true) => "gemeinsamer Werteachse",
        (Locale::De, false) => "je eigener Werteachse",
    };
    let mut text = match locale {
        Locale::En => format!(
            "Time chart in {} {} ({}) with {axis}, each {range}",
            panels.len(),
            plural(panels.len(), "panel", "panels"),
            panels.join(", ")
        ),
        Locale::De => format!(
            "Zeitreihe in {} {} ({}) mit {axis}, jeweils {range}",
            panels.len(),
            plural(panels.len(), "Feld", "Feldern"),
            panels.join(", ")
        ),
    };
    if names.len() > 1 {
        let showing = match locale {
            Locale::En => "showing",
            Locale::De => "mit",
        };
        text.push_str(", ");
        text.push_str(showing);
        text.push(' ');
        text.push_str(&names.join(", "));
    }
    text.push('.');
    text
}

/// The sentence that names the stacked panes of a time chart.
pub(crate) fn panes(locale: Locale, labels: &[String]) -> String {
    match locale {
        Locale::En => format!(
            " {} stacked panes on one time axis: {}.",
            labels.len(),
            labels.join(", ")
        ),
        Locale::De => format!(
            " {} übereinanderliegende Teildiagramme auf einer Zeitachse: {}.",
            labels.len(),
            labels.join(", ")
        ),
    }
}

/// The four values of a candle, for its tooltip: open, high, low and close, already written.
pub(crate) fn candle_values(locale: Locale, values: &[String; 4]) -> String {
    let words = locale.words();
    // A German number carries a decimal comma, so its values are kept apart by semicolons.
    let separator = match locale {
        Locale::En => ", ",
        Locale::De => "; ",
    };
    [words.open, words.high, words.low, words.close]
        .iter()
        .zip(values)
        .map(|(word, value)| format!("{word} {value}"))
        .collect::<Vec<_>>()
        .join(separator)
}

/// What a candlestick layer says in a description: where it opened and closed, how much it
/// changed, and its highest high and lowest low. Every value comes written, each with its time;
/// `percent` is missing when the first open is zero.
pub(crate) struct CandleSummary<'a> {
    pub name: Option<&'a str>,
    pub open: (&'a str, &'a str),
    pub close: (&'a str, &'a str),
    pub change: &'a str,
    pub percent: Option<&'a str>,
    pub high: (&'a str, &'a str),
    pub low: (&'a str, &'a str),
}

/// The sentence about one candlestick layer, see [`CandleSummary`].
pub(crate) fn candles(locale: Locale, summary: &CandleSummary) -> String {
    let percent = summary
        .percent
        .map_or_else(String::new, |percent| format!(" ({percent})"));
    let name = summary
        .name
        .map_or_else(String::new, |name| format!("{name}: "));
    let CandleSummary {
        open,
        close,
        high,
        low,
        change,
        ..
    } = summary;
    match (locale, summary.name.is_some()) {
        (Locale::En, named) => format!(
            " {name}{} at {} on {} and closed at {} on {}, a change of {change}{percent}; high {} on {}, low {} on {}.",
            if named { "opened" } else { "Opened" },
            open.0,
            open.1,
            close.0,
            close.1,
            high.0,
            high.1,
            low.0,
            low.1,
        ),
        (Locale::De, _) => format!(
            " {name}Eröffnung {} am {}, Schluss {} am {}, Veränderung {change}{percent}; Hoch {} am {}, Tief {} am {}.",
            open.0, open.1, close.0, close.1, high.0, high.1, low.0, low.1,
        ),
    }
}

/// The sentence about uncertainty bands.
pub(crate) fn bands(locale: Locale, banded: usize, hatched: bool) -> String {
    match locale {
        Locale::En => format!(
            " {} a shaded band from {} lower to {} upper bound{}; the data table lists both.",
            plural(banded, "One line has", "Lines have"),
            plural(banded, "its", "their"),
            plural(banded, "its", "their"),
            if hatched {
                ", hatched where modelled"
            } else {
                ""
            }
        ),
        Locale::De => format!(
            " {} ein schattiertes Band von der unteren bis zur oberen Grenze{}; die Datentabelle nennt beide.",
            plural(banded, "Eine Linie hat", "Linien haben je"),
            if hatched {
                ", schraffiert, wo modelliert"
            } else {
                ""
            }
        ),
    }
}

/// The opening sentence of small multiples of bars: a bar chart in panels, laid out in a grid.
pub(crate) fn panel_bars_opening(locale: Locale, panels: usize, categories: usize) -> String {
    match locale {
        Locale::En => format!(
            "Bar chart in {panels} {} over {categories} {}, each with its own value axis.",
            plural(panels, "panel", "panels"),
            plural(categories, "category", "categories")
        ),
        Locale::De => format!(
            "Balkendiagramm in {panels} {} über {categories} {}, jedes mit eigener Wertachse.",
            plural(panels, "Feld", "Feldern"),
            plural(categories, "Kategorie", "Kategorien")
        ),
    }
}

/// The notes under the panel titles of small multiples, as `title: note` separated by semicolons.
pub(crate) fn panel_notes(locale: Locale, notes: &str) -> String {
    match locale {
        Locale::En => format!(" Notes: {notes}."),
        Locale::De => format!(" Hinweise: {notes}."),
    }
}

/// Stacked areas, named from the bottom up.
pub(crate) fn stacked_areas(locale: Locale, names: &str) -> String {
    match locale {
        Locale::En => {
            format!(" Stacked areas, from the bottom up: {names}; the top edge shows their total.")
        }
        Locale::De => format!(
            " Gestapelte Flächen, von unten nach oben: {names}; die Oberkante zeigt ihre Summe."
        ),
    }
}

/// The sentence about area layers; `names` lists them, empty for a single unnamed one.
pub(crate) fn areas(locale: Locale, names: &[String]) -> String {
    match (locale, names.len()) {
        (Locale::En, 0) => " The area below the line is filled down to zero.".to_owned(),
        (Locale::En, 1) => format!(" The area below {} is filled down to zero.", names[0]),
        (Locale::En, _) => format!(
            " The areas below {} are filled down to zero.",
            names.join(", ")
        ),
        (Locale::De, 0) => " Die Fläche unter der Linie ist bis null gefüllt.".to_owned(),
        (Locale::De, 1) => format!(" Die Fläche unter {} ist bis null gefüllt.", names[0]),
        (Locale::De, _) => format!(
            " Die Flächen unter {} sind bis null gefüllt.",
            names.join(", ")
        ),
    }
}

/// `one` for a count of one, otherwise `many`.
const fn plural(count: usize, one: &'static str, many: &'static str) -> &'static str {
    if count == 1 { one } else { many }
}

/// The name of a bar or a line chart.
const fn chart_name(locale: Locale, line: bool) -> &'static str {
    match (locale, line) {
        (Locale::En, false) => "Bar chart",
        (Locale::En, true) => "Line chart",
        (Locale::De, false) => "Balkendiagramm",
        (Locale::De, true) => "Liniendiagramm",
    }
}

/// The whole description of a bar or line chart whose values are all equal.
pub(crate) fn equal_values(locale: Locale, line: bool, categories: usize, value: &str) -> String {
    let chart = chart_name(locale, line);
    match locale {
        Locale::En if categories == 1 => format!("{chart} with 1 value: {value}."),
        Locale::En => format!("{chart} with {categories} equal values: {value} each."),
        Locale::De if categories == 1 => format!("{chart} mit 1 Wert: {value}."),
        Locale::De => format!("{chart} mit {categories} gleichen Werten: jeweils {value}."),
    }
}

/// The opening sentence of a bar or line chart; `names` lists the series of a grouped chart.
pub(crate) fn categories_opening(
    locale: Locale,
    line: bool,
    categories: usize,
    series: usize,
    names: &str,
) -> String {
    let chart = chart_name(locale, line);
    match (locale, series > 1) {
        (Locale::En, true) => format!(
            "{chart} with {categories} {} and {series} series ({names}).",
            plural(categories, "category", "categories")
        ),
        (Locale::De, true) => format!(
            "{chart} mit {categories} {} und {series} Reihen ({names}).",
            plural(categories, "Kategorie", "Kategorien")
        ),
        (Locale::En, false) => format!(
            "{chart} with {categories} {}.",
            plural(categories, "category", "categories")
        ),
        (Locale::De, false) => format!(
            "{chart} mit {categories} {}.",
            plural(categories, "Kategorie", "Kategorien")
        ),
    }
}

/// The sentence about missing values of a grouped chart or a time chart, empty when none is
/// missing.
pub(crate) fn missing_values(locale: Locale, missing: usize) -> String {
    match (locale, missing) {
        (_, 0) => String::new(),
        (Locale::En, 1) => " 1 value is missing.".to_owned(),
        (Locale::En, missing) => format!(" {missing} values are missing."),
        (Locale::De, 1) => " 1 Wert fehlt.".to_owned(),
        (Locale::De, missing) => format!(" {missing} Werte fehlen."),
    }
}

/// The sentence about a stack by value: its highest and lowest total, with their categories.
pub(crate) fn stacked_totals(
    locale: Locale,
    (highest, highest_at): (&str, &str),
    (lowest, lowest_at): (&str, &str),
) -> String {
    match locale {
        Locale::En => format!(
            " The series are stacked. Highest total: {highest} ({highest_at}). Lowest total: {lowest} ({lowest_at})."
        ),
        Locale::De => format!(
            " Die Reihen sind gestapelt. Höchste Summe: {highest} ({highest_at}). Niedrigste Summe: {lowest} ({lowest_at})."
        ),
    }
}

/// The sentence about a percent stack: every bar shows shares of its category's total.
pub(crate) const fn stacked_shares(locale: Locale) -> &'static str {
    match locale {
        Locale::En => " Each bar shows the shares of the series in its category's total.",
        Locale::De => " Jeder Balken zeigt die Anteile der Reihen an der Summe seiner Kategorie.",
    }
}

/// The sentence of a time axis whose gaps are collapsed: observations sit side by side, so the
/// distance between them no longer stands for time.
pub(crate) const fn gaps_collapsed(locale: Locale) -> &'static str {
    match locale {
        Locale::En => " Gaps in time are closed up.",
        Locale::De => " Zeiträume ohne Beobachtung sind ausgelassen.",
    }
}

/// The diverging color scale of stripes and calendars, as part of a sentence.
pub(crate) fn diverging_scale(locale: Locale, reference: &str, min: &str, max: &str) -> String {
    match locale {
        Locale::En => format!(
            "on a diverging color scale around {reference} with its outermost steps at {min} and {max}"
        ),
        Locale::De => format!(
            "auf einer divergierenden Farbskala um {reference} mit den äußersten Stufen bei {min} und {max}"
        ),
    }
}

/// The opening sentence of warming stripes.
pub(crate) fn stripes_opening(locale: Locale, first: i32, last: i32, scale: &str) -> String {
    match locale {
        Locale::En if first == last => format!("Warming stripes for {first}, one stripe, {scale}."),
        Locale::De if first == last => format!("Wärmestreifen für {first}, ein Streifen, {scale}."),
        Locale::En => {
            format!("Warming stripes from {first} to {last}, one stripe per year, {scale}.")
        }
        Locale::De => {
            format!("Wärmestreifen von {first} bis {last}, ein Streifen pro Jahr, {scale}.")
        }
    }
}

/// The sentence about years of warming stripes without a value, empty when there is none.
pub(crate) fn years_without_value(locale: Locale, missing: usize) -> String {
    match (locale, missing) {
        (_, 0) => String::new(),
        (Locale::En, 1) => " 1 year has no value.".to_owned(),
        (Locale::En, missing) => format!(" {missing} years have no value."),
        (Locale::De, 1) => " 1 Jahr hat keinen Wert.".to_owned(),
        (Locale::De, missing) => format!(" {missing} Jahre haben keinen Wert."),
    }
}

/// The opening sentences of a calendar: its year, its arrangement, its scale and its coverage.
pub(crate) fn calendar_opening(
    locale: Locale,
    year: i32,
    weeks: bool,
    scale: &str,
    days: usize,
    length: i64,
) -> String {
    match locale {
        Locale::En => format!(
            "Calendar of {year} with {}, {scale}. {days} of {length} days {} a value.",
            if weeks {
                "one row per weekday and one column per week"
            } else {
                "one row per month"
            },
            plural(days, "has", "have")
        ),
        Locale::De => format!(
            "Kalender {year} mit {}, {scale}. {days} von {length} Tagen {} einen Wert.",
            if weeks {
                "einer Zeile pro Wochentag und einer Spalte pro Woche"
            } else {
                "einer Zeile pro Monat"
            },
            plural(days, "hat", "haben")
        ),
    }
}

/// The opening sentences of a range chart: its spans and their outermost ends, each given as
/// value and label.
pub(crate) fn rangebar_opening(
    locale: Locale,
    categories: usize,
    mid: bool,
    lowest: (&str, &str),
    highest: (&str, &str),
) -> String {
    match locale {
        Locale::En => format!(
            "Range chart with {categories} {}, each a span from low to high{}. Lowest low: {} ({}). Highest high: {} ({}).",
            plural(categories, "category", "categories"),
            if mid { " and a central value" } else { "" },
            lowest.0,
            lowest.1,
            highest.0,
            highest.1,
        ),
        Locale::De => format!(
            "Spannweitendiagramm mit {categories} {}, jeweils eine Spanne vom unteren zum oberen Wert{}. Niedrigster unterer Wert: {} ({}). Höchster oberer Wert: {} ({}).",
            plural(categories, "Kategorie", "Kategorien"),
            if mid { " mit einem mittleren Wert" } else { "" },
            lowest.0,
            lowest.1,
            highest.0,
            highest.1,
        ),
    }
}

/// The groups of a range bar chart, each with the labels of its spans, as `group: labels`
/// separated by semicolons.
pub(crate) fn range_groups(locale: Locale, groups: &str) -> String {
    match locale {
        Locale::En => format!(" Colors show groups: {groups}."),
        Locale::De => format!(" Farben zeigen Gruppen: {groups}."),
    }
}

/// The sentence that names the modeled spans of a range chart.
pub(crate) fn modeled_ranges(locale: Locale, labels: &str) -> String {
    match locale {
        Locale::En => format!(" Modelled, drawn hatched: {labels}."),
        Locale::De => format!(" Modelliert, schraffiert gezeichnet: {labels}."),
    }
}

/// The opening sentences of a topic map: its areas and islands, and the largest and smallest
/// topic, each given as label and value.
pub(crate) fn topicmap_opening(
    locale: Locale,
    areas: usize,
    islands: usize,
    largest: (&str, &str),
    smallest: (&str, &str),
) -> String {
    match locale {
        Locale::En => format!(
            "Topic map with {areas} area{}{}. Largest: {} with {} entries, smallest: {} with {}.",
            plural(areas, "", "s"),
            match islands {
                0 => String::new(),
                1 => " and one island".to_owned(),
                islands => format!(" and {islands} islands"),
            },
            largest.0,
            largest.1,
            smallest.0,
            smallest.1,
        ),
        Locale::De => format!(
            "Themenkarte mit {areas} {}{}. Größtes: {} mit {} Einträgen, kleinstes: {} mit {}.",
            plural(areas, "Gebiet", "Gebieten"),
            match islands {
                0 => String::new(),
                1 => " und einer Insel".to_owned(),
                islands => format!(" und {islands} Inseln"),
            },
            largest.0,
            largest.1,
            smallest.0,
            smallest.1,
        ),
    }
}

/// The sentence that names the closest neighbours of a topic map, as pairs of labels.
pub(crate) fn neighbours(locale: Locale, pairs: &[(&str, &str)]) -> String {
    let and = match locale {
        Locale::En => "and",
        Locale::De => "und",
    };
    let named = pairs
        .iter()
        .map(|(from, to)| format!("{from} {and} {to}"))
        .collect::<Vec<_>>()
        .join(", ");
    match locale {
        Locale::En => format!(" Closest neighbours: {named}."),
        Locale::De => format!(" Engste Nachbarn: {named}."),
    }
}

/// The description of a knowledge landscape; `largest` is the label and value of its largest
/// region.
pub(crate) fn atlas_sentence(
    locale: Locale,
    realms: usize,
    regions: usize,
    largest: (&str, &str),
    places: usize,
) -> String {
    match locale {
        Locale::En => format!(
            "Knowledge landscape of {realms} {} and {regions} {}; largest is {} with {}.{}",
            plural(realms, "realm", "realms"),
            plural(regions, "region", "regions"),
            largest.0,
            largest.1,
            match places {
                0 => String::new(),
                1 => " 1 place is marked.".to_owned(),
                places => format!(" {places} places are marked."),
            }
        ),
        Locale::De => format!(
            "Wissenslandschaft aus {realms} {} und {regions} {}; die größte ist {} mit {}.{}",
            plural(realms, "Bereich", "Bereichen"),
            plural(regions, "Region", "Regionen"),
            largest.0,
            largest.1,
            match places {
                0 => String::new(),
                1 => " 1 Ort ist markiert.".to_owned(),
                places => format!(" {places} Orte sind markiert."),
            }
        ),
    }
}

/// 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})")
}

/// Names in a running list: `A`, `A and B`, `A, B and C`.
fn listed(locale: Locale, names: &[String]) -> String {
    let and = match locale {
        Locale::En => "and",
        Locale::De => "und",
    };
    match names {
        [] => String::new(),
        [only] => only.clone(),
        [rest @ .., last] => format!("{} {and} {last}", rest.join(", ")),
    }
}

/// 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}."),
    }
}

/// 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 an architecture diagram.
pub(crate) fn architecture_opening(
    locale: Locale,
    components: usize,
    connections: usize,
    boundaries: usize,
) -> String {
    let boundaries = match (locale, boundaries) {
        (_, 0) => String::new(),
        (Locale::En, count) => format!(" in {count} boundar{}", plural(count, "y", "ies")),
        (Locale::De, count) => format!(" in {count} {}", plural(count, "Grenze", "Grenzen")),
    };
    match locale {
        Locale::En => format!(
            "Architecture diagram with {components} component{} and {connections} connection{}{boundaries}.",
            plural(components, "", "s"),
            plural(connections, "", "s"),
        ),
        Locale::De => format!(
            "Architekturdiagramm mit {components} {} und {connections} {}{boundaries}.",
            plural(components, "Komponente", "Komponenten"),
            plural(connections, "Verbindung", "Verbindungen"),
        ),
    }
}

/// A boundary and what it holds, components and boundaries, as a sentence.
/// The same in English and German.
pub(crate) fn boundary(label: &str, parent: Option<&str>, held: &[&str]) -> String {
    let parent = parent.map_or_else(String::new, |parent| format!(" (in {parent})"));
    format!("{label}{parent}: {}.", held.join(", "))
}

/// What a component is, for the description and the data table.
pub(crate) const fn component_kind(locale: Locale, kind: ComponentKind) -> &'static str {
    match (locale, kind) {
        (Locale::En, ComponentKind::Person) => "person",
        (Locale::En, ComponentKind::Frontend) => "frontend",
        (Locale::En, ComponentKind::Service) => "service",
        (Locale::En, ComponentKind::Database) => "database",
        (Locale::En, ComponentKind::Queue) => "queue",
        (Locale::En, ComponentKind::Storage) => "storage",
        (Locale::En, ComponentKind::Cache) => "cache",
        (Locale::En, ComponentKind::External) => "external system",
        (Locale::En, ComponentKind::Security) => "security",
        (Locale::De, ComponentKind::Person) => "Person",
        (Locale::De, ComponentKind::Frontend) => "Oberfläche",
        (Locale::De, ComponentKind::Service) => "Dienst",
        (Locale::De, ComponentKind::Database) => "Datenbank",
        (Locale::De, ComponentKind::Queue) => "Warteschlange",
        (Locale::De, ComponentKind::Storage) => "Speicher",
        (Locale::De, ComponentKind::Cache) => "Cache",
        (Locale::De, ComponentKind::External) => "externes System",
        (Locale::De, ComponentKind::Security) => "Sicherheit",
    }
}

/// What a connection does and how, for a parenthesis: `reads, via SQL`.
pub(crate) fn connection_note(
    locale: Locale,
    label: Option<&str>,
    technology: Option<&str>,
) -> Option<String> {
    let via = match locale {
        Locale::En => "via",
        Locale::De => "über",
    };
    match (label, technology) {
        (None, None) => None,
        (Some(label), None) => Some(label.to_owned()),
        (None, Some(technology)) => Some(format!("{via} {technology}")),
        (Some(label), Some(technology)) => Some(format!("{label}, {via} {technology}")),
    }
}

/// A component as a sentence: its label and kind, and where it connects to.
pub(crate) fn component(
    locale: Locale,
    label: &str,
    kind: ComponentKind,
    next: &[String],
) -> String {
    let kind = component_kind(locale, kind);
    let next = match (locale, next.is_empty()) {
        (Locale::En, true) => "no outgoing connection".to_owned(),
        (Locale::De, true) => "keine ausgehende Verbindung".to_owned(),
        (Locale::En, false) => format!("connects to {}", listed(locale, next)),
        (Locale::De, false) => format!("verbunden mit {}", listed(locale, next)),
    };
    format!("{label} ({kind}): {next}.")
}

/// The opening sentence of a tree: how many nodes it has and how many levels they lie in.
pub(crate) fn tree_opening(locale: Locale, nodes: usize, levels: usize) -> String {
    match locale {
        Locale::En => format!(
            "Tree with {nodes} node{} in {levels} level{}.",
            plural(nodes, "", "s"),
            plural(levels, "", "s"),
        ),
        Locale::De => format!(
            "Baum mit {nodes} {} in {levels} {}.",
            plural(nodes, "Knoten", "Knoten"),
            plural(levels, "Ebene", "Ebenen"),
        ),
    }
}

/// The root of a tree, as a sentence.
pub(crate) fn tree_root(locale: Locale, root: &str) -> String {
    match locale {
        Locale::En => format!("Root: {root}."),
        Locale::De => format!("Wurzel: {root}."),
    }
}

/// What a boxplot shows: how many boxes, which median is highest and lowest, and where there are
/// outliers.
pub(crate) fn boxplot_summary(
    locale: Locale,
    boxes: usize,
    highest: (&str, &str),
    lowest: (&str, &str),
    outliers: &[&str],
) -> String {
    let outliers = match (locale, outliers.is_empty()) {
        (_, true) => String::new(),
        (Locale::En, false) => format!(" Outliers beyond the whiskers: {}.", outliers.join(", ")),
        (Locale::De, false) => format!(" Ausreißer jenseits der Whisker: {}.", outliers.join(", ")),
    };
    match locale {
        Locale::En => format!(
            "Box plot with {boxes} box{}, each from the first to the third quartile with its median. Highest median: {} ({}). Lowest median: {} ({}).{outliers}",
            plural(boxes, "", "es"),
            highest.0,
            highest.1,
            lowest.0,
            lowest.1,
        ),
        Locale::De => format!(
            "Boxplot mit {boxes} {}, jeweils vom ersten bis zum dritten Quartil mit dem Median. Höchster Median: {} ({}). Niedrigster Median: {} ({}).{outliers}",
            plural(boxes, "Box", "Boxen"),
            highest.0,
            highest.1,
            lowest.0,
            lowest.1,
        ),
    }
}

/// The sentence that says what the error bars of a bar or line chart show.
pub(crate) fn error_bars(locale: Locale, line: bool) -> String {
    match (locale, line) {
        (Locale::En, false) => " Error bars show the interval from lower to upper; the table gives it for every bar.".to_owned(),
        (Locale::En, true) => " Error bars show the interval from lower to upper; the table gives it for every point.".to_owned(),
        (Locale::De, false) => " Fehlerbalken zeigen das Intervall von unten bis oben; die Tabelle nennt es für jeden Balken.".to_owned(),
        (Locale::De, true) => " Fehlerbalken zeigen das Intervall von unten bis oben; die Tabelle nennt es für jeden Punkt.".to_owned(),
    }
}

/// The overall results among the spans of a range chart, drawn as diamonds.
pub(crate) fn summary_ranges(locale: Locale, summaries: &str) -> String {
    match locale {
        Locale::En => format!(" Overall result, drawn as a diamond: {summaries}."),
        Locale::De => format!(" Gesamtergebnis, als Raute gezeichnet: {summaries}."),
    }
}

/// What the squares of a range chart mean.
pub(crate) fn weighted_ranges(locale: Locale) -> String {
    match locale {
        Locale::En => " The area of each square follows the weight of its span.".to_owned(),
        Locale::De => " Die Fläche jedes Quadrats folgt dem Gewicht seiner Spanne.".to_owned(),
    }
}

/// The opening sentence of a timeline: its phases and milestones, and the days it spans.
pub(crate) fn timeline_opening(
    locale: Locale,
    (phases, milestones): (usize, usize),
    (first, last): (&str, &str),
) -> String {
    let days = match locale {
        Locale::En if first == last => format!("on {first}"),
        Locale::De if first == last => format!("am {first}"),
        Locale::En => format!("from {first} to {last}"),
        Locale::De => format!("vom {first} bis zum {last}"),
    };
    match locale {
        Locale::En => format!(
            "Timeline with {phases} phase{} and {milestones} milestone{} {days}.",
            plural(phases, "", "s"),
            plural(milestones, "", "s"),
        ),
        Locale::De => format!(
            "Zeitstrahl mit {phases} {} und {milestones} {} {days}.",
            plural(phases, "Phase", "Phasen"),
            plural(milestones, "Meilenstein", "Meilensteinen"),
        ),
    }
}

/// One item of a timeline as a sentence: its days, and what it follows.
pub(crate) fn timeline_item(locale: Locale, label: &str, days: &str, follows: &[&str]) -> String {
    let after = match (locale, follows.is_empty()) {
        (_, true) => String::new(),
        (Locale::En, false) => format!(", after {}", follows.join(" and ")),
        (Locale::De, false) => format!(", nach {}", follows.join(" und ")),
    };
    format!("{label}: {days}{after}.")
}

/// The days that matter, drawn as lines across the timeline.
pub(crate) fn timeline_markers(locale: Locale, markers: &str) -> String {
    match locale {
        Locale::En => format!(" Marked days: {markers}."),
        Locale::De => format!(" Markierte Tage: {markers}."),
    }
}

/// What a waterfall shows: its steps, where it ends, and its biggest rise and fall.
pub(crate) fn waterfall_summary(
    locale: Locale,
    (steps, end): (usize, &str),
    rise: Option<(&str, String)>,
    fall: Option<(&str, String)>,
) -> String {
    let (rise_word, fall_word) = match locale {
        Locale::En => ("Biggest rise", "Biggest fall"),
        Locale::De => ("Größter Anstieg", "Größter Rückgang"),
    };
    let mut text = match locale {
        Locale::En => format!("Waterfall with {steps} steps, ending at {end}."),
        Locale::De => format!("Wasserfall mit {steps} Schritten, endend bei {end}."),
    };
    for (word, entry) in [(rise_word, rise), (fall_word, fall)] {
        if let Some((label, value)) = entry {
            write!(text, " {word}: {label} ({value}).").expect("writing to String cannot fail");
        }
    }
    text
}

/// What a waffle shows: its squares, what one stands for, and every part.
pub(crate) fn waffle_summary(locale: Locale, (squares, each): (u32, &str), parts: &str) -> String {
    match locale {
        Locale::En => format!(
            "Waffle chart of {squares} squares, each standing for {each}. Parts, as value (share, squares): {parts}."
        ),
        Locale::De => format!(
            "Waffeldiagramm aus {squares} Feldern, jedes für {each}. Teile als Wert (Anteil, Felder): {parts}."
        ),
    }
}

/// What a parliament chart shows: its seats and parties, with every party, and the majority.
pub(crate) fn parliament_summary(
    locale: Locale,
    (seats, parties): (u32, usize),
    list: &str,
    majority: Option<u32>,
) -> String {
    let majority = match (locale, majority) {
        (_, None) => String::new(),
        (Locale::En, Some(seats)) => format!(" A majority takes {seats} seats."),
        (Locale::De, Some(seats)) => format!(" Eine Mehrheit braucht {seats} Sitze."),
    };
    match locale {
        Locale::En => format!(
            "Parliament with {seats} seats and {parties} part{}: {list}.{majority}",
            plural(parties, "y", "ies")
        ),
        Locale::De => format!(
            "Parlament mit {seats} Sitzen und {parties} {}: {list}.{majority}",
            plural(parties, "Partei", "Parteien")
        ),
    }
}

/// The parties that govern together, their seats and whether those are a majority.
pub(crate) fn parliament_coalition(
    locale: Locale,
    parties: &str,
    seats: u32,
    majority: bool,
) -> String {
    match (locale, majority) {
        (Locale::En, true) => format!("Coalition {parties}: {seats} seats, a majority."),
        (Locale::En, false) => format!("Coalition {parties}: {seats} seats, no majority."),
        (Locale::De, true) => format!("Koalition {parties}: {seats} Sitze, eine Mehrheit."),
        (Locale::De, false) => format!("Koalition {parties}: {seats} Sitze, keine Mehrheit."),
    }
}

/// Where the values of a scatter axis lie: `from 1 to 5`, or `at 3` when they are all equal.
pub(crate) fn value_span(locale: Locale, low: &str, high: &str) -> String {
    match locale {
        Locale::En if low == high => format!("at {low}"),
        Locale::De if low == high => format!("bei {low}"),
        Locale::En => format!("from {low} to {high}"),
        Locale::De => format!("von {low} bis {high}"),
    }
}

/// What a scatter plot shows: its points, the spans of both axes, the groups and the lines.
pub(crate) fn scatter_summary(
    locale: Locale,
    points: usize,
    (x_span, y_span): (&str, &str),
    (groups, lines): (&str, &str),
    fits: &str,
) -> String {
    let mut text = match locale {
        Locale::En => format!(
            "Scatter plot of {points} point{}: x {x_span}, y {y_span}.",
            plural(points, "", "s")
        ),
        Locale::De => format!(
            "Streudiagramm aus {points} {}: x {x_span}, y {y_span}.",
            plural(points, "Punkt", "Punkten")
        ),
    };
    if !groups.is_empty() {
        let word = match locale {
            Locale::En => "Groups (points)",
            Locale::De => "Gruppen (Punkte)",
        };
        write!(text, " {word}: {groups}.").expect("writing to String cannot fail");
    }
    if !lines.is_empty() {
        let word = match locale {
            Locale::En => "Lines",
            Locale::De => "Linien",
        };
        write!(text, " {word}: {lines}.").expect("writing to String cannot fail");
    }
    if !fits.is_empty() {
        write!(text, " {fits}").expect("writing to String cannot fail");
    }
    text
}

/// 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}."),
    }
}

/// What a class diagram shows: how many classes and relations.
pub(crate) fn classes_opening(locale: Locale, classes: usize, relations: usize) -> String {
    match locale {
        Locale::En => format!(
            "Class diagram with {classes} class{} and {relations} relation{}.",
            plural(classes, "", "es"),
            plural(relations, "", "s")
        ),
        Locale::De => format!(
            "Klassendiagramm mit {classes} {} und {relations} {}.",
            plural(classes, "Klasse", "Klassen"),
            plural(relations, "Beziehung", "Beziehungen")
        ),
    }
}

/// A class with the number of its members and the relations it starts.
pub(crate) fn class_sentence(
    locale: Locale,
    label: &str,
    (attributes, methods): (usize, usize),
    relations: &[String],
) -> String {
    let members = match locale {
        Locale::En => format!(
            "{attributes} attribute{}, {methods} method{}",
            plural(attributes, "", "s"),
            plural(methods, "", "s")
        ),
        Locale::De => format!(
            "{attributes} {}, {methods} {}",
            plural(attributes, "Attribut", "Attribute"),
            plural(methods, "Methode", "Methoden")
        ),
    };
    let mut sentence = format!("{label}: {members}.");
    if !relations.is_empty() {
        let joined = relations.join("; ");
        sentence.push(' ');
        write!(sentence, "{label} {joined}.").expect("writing to String cannot fail");
    }
    sentence
}

/// The kind of a class as the table writes it.
pub(crate) fn class_kind(locale: Locale, kind: crate::spec::ClassKind) -> &'static str {
    use crate::spec::ClassKind;
    match (locale, kind) {
        (Locale::En, ClassKind::Class) => "Class",
        (Locale::En, ClassKind::Interface) => "Interface",
        (Locale::En, ClassKind::Abstract) => "Abstract class",
        (Locale::En, ClassKind::Enum) => "Enumeration",
        (Locale::En, ClassKind::Entity) => "Entity",
        (Locale::De, ClassKind::Class) => "Klasse",
        (Locale::De, ClassKind::Interface) => "Schnittstelle",
        (Locale::De, ClassKind::Abstract) => "Abstrakte Klasse",
        (Locale::De, ClassKind::Enum) => "Aufzählung",
        (Locale::De, ClassKind::Entity) => "Entität",
    }
}

/// One relation of a class in words: `inherits from Animal`, with its cardinalities and its
/// label. `from_side` says whether the class starts the relation.
pub(crate) fn relation_phrase(
    locale: Locale,
    (kind, from_side): (crate::spec::RelationKind, bool),
    other: &str,
    cardinality: Option<&str>,
    label: Option<&str>,
) -> String {
    use crate::spec::RelationKind;
    let verb = match (locale, kind, from_side) {
        (Locale::En, RelationKind::Association, _) => "is associated with",
        (Locale::En, RelationKind::Inheritance, true) => "inherits from",
        (Locale::En, RelationKind::Inheritance, false) => "is the parent of",
        (Locale::En, RelationKind::Realization, true) => "implements",
        (Locale::En, RelationKind::Realization, false) => "is implemented by",
        (Locale::En, RelationKind::Composition, true) => "is composed of",
        (Locale::En, RelationKind::Composition, false) => "is part of",
        (Locale::En, RelationKind::Aggregation, true) => "holds",
        (Locale::En, RelationKind::Aggregation, false) => "is held by",
        (Locale::En, RelationKind::Dependency, true) => "depends on",
        (Locale::En, RelationKind::Dependency, false) => "is needed by",
        (Locale::De, RelationKind::Association, _) => "ist verbunden mit",
        (Locale::De, RelationKind::Inheritance, true) => "erbt von",
        (Locale::De, RelationKind::Inheritance, false) => "ist Elternklasse von",
        (Locale::De, RelationKind::Realization, true) => "implementiert",
        (Locale::De, RelationKind::Realization, false) => "wird implementiert von",
        (Locale::De, RelationKind::Composition, true) => "besteht aus",
        (Locale::De, RelationKind::Composition, false) => "ist Teil von",
        (Locale::De, RelationKind::Aggregation, true) => "enthält",
        (Locale::De, RelationKind::Aggregation, false) => "wird enthalten von",
        (Locale::De, RelationKind::Dependency, true) => "hängt ab von",
        (Locale::De, RelationKind::Dependency, false) => "wird gebraucht von",
    };
    let mut phrase = format!("{verb} {other}");
    if let Some(cardinality) = cardinality {
        write!(phrase, " ({cardinality})").expect("writing to String cannot fail");
    }
    if let Some(label) = label {
        write!(phrase, " [{label}]").expect("writing to String cannot fail");
    }
    phrase
}

/// A least-squares line of a scatter plot: its slope, intercept and r², for a group or all points.
pub(crate) fn scatter_fit(
    locale: Locale,
    group: Option<&str>,
    (slope, intercept, r_squared): (String, String, String),
    (log, points): (bool, usize),
) -> String {
    let of = match (locale, group) {
        (Locale::En, Some(group)) => format!("Line for {group}"),
        (Locale::En, None) => "Line".to_owned(),
        (Locale::De, Some(group)) => format!("Gerade für {group}"),
        (Locale::De, None) => "Gerade".to_owned(),
    };
    match (locale, log) {
        (Locale::En, false) => {
            format!("{of} through {points} points: y = {intercept} + {slope} x, r² = {r_squared}.")
        }
        (Locale::En, true) => format!(
            "{of} through {points} points, fitted to the logarithms: ln y = {intercept} + {slope} ln x, r² = {r_squared}."
        ),
        (Locale::De, false) => {
            format!("{of} durch {points} Punkte: y = {intercept} + {slope} x, r² = {r_squared}.")
        }
        (Locale::De, true) => format!(
            "{of} durch {points} Punkte, an die Logarithmen angepasst: ln y = {intercept} + {slope} ln x, r² = {r_squared}."
        ),
    }
}

/// The caption of a table that lists only some of the points of a big plot.
pub(crate) fn scatter_caption(
    locale: Locale,
    caption: &str,
    (shown, all): (usize, usize),
) -> String {
    match locale {
        Locale::En => format!("{caption} — {shown} of {all} points, the named or the highest"),
        Locale::De => {
            format!("{caption} — {shown} von {all} Punkten, die benannten oder die höchsten")
        }
    }
}

/// One group of Kaplan-Meier curves: its observations, events, median time and last survival.
pub(crate) fn survival_group(
    locale: Locale,
    (label, observations, events): (&str, usize, usize),
    median: Option<&str>,
    last: &str,
) -> String {
    let event = plural(events, "event", "events");
    let ereignis = plural(events, "Ereignis", "Ereignisse");
    match (locale, median) {
        (Locale::En, Some(median)) => format!(
            "{label}: {observations} observations, {events} {event}, median {median}, {last} at the end."
        ),
        (Locale::En, None) => format!(
            "{label}: {observations} observations, {events} {event}, median not reached, {last} at the end."
        ),
        (Locale::De, Some(median)) => format!(
            "{label}: {observations} Beobachtungen, {events} {ereignis}, Median {median}, {last} am Ende."
        ),
        (Locale::De, None) => format!(
            "{label}: {observations} Beobachtungen, {events} {ereignis}, Median nicht erreicht, {last} am Ende."
        ),
    }
}

/// The log-rank test in the plot: the p value, as `< 0.001` or `= 0.013`.
pub(crate) fn survival_test_short(locale: Locale, p: &str) -> String {
    match locale {
        Locale::En => format!("Log-rank p {p}"),
        Locale::De => format!("Log-Rank-Test p {p}"),
    }
}

/// The log-rank test in the description: statistic, degrees of freedom and p.
pub(crate) fn survival_test(locale: Locale, (chi, degrees): (&str, usize), p: &str) -> String {
    match locale {
        Locale::En => format!(
            "Log-rank test: χ² = {chi}, {degrees} degree{} of freedom, p {p}.",
            plural(degrees, "", "s")
        ),
        Locale::De => format!(
            "Log-Rank-Test: χ² = {chi}, {degrees} Freiheitsgrad{}, p {p}.",
            plural(degrees, "", "e")
        ),
    }
}

/// How much of a phase is done, as a percentage.
pub(crate) fn percent_done(locale: Locale, progress: f64) -> String {
    let percent = (progress * 100.0).round();
    match locale {
        Locale::En => format!("{percent}% done"),
        Locale::De => format!("{percent} % erledigt"),
    }
}

/// The hazard ratio of two groups with its 95 % limits.
pub(crate) fn survival_hazard(
    locale: Locale,
    (group, reference): (&str, &str),
    (ratio, lower, upper): (&str, &str, &str),
) -> String {
    match locale {
        Locale::En => format!(
            "Hazard ratio of {group} against {reference}: {ratio} (95% confidence interval {lower} to {upper})."
        ),
        Locale::De => format!(
            "Hazard Ratio von {group} gegenüber {reference}: {ratio} (95-%-Konfidenzintervall {lower} bis {upper})."
        ),
    }
}

/// What Kaplan-Meier curves show: how many groups, whether bands are drawn, and each group.
pub(crate) fn survival_summary(
    locale: Locale,
    groups: usize,
    confidence: bool,
    each: &str,
) -> String {
    match locale {
        Locale::En => format!(
            "Kaplan-Meier curves of {groups} group{}{}.{each}",
            plural(groups, "", "s"),
            if confidence {
                ", with 95% confidence bands"
            } else {
                ""
            }
        ),
        Locale::De => format!(
            "Kaplan-Meier-Kurven von {groups} {}{}.{each}",
            plural(groups, "Gruppe", "Gruppen"),
            if confidence {
                ", mit 95-%-Konfidenzbändern"
            } else {
                ""
            }
        ),
    }
}

/// What a Sankey diagram shows: its nodes, links and total, and its biggest links.
pub(crate) fn sankey_summary(
    locale: Locale,
    (nodes, links): (usize, usize),
    total: &str,
    largest: &str,
) -> String {
    match locale {
        Locale::En => format!(
            "Sankey diagram of {nodes} nodes and {links} link{}; {total} enter it. Biggest links: {largest}.",
            plural(links, "", "s")
        ),
        Locale::De => format!(
            "Sankey-Diagramm aus {nodes} Knoten und {links} {}; {total} fließen hinein. Größte Verbindungen: {largest}.",
            plural(links, "Verbindung", "Verbindungen")
        ),
    }
}

/// What a treemap shows: its items and total, the biggest ones, and the shares of its groups.
pub(crate) fn treemap_summary(
    locale: Locale,
    (items, total): (usize, &str),
    largest: &str,
    groups: &str,
) -> String {
    let groups = match (locale, groups.is_empty()) {
        (_, true) => String::new(),
        (Locale::En, false) => format!(" Groups: {groups}."),
        (Locale::De, false) => format!(" Gruppen: {groups}."),
    };
    match locale {
        Locale::En => format!(
            "Treemap of {items} item{}, together {total}; the rectangle of each has the area of its value. Largest: {largest}.{groups}",
            plural(items, "", "s")
        ),
        Locale::De => format!(
            "Treemap aus {items} {}, zusammen {total}; die Fläche jedes Rechtecks folgt seinem Wert. Am größten: {largest}.{groups}",
            plural(items, "Eintrag", "Einträgen")
        ),
    }
}

#[cfg(test)]
mod tests {
    use super::{
        atlas_sentence, bands, calendar_opening, categories_opening, equal_values, missing_values,
        multiples_opening, panel_bars_opening, stripes_opening, survival_group, time_opening,
        timeline_opening, topicmap_opening, value_span, years_without_value,
    };
    use crate::spec::Locale;

    #[test]
    fn german_counts_of_one_are_singular() {
        assert_eq!(
            equal_values(Locale::De, false, 1, "5"),
            "Balkendiagramm mit 1 Wert: 5."
        );
        assert_eq!(
            time_opening(Locale::De, 1, "2024", &[], false),
            "Zeitreihe mit 1 Punkt 2024."
        );
        assert_eq!(
            time_opening(Locale::De, 2, "2024", &[], false),
            "Zeitreihe mit 2 Punkten 2024."
        );
    }

    #[test]
    fn english_counts_of_one_are_singular() {
        assert_eq!(
            equal_values(Locale::En, false, 1, "5"),
            "Bar chart with 1 value: 5."
        );
        assert_eq!(
            categories_opening(Locale::En, false, 1, 1, ""),
            "Bar chart with 1 category."
        );
        assert_eq!(
            categories_opening(Locale::En, true, 1, 2, "A, B"),
            "Line chart with 1 category and 2 series (A, B)."
        );
        assert_eq!(
            time_opening(Locale::En, 1, "in 2024", &[], false),
            "Time chart with 1 point in 2024."
        );
        assert_eq!(
            time_opening(Locale::En, 1, "in 2024", &[], true),
            "Time chart with 1 point in 2024, modelled."
        );
        assert_eq!(
            time_opening(
                Locale::En,
                1,
                "in 2024",
                &["A".to_owned(), "B".to_owned()],
                false
            ),
            "Time chart with 1 point in 2024 and 2 series (A, B)."
        );
        assert!(
            calendar_opening(Locale::En, 2024, true, "scale", 1, 366)
                .ends_with(" 1 of 366 days has a value.")
        );
        assert_eq!(
            atlas_sentence(Locale::En, 1, 1, ("A", "3"), 1),
            "Knowledge landscape of 1 realm and 1 region; largest is A with 3. 1 place is marked."
        );
        assert!(
            topicmap_opening(Locale::En, 1, 1, ("A", "3"), ("A", "3"))
                .starts_with("Topic map with 1 area and one island.")
        );
        assert_eq!(missing_values(Locale::En, 1), " 1 value is missing.");
        assert_eq!(years_without_value(Locale::En, 1), " 1 year has no value.");
    }

    #[test]
    fn english_counts_of_many_stay_plural() {
        assert_eq!(
            categories_opening(Locale::En, false, 3, 1, ""),
            "Bar chart with 3 categories."
        );
        assert_eq!(
            time_opening(Locale::En, 3, "in 2024", &[], false),
            "Time chart with 3 points in 2024."
        );
        assert!(
            calendar_opening(Locale::En, 2024, false, "scale", 2, 366)
                .ends_with(" 2 of 366 days have a value.")
        );
        assert_eq!(
            atlas_sentence(Locale::En, 2, 3, ("A", "3"), 4),
            "Knowledge landscape of 2 realms and 3 regions; largest is A with 3. 4 places are marked."
        );
    }

    #[test]
    fn panels_are_named_in_plain_words() {
        let two = ["A".to_owned(), "B".to_owned()];
        assert_eq!(
            multiples_opening(Locale::En, &two, "from 2000 to 2050", &[], true),
            "Time chart in 2 panels (A, B) with a shared value axis, each from 2000 to 2050."
        );
        assert_eq!(
            multiples_opening(Locale::De, &two, "von 2000 bis 2050", &[], false),
            "Zeitreihe in 2 Feldern (A, B) mit je eigener Werteachse, jeweils von 2000 bis 2050."
        );
        let one = ["A".to_owned()];
        assert!(
            multiples_opening(Locale::En, &one, "from 2000 to 2050", &[], true)
                .starts_with("Time chart in 1 panel (A)")
        );
        assert!(
            multiples_opening(Locale::De, &one, "von 2000 bis 2050", &[], true)
                .starts_with("Zeitreihe in 1 Feld (A)")
        );
        assert_eq!(
            panel_bars_opening(Locale::En, 2, 3),
            "Bar chart in 2 panels over 3 categories, each with its own value axis."
        );
        assert_eq!(
            panel_bars_opening(Locale::De, 2, 1),
            "Balkendiagramm in 2 Feldern über 1 Kategorie, jedes mit eigener Wertachse."
        );
    }

    #[test]
    fn bands_agree_with_the_number_of_lines() {
        assert_eq!(
            bands(Locale::En, 1, true),
            " One line has a shaded band from its lower to its upper bound, hatched where modelled; the data table lists both."
        );
        assert_eq!(
            bands(Locale::En, 2, false),
            " Lines have a shaded band from their lower to their upper bound; the data table lists both."
        );
        assert!(bands(Locale::De, 2, false).starts_with(" Linien haben je ein schattiertes Band"));
    }

    #[test]
    fn equal_ends_are_named_once() {
        assert_eq!(value_span(Locale::En, "3", "3"), "at 3");
        assert_eq!(value_span(Locale::De, "3", "3"), "bei 3");
        assert_eq!(value_span(Locale::En, "1", "5"), "from 1 to 5");
        assert_eq!(value_span(Locale::De, "1", "5"), "von 1 bis 5");
        assert_eq!(
            stripes_opening(Locale::En, 2020, 2020, "scale"),
            "Warming stripes for 2020, one stripe, scale."
        );
        assert_eq!(
            stripes_opening(Locale::De, 2020, 2020, "Skala"),
            "Wärmestreifen für 2020, ein Streifen, Skala."
        );
        assert_eq!(
            timeline_opening(Locale::En, (0, 1), ("3 Mar 2026", "3 Mar 2026")),
            "Timeline with 0 phases and 1 milestone on 3 Mar 2026."
        );
        assert_eq!(
            timeline_opening(Locale::De, (0, 1), ("3. Mär 2026", "3. Mär 2026")),
            "Zeitstrahl mit 0 Phasen und 1 Meilenstein am 3. Mär 2026."
        );
    }

    #[test]
    fn one_event_is_singular() {
        assert_eq!(
            survival_group(Locale::En, ("A", 5, 1), None, "80%"),
            "A: 5 observations, 1 event, median not reached, 80% at the end."
        );
        assert_eq!(
            survival_group(Locale::De, ("A", 5, 1), Some("3"), "80 %"),
            "A: 5 Beobachtungen, 1 Ereignis, Median 3, 80 % am Ende."
        );
    }
}