monospace-description 0.1.0

The diagram description format: JSON deserialized into a monospace_diagram::Diagram
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
//! The diagram description format: JSON deserialized into a `monospace_diagram::Diagram` or
//! serialized back from one.
//!
//! Two calls do the whole of it — [`parse`] takes the text and hands back the diagram, and
//! [`serialize`] takes the diagram and hands back the formatted JSON text — and every type behind
//! those calls is private to this crate. The public surface is four things: [`parse`],
//! [`ParseError`], [`serialize`] and [`SerializeError`]. Nothing here reaches a file, a terminal or
//! a screen: a caller that wants to read from or write to disk reads or writes the disk itself and
//! hands the text over. **Nothing here names a window either**, because which part of a diagram to
//! draw is the caller's question and the window is the caller's.
//!
//! **This crate is a layer above the diagram, and it knows nothing of the editing layer.** Both
//! hang off `monospace-diagram` and neither depends on the other; what would join them is a
//! convenience that opens a file into a session, and that belongs to whoever needs it rather than
//! to either layer. See [`docs/diagram-model.md`](../../../docs/diagram-model.md).
//!
//! # The envelope
//!
//! One file is one JSON object of two fields, and both are required:
//!
//! ```json
//! {
//!   "next_id": 3,
//!   "shapes": []
//! }
//! ```
//!
//! - **`next_id`** is the ordinal the next shape added takes, which is where numbering **resumes**
//!   rather than a count of what was read: `1`, `7` and `9` under `next_id: 10` hands back `10`. It
//!   is a **nonzero** ordinal, because zero is not an identity; `"next_id": 0` is refused here
//!   rather than seeded with something no shape can carry.
//! - **`shapes`** is the figures in drawing order, empty or not, the last front-most and deciding a
//!   shared cell first. Each entry names a `kind` and carries the `id` its shape is held under.
//!
//! **There is no `canvas`.** A description that still carries one is read, and the canvas ignored:
//! there is no writer, so nothing outside this repository has ever produced a file, and a stricter
//! error would be a change to wording that fifteen tests assert verbatim for no gain. **The window a
//! picture is drawn into is the caller's**, named on the command line or on the line that opens a
//! render marker — see [`docs/diagram-model.md`](../../../docs/diagram-model.md), which holds that
//! the diagram measures nothing and sizes nothing.
//!
//! # What is not here
//!
//! **No file.** Neither [`parse`] nor [`serialize`] takes a path, so nothing in this crate reaches
//! a filesystem — which is also what keeps it portable by naming rather than by anything it
//! avoids.

use std::num::NonZeroU16;

use monospace_core::{Direction, Glyph, Orientation as CoreOrientation, SymbolStyleName, Text};
use monospace_diagram::{
    Anchor, Delta, Diagram, Endpoint as DiagramEndpoint, EndpointAt, Position, Reference,
    Shape as DiagramShape, ShapeId,
};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// A description that could not be read.
///
/// **The message is the one `serde_json` produced, unchanged.** A newtype rather than a
/// re-wrap: the value of this type is that `serde` does not appear in this crate's public API, not
/// that it says anything the underlying error did not. A caller prints it and the words are the
/// ones the format has always reported — a missing field named, a `kind` this build does not know
/// named beside the two it does, an identity written as free text and quoted back — which is what
/// the contract tests here and in `monospace-cli` assert on.
///
/// What would earn it more is a writer: a file whose `kind` this build does not know is a
/// different kind of problem from one that is spelled wrong, and only then is there something to add
/// that `serde` cannot say.
#[derive(Debug)]
pub struct ParseError(serde_json::Error);

impl std::fmt::Display for ParseError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(formatter)
    }
}

impl std::error::Error for ParseError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.0)
    }
}

/// Reads a description and hands back the diagram it holds, and nothing else.
///
/// The whole of this crate's public surface for reading, in one call: there is no value to build,
/// hold or convert afterwards, so no method can be called in the wrong order and none leaves a
/// diagram half-converted. **The window is not here** — which part of a diagram to draw is the
/// caller's question, and a caller that wants one names it on the command line or on the line that
/// opens a render marker.
///
/// # Errors
///
/// [`ParseError`] when the text is not a description this crate reads — a field left out, a `kind`
/// it does not name, an identity written as free text, a `next_id` of zero. The message names the
/// field it was refused on and is the one `serde_json` produced.
///
/// # Examples
///
/// ```
/// # use monospace_description::parse;
/// let diagram = parse(
///     r#"{
///         "next_id": 2,
///         "shapes": [ { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 },
///                       "size": { "width": 4, "height": 3 }, "stroke": "light" } ]
///     }"#,
/// )
/// .expect("a well-formed description");
///
/// assert!(diagram
///     .get(monospace_diagram::ShapeId::new(std::num::NonZeroU16::new(1).expect("one is nonzero")))
///     .is_some());
/// ```
pub fn parse(json: &str) -> Result<Diagram, ParseError> {
    let description: Description = serde_json::from_str(json).map_err(ParseError)?;
    Ok(description.into_diagram())
}

/// A description that could not be serialized.
///
/// **The message is the one `serde_json` produced, unchanged.** A newtype rather than a
/// re-wrap: the value of this type is that `serde` does not appear in this crate's public API, not
/// that it says anything the underlying error did not.
#[derive(Debug)]
pub struct SerializeError(serde_json::Error);

impl std::fmt::Display for SerializeError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(formatter)
    }
}

impl std::error::Error for SerializeError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.0)
    }
}

/// Serializes `diagram` into formatted JSON matching the description format read by [`parse`].
///
/// The output is 2-space pretty-printed JSON ending in a newline, with `next_id` and the `shapes`
/// array in drawing order from back to front.
///
/// # Errors
///
/// [`SerializeError`] when the description could not be converted to JSON.
///
/// # Examples
///
/// ```
/// # use monospace_description::{parse, serialize};
/// let diagram = parse(
///     r#"{
///         "next_id": 2,
///         "shapes": [ { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 },
///                       "size": { "width": 4, "height": 3 }, "stroke": "light" } ]
///     }"#,
/// )
/// .expect("a well-formed description");
///
/// let json = serialize(&diagram).expect("serializes to JSON");
/// assert!(json.contains("\"next_id\": 2"));
/// ```
pub fn serialize(diagram: &Diagram) -> Result<String, SerializeError> {
    let description = Description::from_diagram(diagram);
    let mut json = serde_json::to_string_pretty(&description).map_err(SerializeError)?;
    json.push('\n');
    Ok(json)
}

/// A position, mirroring `monospace_core::Pos` for deserialization and serialization.
#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)]
struct Pos {
    x: i16,
    y: i16,
}

impl From<Pos> for monospace_core::Pos {
    fn from(pos: Pos) -> Self {
        monospace_core::Pos { x: pos.x, y: pos.y }
    }
}

impl From<monospace_core::Pos> for Pos {
    fn from(pos: monospace_core::Pos) -> Self {
        Self { x: pos.x, y: pos.y }
    }
}

/// A size, mirroring `monospace_core::Size` for deserialization and serialization.
#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)]
struct Size {
    width: u16,
    height: u16,
}

impl From<Size> for monospace_core::Size {
    fn from(size: Size) -> Self {
        monospace_core::Size {
            width: size.width,
            height: size.height,
        }
    }
}

impl From<monospace_core::Size> for Size {
    fn from(size: monospace_core::Size) -> Self {
        Self {
            width: size.width,
            height: size.height,
        }
    }
}

/// Whether a line runs along a row or a column, mirroring `monospace_core::Orientation`.
#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
enum Orientation {
    Horizontal,
    Vertical,
}

impl From<Orientation> for CoreOrientation {
    fn from(orientation: Orientation) -> Self {
        match orientation {
            Orientation::Horizontal => CoreOrientation::Horizontal,
            Orientation::Vertical => CoreOrientation::Vertical,
        }
    }
}

impl From<CoreOrientation> for Orientation {
    fn from(orientation: CoreOrientation) -> Self {
        match orientation {
            CoreOrientation::Horizontal => Self::Horizontal,
            CoreOrientation::Vertical => Self::Vertical,
        }
    }
}

/// The direction a connector endpoint leaves in, mirroring `monospace_core::Direction`.
#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
enum Leaving {
    Up,
    Right,
    Down,
    Left,
}

impl From<Leaving> for Direction {
    fn from(leaving: Leaving) -> Self {
        match leaving {
            Leaving::Up => Direction::Up,
            Leaving::Right => Direction::Right,
            Leaving::Down => Direction::Down,
            Leaving::Left => Direction::Left,
        }
    }
}

impl From<Direction> for Leaving {
    fn from(direction: Direction) -> Self {
        match direction {
            Direction::Up => Self::Up,
            Direction::Right => Self::Right,
            Direction::Down => Self::Down,
            Direction::Left => Self::Left,
        }
    }
}

/// Serializes a required glyph field as its string representation.
fn serialize_glyph<S>(glyph: &Glyph, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    serializer.serialize_str(glyph.as_str())
}

/// Serializes an optional glyph field (`fill`): `Some` writes the string, `None` is skipped.
#[allow(clippy::ref_option)]
fn serialize_optional_glyph<S>(glyph: &Option<Glyph>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    match glyph {
        Some(glyph) => serializer.serialize_str(glyph.as_str()),
        None => serializer.serialize_none(),
    }
}

/// Serializes an optional text field (`text`): lines are joined with newlines.
#[allow(clippy::ref_option)]
fn serialize_optional_text<S>(text: &Option<Text>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    match text {
        Some(text) => {
            let content = text
                .lines()
                .iter()
                .map(|line| line.iter().map(Glyph::as_str).collect::<String>())
                .collect::<Vec<_>>()
                .join("\n");
            serializer.serialize_str(&content)
        }
        None => serializer.serialize_none(),
    }
}

#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_zero(n: &i16) -> bool {
    *n == 0
}

fn shape_id_ordinal(id: ShapeId) -> NonZeroU16 {
    id.to_string()
        .parse::<NonZeroU16>()
        .expect("ShapeId displays its NonZeroU16")
}

/// Deserializes a required glyph field: the text must be exactly one grapheme cluster with no
/// control character, or this reports the same data-error kind `serde_json` reports for anything
/// else wrong with the file.
fn deserialize_glyph<'de, D>(deserializer: D) -> Result<Glyph, D::Error>
where
    D: Deserializer<'de>,
{
    let text = String::deserialize(deserializer)?;
    Glyph::new(&text).ok_or_else(|| {
        serde::de::Error::custom(format!("{text:?} is not exactly one grapheme cluster"))
    })
}

/// Deserializes an optional glyph field (`fill`): absent stays `None`; present, it is checked the
/// same way [`deserialize_glyph`] checks a required one.
fn deserialize_optional_glyph<'de, D>(deserializer: D) -> Result<Option<Glyph>, D::Error>
where
    D: Deserializer<'de>,
{
    #[derive(Deserialize)]
    struct Wrapper(#[serde(deserialize_with = "deserialize_glyph")] Glyph);

    Ok(Option::<Wrapper>::deserialize(deserializer)?.map(|wrapper| wrapper.0))
}

/// Deserializes a text field: one string, split on `'\n'`, where any other control character is
/// refused **by the field's name** the way [`deserialize_glyph`] refuses a bad `fill`.
fn deserialize_text<'de, D>(deserializer: D) -> Result<Text, D::Error>
where
    D: Deserializer<'de>,
{
    let content = String::deserialize(deserializer)?;
    Text::new(&content).ok_or_else(|| {
        serde::de::Error::custom(format!(
            "`text` is lines of glyphs: {content:?} holds a control character that is not a \
             newline"
        ))
    })
}

/// Deserializes an optional text field (`text`): absent stays `None`; present, it is checked the
/// same way [`deserialize_text`] checks a required one.
fn deserialize_optional_text<'de, D>(deserializer: D) -> Result<Option<Text>, D::Error>
where
    D: Deserializer<'de>,
{
    #[derive(Deserialize)]
    struct Wrapper(#[serde(deserialize_with = "deserialize_text")] Text);

    Ok(Option::<Wrapper>::deserialize(deserializer)?.map(|wrapper| wrapper.0))
}

/// The ordinal the three identity fields share, and the reason each names itself on a refusal.
///
/// An identity is a number greater than zero — `1`, not `"#1"` — so a file spelling it any other
/// way is a **data error**, and the message says which field was wrong rather than leaving a reader
/// to work back from a position: `serde` reports `invalid type: string "#1", expected a nonzero
/// u16`, which names neither `id` nor `shape` nor `next_id`, and the three are the whole of what a
/// caller has to go on.
///
/// The name is the field's, written beside the field rather than read from serde's error, because
/// serde cannot know it: the same [`NonZeroU16`] is deserialized from three different keys. The
/// underlying message is carried through whole, so what the file actually said survives next to the
/// field it was said in.
fn ordinal<'de, D>(field: &'static str, deserializer: D) -> Result<NonZeroU16, D::Error>
where
    D: Deserializer<'de>,
{
    NonZeroU16::deserialize(deserializer)
        .map_err(|error| serde::de::Error::custom(format!("`{field}` is an ordinal: {error}")))
}

/// The `id` of an entry in `shapes`. A thin wrapper over [`ordinal`] so that the name in the message
/// is the field's own, beside the field it belongs to.
fn id<'de, D>(deserializer: D) -> Result<NonZeroU16, D::Error>
where
    D: Deserializer<'de>,
{
    ordinal("id", deserializer)
}

/// The `next_id` a diagram's numbering resumes from.
fn next_id<'de, D>(deserializer: D) -> Result<NonZeroU16, D::Error>
where
    D: Deserializer<'de>,
{
    ordinal("next_id", deserializer)
}

/// The `shape` a reference names.
fn shape<'de, D>(deserializer: D) -> Result<NonZeroU16, D::Error>
where
    D: Deserializer<'de>,
{
    ordinal("shape", deserializer)
}

/// What an endpoint's `terminal` is on the wire, tagged by `kind`: one chosen glyph, one symbol in a
/// named style, or one arm. An unrecognized `kind` is reported by name, and the message names the
/// three accepted.
///
/// Internally tagged rather than externally, because `deserialize_glyph` needs a _named_ field to
/// sit on and the external form has none — `Glyph(Glyph)` does not compile, since `Glyph` derives
/// no `Deserialize`. A field an `arm` does not know is ignored, as everywhere else in this format.
///
/// **The `symbol` variant carries a style name and not a symbol.** Which symbol it writes follows
/// from the endpoint's `leaving`, decided by the core so no file can spell a head that disagrees
/// with the direction it leaves in. The name is not checked here: the catalog the caller renders
/// with answers it, and a name it does not hold draws a space.
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "lowercase")]
enum Terminal {
    Glyph {
        #[serde(
            serialize_with = "serialize_glyph",
            deserialize_with = "deserialize_glyph"
        )]
        glyph: Glyph,
    },
    Symbol {
        style: String,
    },
    Arm,
}

impl From<Terminal> for monospace_core::Terminal {
    fn from(terminal: Terminal) -> Self {
        match terminal {
            Terminal::Glyph { glyph } => monospace_core::Terminal::Glyph { glyph },
            Terminal::Symbol { style } => monospace_core::Terminal::Symbol {
                style: SymbolStyleName::from(style.as_str()),
            },
            Terminal::Arm => monospace_core::Terminal::Arm,
        }
    }
}

impl From<monospace_core::Terminal> for Terminal {
    fn from(terminal: monospace_core::Terminal) -> Self {
        match terminal {
            monospace_core::Terminal::Glyph { glyph } => Self::Glyph { glyph },
            monospace_core::Terminal::Symbol { style } => Self::Symbol { style: style.0 },
            monospace_core::Terminal::Arm => Self::Arm,
        }
    }
}

/// Which of a figure's four sides an endpoint hangs from, mirroring `monospace_diagram::Anchor`.
///
/// The same four and no fifth: there is no corner and no center, and the file cannot name one.
#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
enum AnchorDescription {
    Top,
    Right,
    Bottom,
    Left,
}

impl From<AnchorDescription> for Anchor {
    fn from(anchor: AnchorDescription) -> Self {
        match anchor {
            AnchorDescription::Top => Anchor::Top,
            AnchorDescription::Right => Anchor::Right,
            AnchorDescription::Bottom => Anchor::Bottom,
            AnchorDescription::Left => Anchor::Left,
        }
    }
}

impl From<Anchor> for AnchorDescription {
    fn from(anchor: Anchor) -> Self {
        match anchor {
            Anchor::Top => Self::Top,
            Anchor::Right => Self::Right,
            Anchor::Bottom => Self::Bottom,
            Anchor::Left => Self::Left,
        }
    }
}

/// How far from that side an endpoint stands, mirroring `monospace_diagram::Delta`.
///
/// `Default` is what makes the field optional on the wire: `#[serde(default)]` on the field below
/// builds a zero delta when the key is absent, so a reference that means "on the side itself" spells
/// three fields rather than five. The two amounts are signed and are in the **screen** axes whatever
/// side the anchor names — `dx` is cells right, `dy` cells down — and neither is checked against the
/// side it is measured from.
#[derive(Deserialize, Serialize, Debug, Clone, Copy, Default, PartialEq, Eq)]
struct OffsetDescription {
    dx: i16,
    dy: i16,
}

impl From<OffsetDescription> for Delta {
    fn from(offset: OffsetDescription) -> Self {
        Delta {
            dx: offset.dx,
            dy: offset.dy,
        }
    }
}

impl From<Delta> for OffsetDescription {
    fn from(offset: Delta) -> Self {
        Self {
            dx: offset.dx,
            dy: offset.dy,
        }
    }
}

/// What an endpoint's `at` is on the wire, tagged by `kind`: a point, or a reference to a side of
/// another figure.
///
/// **The tag is the rule, not a sentence.** A file cannot say both, cannot say neither, and cannot
/// say one by mistake — all three are compile-time facts about this enum rather than conventions a
/// reader has to remember. The three spellings were measured against this crate's own `serde`
/// rather than argued: an untagged union reads every existing description and
/// answers anything wrong with `data did not match any variant of untagged enum At`, and a sibling
/// `reference` beside an optional `at` refuses nothing at all.
///
/// A reference to a shape the diagram does not hold, or to an anchor that kind does not answer, is
/// **not** an error here or anywhere downstream: the figure holding it is simply not drawn and the
/// run succeeds. **The silence is the answer, on purpose** — a reference naming a shape that is not
/// there yet is an ordinary state of a diagram being built rather than an invalid one, so the only
/// thing this layer owes anybody is to refuse to draw something it cannot place. What it pays for
/// that is that a diagram which drew nothing and a diagram whose every reference is broken look
/// identical, and there is nothing to ask about the difference.
///
/// `Point` carries its `x` and `y` coordinates inline so the enum serializes and deserializes
/// with the internal `kind` tag identically.
///
/// The `Reference` variant's two gap fields are **two spellings of one gap**, and which one a file
/// reaches for is the caller's: `offset` is the screen axes whatever side the anchor names, and
/// `out` is the side's own words, so `"anchor": "bottom", "out": 1` is one cell below the border
/// without the file knowing that "below" is `dy: 1`. Both are optional and absent is zero, so a
/// reference on the side itself is three fields; `out` is added to `offset` rather than replacing it,
/// and a file may write either or both. `Reference` preserves both `offset` and `out` separately,
/// resolving their sum at draw time and keeping `out` on serialization.
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "lowercase")]
enum At {
    Point {
        x: i16,
        y: i16,
    },
    Reference {
        #[serde(deserialize_with = "shape")]
        shape: NonZeroU16,
        anchor: AnchorDescription,
        #[serde(default)]
        offset: OffsetDescription,
        #[serde(default, skip_serializing_if = "is_zero")]
        out: i16,
    },
}

impl From<Position> for At {
    fn from(position: Position) -> Self {
        match position {
            Position::Absolute(pos) => Self::Point { x: pos.x, y: pos.y },
            Position::Reference(reference) => Self::Reference {
                shape: shape_id_ordinal(reference.id),
                anchor: reference.anchor.into(),
                offset: reference.offset.into(),
                out: reference.out,
            },
        }
    }
}

/// One endpoint of a connector: where it stands, the direction it leaves in, and its terminal.
///
/// `at` is an [`At`], so the diagram's `Position` is spelled by name in the conversion below: the
/// `into()` on a [`Pos`] resolves `description::Pos → monospace_core::Pos` and lands on
/// `Position::Absolute`, while a reference is built field by field. A reference may only be held by
/// a **connector's endpoint** — a `box` and a `line` keep their bare `Pos` — and the types say so
/// rather than the prose. The restriction is what keeps a chain of references one link long: a
/// reference names a box or a line, both positioned absolutely, or a connector, which answers no
/// side at all, so nothing recurses and no cycle can be built.
/// An endpoint positioning at a `point` requires `leaving`. An endpoint positioning at a `reference`
/// derives its leaving direction from its anchor and must not specify `leaving`.
#[derive(Serialize, Debug, Clone, PartialEq, Eq)]
struct Endpoint {
    at: At,
    #[serde(skip_serializing_if = "Option::is_none")]
    leaving: Option<Leaving>,
    terminal: Terminal,
}

impl<'de> Deserialize<'de> for Endpoint {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct RawEndpoint {
            at: At,
            #[serde(default)]
            leaving: Option<Leaving>,
            terminal: Terminal,
        }

        let raw = RawEndpoint::deserialize(deserializer)?;
        match (&raw.at, raw.leaving) {
            (At::Point { .. }, None) => Err(serde::de::Error::missing_field("leaving")),
            (At::Reference { .. }, Some(_)) => Err(serde::de::Error::custom(
                "a reference endpoint derives its leaving direction from its anchor and must not specify `leaving`",
            )),
            _ => Ok(Self {
                at: raw.at,
                leaving: raw.leaving,
                terminal: raw.terminal,
            }),
        }
    }
}

impl From<DiagramEndpoint> for Endpoint {
    fn from(endpoint: DiagramEndpoint) -> Self {
        match endpoint.at {
            EndpointAt::Absolute { at, leaving } => Self {
                at: Position::Absolute(at).into(),
                leaving: Some(leaving.into()),
                terminal: endpoint.terminal.into(),
            },
            EndpointAt::Reference(reference) => Self {
                at: Position::Reference(reference).into(),
                leaving: None,
                terminal: endpoint.terminal.into(),
            },
        }
    }
}

impl From<Endpoint> for DiagramEndpoint {
    fn from(endpoint: Endpoint) -> Self {
        match endpoint.at {
            At::Point { x, y } => DiagramEndpoint::absolute(
                monospace_core::Pos { x, y },
                endpoint
                    .leaving
                    .expect("a deserialized point endpoint always has a leaving direction")
                    .into(),
                endpoint.terminal.into(),
            ),
            At::Reference {
                shape,
                anchor,
                offset,
                out,
            } => DiagramEndpoint::reference(
                Reference::new(ShapeId::new(shape), anchor.into(), offset.into(), out),
                endpoint.terminal.into(),
            ),
        }
    }
}

/// One entry in a `Description`'s `shapes` array, tagged by `kind`. An unrecognized `kind` is
/// reported by name, since this enum is internally tagged.
///
/// Every variant carries an `id`: the identity its shape is held under, and the one a `reference`
/// names. It is required, so a file leaving it out is refused **by name**, exactly as `canvas`,
/// `shapes`, `leaving`, `terminal` and `at`'s `kind` already are. It sits **first** in every
/// variant because a variant's fields are read in declaration order, and `id` immediately after
/// `kind` on the wire is where all the descriptions in this repository already put it.
///
/// **The identity is an ordinal rather than any text.** One number greater than zero, deserialized
/// by [`id`] so that `"#1"` is refused by name rather than read as a string nobody can resolve,
/// and the same spelling the `next_id` beside it has always used.
///
/// The identity is **not** checked for uniqueness, and two entries may carry one: both are read,
/// the first is what every change and every reference finds, and the second is reachable by no
/// identity until the first is removed. That cost is accepted, and it is why the model's "unique
/// within that diagram" is amended in the `docs` commit rather than enforced here.
#[derive(Deserialize, Serialize, Debug, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "lowercase")]
enum ShapeDescription {
    Box {
        #[serde(deserialize_with = "id")]
        id: NonZeroU16,
        at: Pos,
        size: Size,
        stroke: String,
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            serialize_with = "serialize_optional_glyph",
            deserialize_with = "deserialize_optional_glyph"
        )]
        fill: Option<Glyph>,
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            serialize_with = "serialize_optional_text",
            deserialize_with = "deserialize_optional_text"
        )]
        text: Option<Text>,
    },
    Line {
        #[serde(deserialize_with = "id")]
        id: NonZeroU16,
        at: Pos,
        len: u16,
        orientation: Orientation,
        stroke: String,
    },
    Connector {
        #[serde(deserialize_with = "id")]
        id: NonZeroU16,
        from: Endpoint,
        to: Endpoint,
        stroke: String,
    },
}

impl ShapeDescription {
    fn from_shape(id: ShapeId, shape: &DiagramShape) -> Self {
        let ordinal = shape_id_ordinal(id);
        match shape {
            DiagramShape::Box {
                at,
                size,
                stroke,
                fill,
                text,
            } => Self::Box {
                id: ordinal,
                at: (*at).into(),
                size: (*size).into(),
                stroke: stroke.0.clone(),
                fill: fill.clone(),
                text: text.clone(),
            },
            DiagramShape::Line {
                at,
                len,
                orientation,
                stroke,
            } => Self::Line {
                id: ordinal,
                at: (*at).into(),
                len: *len,
                orientation: (*orientation).into(),
                stroke: stroke.0.clone(),
            },
            DiagramShape::Connector { from, to, stroke } => Self::Connector {
                id: ordinal,
                from: from.clone().into(),
                to: to.clone().into(),
                stroke: stroke.0.clone(),
            },
        }
    }

    /// The identity this entry's shape is held under, read before the shape is converted.
    ///
    /// One method rather than three because the field is on every variant and the conversion below
    /// drops it: the figure carries no identity, and it is the diagram that holds the one the file
    /// wrote.
    fn id(&self) -> ShapeId {
        match self {
            ShapeDescription::Box { id, .. }
            | ShapeDescription::Line { id, .. }
            | ShapeDescription::Connector { id, .. } => ShapeId::new(*id),
        }
    }
}

impl From<ShapeDescription> for DiagramShape {
    /// Converts this description into the matching `monospace_diagram` shape, dropping no
    /// parameter. The `id` goes with the diagram rather than with the figure: nothing about a
    /// returned shape says where it sits, which is the arrangement here and stays it.
    fn from(description: ShapeDescription) -> Self {
        match description {
            ShapeDescription::Box {
                at,
                size,
                stroke,
                fill,
                text,
                ..
            } => DiagramShape::Box {
                at: at.into(),
                size: size.into(),
                stroke: stroke.as_str().into(),
                fill,
                text,
            },
            ShapeDescription::Line {
                at,
                len,
                orientation,
                stroke,
                ..
            } => DiagramShape::Line {
                at: at.into(),
                len,
                orientation: orientation.into(),
                stroke: stroke.as_str().into(),
            },
            ShapeDescription::Connector {
                from, to, stroke, ..
            } => DiagramShape::Connector {
                from: from.into(),
                to: to.into(),
                stroke: stroke.as_str().into(),
            },
        }
    }
}

/// The whole of one description file: the ordinal the next shape takes, and an ordered list of
/// shapes.
///
/// Private because nothing outside this crate needs it: [`parse`] reads one and hands back what it
/// holds, and a caller that could hold a `Description` would be able to look at a format this
/// crate does not promise to keep.
#[derive(Deserialize, Serialize, Debug, PartialEq, Eq)]
struct Description {
    /// The ordinal the next `add` takes: a number rather than a container holding one, because it
    /// is one number. Required, so a file leaving it out is refused by name, the way `shapes`
    /// already is.
    ///
    /// **It is trusted, not checked, beyond being nonzero.** A stale value — an entry removed, a
    /// `2` deleted — hands back an identity already in use. That is D6's accepted cost (see
    /// `specs/197`), and the repair it named was one line in `monospace-diagram`: `Diagram::add`
    /// issues the first ordinal at or after this one that names no figure, which is what
    /// `specs/212-hold-the-diagram-as-a-persistent-value.md` decides. **So the numbering a file
    /// resumes at is a lower bound rather than a promise**, and a figure the diagram issued can come
    /// out under an ordinal later than the one the reader would have counted to. What **is** checked
    /// is the zero: zero is not an identity, so `"next_id": 0` is a data error naming the field
    /// rather than a counter seeded with something the diagram could not carry.
    #[serde(deserialize_with = "next_id")]
    next_id: NonZeroU16,
    /// The figures, in the order they are drawn. Required, and the order is load-bearing: the array
    /// order is the drawing order, so the last entry is front-most and decides a shared cell first.
    shapes: Vec<ShapeDescription>,
}

impl Description {
    /// Builds a description representation from `diagram`.
    fn from_diagram(diagram: &Diagram) -> Self {
        Self {
            next_id: diagram.next_id(),
            shapes: diagram
                .shapes()
                .map(|(id, shape)| ShapeDescription::from_shape(id, shape))
                .collect(),
        }
    }

    /// Builds a diagram from `shapes`, in order, under the identities the file wrote and with its
    /// numbering resuming where it says.
    ///
    /// **The order is still the order.** The array order remains the drawing order, so every
    /// picture in the repository comes out byte for byte what it did — that is the claim the whole
    /// mechanical change rests on, and it was measured rather than argued.
    ///
    /// A shape a connector names before the entry carrying it is written still resolves, because
    /// resolution happens at draw time and the whole diagram exists by then. That edge case needs
    /// no code here; it is what a whole diagram exists by then means.
    fn into_diagram(self) -> Diagram {
        let mut diagram = Diagram::numbered_from(self.next_id);
        for shape in self.shapes {
            diagram = diagram.add_under(shape.id(), shape.into());
        }
        diagram
    }
}

#[cfg(test)]
mod tests {
    use monospace_core::{Buffer, Direction, GlyphCatalog, Pos, Size, Window};
    use monospace_diagram::{Shape as DiagramShape, ShapeId};

    use super::{Description, Diagram, ParseError, parse};

    /// The error a description that must not read hands back.
    ///
    /// **A helper rather than `expect_err`**, which would need `Debug` on the pair `parse` returns:
    /// `Diagram` derives none, and deriving it here would mean the diagram crate grew a `Debug`
    /// every consumer inherits for the sake of one test module. `Result::err` does not.
    fn refusal(json: &str) -> ParseError {
        parse(json)
            .err()
            .expect("a description this format refuses must fail")
    }

    /// Rule 1 — `parse` reads a description and hands back the diagram it holds, and nothing else.
    ///
    /// **The test is the type.** A function that returns a `Diagram` cannot be handed a window, so
    /// the claim is made where it can fail: in a caller that binds one value and draws it into a
    /// window of its own choosing. A test asserting `parse(..).is_ok()` would pass against a
    /// signature returning a pair, and would prove nothing the compiler does not already.
    #[test]
    fn parse_hands_back_the_diagram_and_nothing_else() {
        let diagram: Diagram = parse(
            r#"{
            "next_id": 2,
            "shapes": [ { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 },
                          "size": { "width": 4, "height": 3 }, "stroke": "light" } ]
        }"#,
        )
        .expect("a well-formed description");

        // And the window is the caller's: the same diagram drawn into two different ones.
        let drawn = |origin: Pos, size: Size| {
            let mut buffer = Buffer::new(Window { origin, size });
            diagram.draw(&mut buffer);
            monospace_core::render(&buffer, &GlyphCatalog::light(), buffer.window())
        };
        let small = drawn(
            Pos { x: 0, y: 0 },
            Size {
                width: 4,
                height: 3,
            },
        );
        let large = drawn(
            Pos { x: 0, y: 0 },
            Size {
                width: 8,
                height: 3,
            },
        );

        assert_eq!(small, "┌──┐\n│  │\n└──┘\n");
        assert_ne!(
            small, large,
            "the window is the caller's, not the description's"
        );
    }

    /// Rule 9 — a box's `text` is one string, `\n` splits it into lines, and any other control
    /// character is refused naming the field it was written in.
    #[test]
    fn a_description_refuses_a_control_character_in_text() {
        let json = r#"{
            "next_id": 2,
            "shapes": [ { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 },
                          "size": { "width": 4, "height": 3 }, "stroke": "light",
                          "text": "a\tb" } ]
        }"#;
        let error = refusal(json).to_string();

        assert!(
            error.contains("`text`"),
            "the refusal names the field the text was written in: {error}"
        );

        let json = json.replace("a\\tb", "one\\ntwo");
        parse(&json).expect("`\\n` is the one control character a text allows");
    }

    /// Rule 9 — a box's `text` is read and drawn centred in the box's interior: an 8x5 box puts
    /// `hi` at `(3, 2)`, the position the diagram's own box test measures.
    #[test]
    fn a_description_reads_a_box_with_text() {
        let diagram = parse(
            r#"{
            "next_id": 2,
            "shapes": [ { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 },
                          "size": { "width": 8, "height": 5 }, "stroke": "light",
                          "text": "hi" } ]
        }"#,
        )
        .expect("a box with a text is a well-formed description");

        let mut buffer = Buffer::new(Window {
            origin: Pos { x: 0, y: 0 },
            size: Size {
                width: 8,
                height: 5,
            },
        });
        diagram.draw(&mut buffer);

        assert_eq!(
            monospace_core::render(&buffer, &GlyphCatalog::light(), buffer.window()),
            "┌──────┐\n│      │\n│  hi  │\n│      │\n└──────┘\n"
        );
    }

    /// Rule 2 — a description carrying a `canvas` is read, and the canvas ignored.
    ///
    /// **The file says `13x9` and the picture is drawn at `6x4`.** That is the whole of the claim,
    /// and it is the block a reader should be least comfortable with: a file that says it is one
    /// size and is drawn at another is a wrong answer given without an error. It is accepted because
    /// there is no writer, so nothing outside this repository has ever produced a file, and every
    /// marker is rewritten in the same increment.
    #[test]
    fn a_description_carrying_a_canvas_is_read_and_the_canvas_ignored() {
        let json = r#"{
            "canvas": { "origin": { "x": 0, "y": 0 }, "size": { "width": 13, "height": 9 } },
            "next_id": 2,
            "shapes": [ { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 },
                          "size": { "width": 4, "height": 3 }, "stroke": "light" } ]
        }"#;

        let diagram: Diagram = parse(json).expect("a description carrying a canvas still reads");
        let origin = Pos { x: 0, y: 0 };
        let size = Size {
            width: 6,
            height: 4,
        };
        let mut buffer = Buffer::new(Window { origin, size });
        diagram.draw(&mut buffer);

        assert_eq!(
            monospace_core::render(&buffer, &GlyphCatalog::light(), buffer.window()),
            "┌──┐  \n│  │  \n└──┘  \n      \n",
            "the `13x9` in the file has no say in it: the picture is the window the caller chose"
        );
    }

    /// The rendering of a parsed description, drawn into `size` at `origin`.
    ///
    /// **The window is a parameter rather than something the description carries**, which is the
    /// whole of what this crate's public surface is now: a caller that wants a picture names the
    /// window, and the description it drew from has nothing to say about it.
    ///
    /// **The core's own Light table, and no glyph set beside it.** Every shape here is drawn in
    /// `light`, which is what Light covers, and the two tests that need a picture are about what a
    /// reference resolves to rather than about how a stroke draws — so a second catalog would add a
    /// dependency to answer nothing they ask. Measured rather than argued: the same three shapes
    /// drawn in `double` come out of this catalog as an empty buffer.
    fn render_once(description: Description, origin: Pos, size: Size) -> String {
        let diagram = description.into_diagram();

        let mut buffer = Buffer::new(Window { origin, size });
        diagram.draw(&mut buffer);
        monospace_core::render(&buffer, &GlyphCatalog::light(), buffer.window())
    }

    /// An unrecognized `kind` fails to deserialize and names the unrecognized value.
    #[test]
    fn an_unrecognized_kind_fails_to_deserialize_and_names_it() {
        let json = r#"{
            "canvas": { "origin": { "x": 0, "y": 0 }, "size": { "width": 4, "height": 3 } },
            "next_id": 1,
            "shapes": [ { "kind": "triangle" } ]
        }"#;

        let error = refusal(json);

        assert!(error.to_string().contains("triangle"), "{error}");
    }

    /// A `fill` of more than one grapheme cluster fails to deserialize.
    #[test]
    fn a_multi_grapheme_fill_fails_to_deserialize() {
        let json = r#"{
            "canvas": { "origin": { "x": 0, "y": 0 }, "size": { "width": 4, "height": 3 } },
            "next_id": 2,
            "shapes": [
                { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 }, "size": { "width": 4, "height": 3 },
                  "stroke": "light", "fill": "ab" }
            ]
        }"#;

        assert!(parse(json).is_err());
    }

    /// A `terminal`'s glyph of more than one grapheme cluster fails to deserialize. The grapheme
    /// check sits on the named field inside the tagged object, which is the only reason the wire
    /// form is internally tagged.
    #[test]
    fn a_multi_grapheme_terminal_glyph_fails_to_deserialize() {
        let json = r#"{
            "canvas": { "origin": { "x": 0, "y": 0 }, "size": { "width": 8, "height": 1 } },
            "next_id": 2,
            "shapes": [
                { "kind": "connector", "id": 1,
                  "from": { "at": { "kind": "point", "x": 0, "y": 0 }, "leaving": "right",
                            "terminal": { "kind": "glyph", "glyph": "ab" } },
                  "to": { "at": { "kind": "point", "x": 6, "y": 0 }, "leaving": "left",
                          "terminal": { "kind": "glyph", "glyph": ">" } },
                  "stroke": "light" }
            ]
        }"#;

        assert!(parse(json).is_err());
    }

    /// One connector, with `TERMINAL` standing where the `from` endpoint's terminal goes. The three
    /// refusals below differ only in what is written there, which is what makes them the same test
    /// three times over.
    const ARROW: &str = r#""from": { "at": { "kind": "point", "x": 0, "y": 0 }, "leaving": "right", "terminal": TERMINAL },
                  "to": { "at": { "kind": "point", "x": 6, "y": 0 }, "leaving": "left",
                          "terminal": { "kind": "glyph", "glyph": ">" } }"#;

    /// The same connector with the field left out altogether.
    const ARROW_WITHOUT_A_TERMINAL: &str = r#""from": { "at": { "kind": "point", "x": 0, "y": 0 }, "leaving": "right" },
                  "to": { "at": { "kind": "point", "x": 6, "y": 0 }, "leaving": "left",
                          "terminal": { "kind": "glyph", "glyph": ">" } }"#;

    fn description_of(connector: &str) -> String {
        format!(
            r#"{{
            "canvas": {{ "origin": {{ "x": 0, "y": 0 }}, "size": {{ "width": 8, "height": 1 }} }},
            "next_id": 2,
            "shapes": [
                {{ "kind": "connector", "id": 1,
                  {connector},
                  "stroke": "light" }}
            ]
        }}"#
        )
    }

    /// The message the binary reports for an endpoint whose terminal is `terminal`.
    ///
    /// `serde_json` appends the position the problem was found at, so what is compared is the
    /// message this crate produced and not the whole of what `serde_json` renders.
    fn error_for(terminal: &str) -> String {
        let json = description_of(&ARROW.replace("TERMINAL", terminal));
        refusal(&json).to_string()
    }

    /// A `kind` the model has not named is refused by name, and the message names the three that
    /// are accepted — so the value is never read as one of them.
    #[test]
    fn an_unrecognized_terminal_kind_names_it_and_the_three_that_are_accepted() {
        let error = error_for(r#"{ "kind": "dot" }"#);

        assert!(
            error.starts_with("unknown variant `dot`, expected one of `glyph`, `symbol`, `arm`"),
            "{error}"
        );
    }

    /// A symbol terminal names a style, and a file that leaves the field out is refused **by
    /// name** rather than read as an arm or as a default style. The fallback #245 proposed was for
    /// an unknown name; a missing one is not a name at all.
    #[test]
    fn a_symbol_terminal_without_a_style_is_refused_by_name() {
        let error = error_for(r#"{ "kind": "symbol" }"#);

        assert!(error.starts_with("missing field `style`"), "{error}");
    }

    /// D6's other half: a style name the catalog does not hold is accepted by `parse` and draws a
    /// space, because the name is resolved at render rather than where the file is read. The
    /// catalog here holds `solid`, so the space is the misspelled name's and not a missing table's.
    #[test]
    fn an_unknown_style_name_draws_a_space() {
        let json = description_of(
            r#""from": { "at": { "kind": "point", "x": 0, "y": 0 }, "leaving": "right",
                         "terminal": { "kind": "symbol", "style": "nope" } },
               "to": { "at": { "kind": "point", "x": 6, "y": 0 }, "leaving": "left",
                       "terminal": { "kind": "symbol", "style": "solid" } }"#,
        );
        let diagram = parse(&json).expect("an unknown style is read, not refused");
        let mut buffer = Buffer::new(Window {
            origin: Pos { x: 0, y: 0 },
            size: Size {
                width: 7,
                height: 1,
            },
        });
        diagram.draw(&mut buffer);
        let catalog = GlyphCatalog::union([GlyphCatalog::light(), GlyphCatalog::solid()]);

        assert_eq!(
            monospace_core::render(&buffer, &catalog, buffer.window()),
            " ─────▶\n",
            "the unknown name is a space and the held one draws its glyph"
        );
    }

    /// A `glyph` that is not exactly one grapheme cluster is rejected with the message the old
    /// `head` produced, byte for byte.
    #[test]
    fn a_multi_grapheme_terminal_glyph_is_rejected_with_the_message_the_old_head_produced() {
        let error = error_for(r#"{ "kind": "glyph", "glyph": "ab" }"#);

        assert!(
            error.starts_with("\"ab\" is not exactly one grapheme cluster"),
            "{error}"
        );
    }

    /// The field is required for both values, so a file that omits it is refused rather than read
    /// as a connector with no terminal at either end. A terminal's presence never decides what a
    /// description means.
    #[test]
    fn an_omitted_terminal_field_is_refused_by_name() {
        let json = description_of(ARROW_WITHOUT_A_TERMINAL);

        let error = refusal(&json).to_string();

        assert!(error.starts_with("missing field `terminal`"), "{error}");
    }

    /// The externally tagged spelling was measured too: every value of `terminal` is an object
    /// tagged by `kind`, so a bare string is refused on purpose rather than read as an arm.
    #[test]
    fn an_externally_tagged_terminal_is_refused() {
        let error = error_for(r#""arm""#);

        assert!(
            error.starts_with(
                r#"invalid type: string "arm", expected internally tagged enum Terminal"#
            ),
            "{error}"
        );
    }

    /// The same connector as `ARROW`, with `AT` standing where the `from` endpoint's `at` goes, so
    /// the three cases below differ only in what an `at` says and the file around it is fixed.
    const ARROW_WITH_AN_AT: &str = r#""from": { "at": AT, "leaving": "right",
        "terminal": { "kind": "arm" } },
      "to": { "at": { "kind": "point", "x": 6, "y": 0 }, "leaving": "left",
              "terminal": { "kind": "glyph", "glyph": ">" } }"#;

    /// A connector whose `from` endpoint stands at `AT` without a `leaving` direction, used for
    /// reference endpoints which derive leaving from their anchor.
    const ARROW_WITH_A_REFERENCE: &str = r#""from": { "at": AT,
        "terminal": { "kind": "arm" } },
      "to": { "at": { "kind": "point", "x": 6, "y": 0 }, "leaving": "left",
              "terminal": { "kind": "glyph", "glyph": ">" } }"#;

    /// The message the binary reports for an endpoint whose `at` is `at`, read the way a reader
    /// reads it: the message, not the `serde_json` position that follows it.
    fn error_for_an_at(at: &str) -> String {
        let json = description_of(&ARROW_WITH_AN_AT.replace("AT", at));
        refusal(&json).to_string()
    }

    /// A point written without a tag is **refused**, not read as one of the two.
    ///
    /// The position that follows the message is `serde_json`'s and moves with the bytes, which is
    /// why what is compared is the message. Before the tag landed this file rendered and exited
    /// successfully — the silence the tag is there to end, measured both ways.
    #[test]
    fn an_untagged_at_is_refused_by_name() {
        let error = error_for_an_at(r#"{ "x": 0, "y": 0 }"#);

        assert!(error.starts_with("missing field `kind`"), "{error}");
    }

    /// A `kind` the union has no arm for is refused by name, **and the message names the two it
    /// does have** — so the value is never read as one of them.
    ///
    /// The same rule this format's other `kind` fields have always obeyed, and the message is the
    /// whole of what choosing the tag bought over an untagged union, which would have answered the
    /// same file with `data did not match any variant of untagged enum At`.
    #[test]
    fn an_unknown_at_kind_names_it_and_the_two_that_are_accepted() {
        let error = error_for_an_at(r#"{ "kind": "arrows", "x": 0, "y": 0 }"#);

        assert!(
            error.starts_with("unknown variant `arrows`, expected `point` or `reference`"),
            "{error}"
        );
    }

    /// A `point` written beside a stray `shape` is **accepted**, and the `shape` is dropped in
    /// silence.
    ///
    /// This is the format's existing behavior rather than anything this slice adds, and it is the
    /// cost of an internal tag rather than a defect: the tag is the rule, and a field beside it is
    /// an unknown field exactly as a description carrying `mode` was before the format dropped it.
    /// Pinned because the alternative — refusing a file for a harmless extra key — is the change a
    /// later slice would make silently, and this is where the present answer is written down.
    #[test]
    fn a_stray_field_beside_an_at_is_dropped_in_silence() {
        let json = description_of(
            &ARROW_WITH_AN_AT.replace("AT", r#"{ "kind": "point", "x": 1, "y": 1, "shape": 5 }"#),
        );

        assert!(
            parse(&json).is_ok(),
            "a stray field beside a tagged `at` must not refuse the file"
        );
    }

    /// A reference carrying **no** `offset` at all reads, and is a reference standing on the side
    /// itself — which is the case the field's being optional exists for.
    ///
    /// Without `#[serde(default)]` this would be a missing-field error on `offset`, and every
    /// reference meaning "on the border" would have to spell two zeros to say nothing — the reason
    /// the field is optional and absent zero.
    #[test]
    fn a_reference_with_no_offset_is_read_as_a_reference_on_the_side_itself() {
        let json = description_of(&ARROW_WITH_A_REFERENCE.replace(
            "AT",
            r#"{ "kind": "reference", "shape": 1, "anchor": "right" }"#,
        ));

        assert!(
            parse(&json).is_ok(),
            "a reference without an `offset` must read"
        );
    }

    /// An unknown key **inside** a reference is dropped in silence — which is why a file could not
    /// spell `out` before the field existed, and why `"out": 1` read by a build without it draws the
    /// point on the border and says nothing at all.
    ///
    /// One level in from `a_stray_field_beside_an_at_is_dropped_in_silence`: that one puts a field
    /// beside the tag and this one beside a reference's own fields, and both are the same cost of an
    /// internal tag. **`along` is the key this is really about** — the second spelling of the amount
    /// that runs along the side, declined because the offset already says it — so a file naming it
    /// reads, and reads as a reference that says nothing about it.
    #[test]
    fn an_unknown_key_inside_a_reference_is_dropped_in_silence() {
        let json = description_of(&ARROW_WITH_A_REFERENCE.replace(
            "AT",
            r#"{ "kind": "reference", "shape": 1, "anchor": "right", "along": 2 }"#,
        ));

        assert!(
            parse(&json).is_ok(),
            "an unknown key beside a reference's own fields must not refuse the file"
        );
    }

    /// A reference follows the identity, **both directions**.
    ///
    /// Two descriptions over the same window, the same two boxes and the same connector, differing
    /// only in the order their entries are listed in. The connector naming the **box** draws the
    /// same buffer whichever order the entries are in; the connector naming the **place** draws two
    /// different pictures, which is what those files mean today.
    ///
    /// Both directions, because a reader that made the identity win in one and not in the other
    /// would pass a single test — and the second half is the one that is easy to leave out, since
    /// the first half is what the slice is for.
    ///
    /// **The identities are ordinals rather than the free text this test used to give them**,
    /// which is the whole cost the format change names: the two halves are still about the same
    /// thing — an identity is not a place — and they say it with `1` and `2`.
    #[test]
    fn a_reference_follows_the_identity_and_not_the_place_where_the_entry_is_written() {
        // Two boxes at **fixed** positions, far enough apart that the route to either is a
        // different drawing: one at `{0, 3}` and one at `{11, 3}`, and a connector falling from
        // `{7, 0}` onto the **top** of whichever box it is told to name. The two boxes do not
        // touch, which is what makes the two routes distinguishable at all — measured, because a
        // pair that shares cells composes to the same picture whichever way round it is built.
        //
        // `left` and `right` are the ordinals given to the box at `{0, 3}` and the one at `{11, 3}`
        // respectively, and `right_listed_first` says which of them the `shapes` array lists
        // first. Nothing else changes between the four descriptions below, so the route can only
        // move if the reader is following the place rather than the identity.
        let description_with =
            |left: u16, right: u16, right_listed_first: bool, connector_names| {
                let left_box = format!(
                    r#"{{ "kind": "box", "id": {left}, "at": {{ "x": 0, "y": 3 }},
                  "size": {{ "width": 4, "height": 3 }}, "stroke": "light" }}"#
                );
                let right_box = format!(
                    r#"{{ "kind": "box", "id": {right}, "at": {{ "x": 11, "y": 3 }},
                  "size": {{ "width": 4, "height": 3 }}, "stroke": "light" }}"#
                );
                let boxes = if right_listed_first {
                    format!("{right_box},\n                {left_box}")
                } else {
                    format!("{left_box},\n                {right_box}")
                };
                format!(
                    r#"{{
            "canvas": {{ "origin": {{ "x": 0, "y": 0 }}, "size": {{ "width": 16, "height": 6 }} }},
            "next_id": 3,
            "shapes": [
                {boxes},
                {{ "kind": "connector", "id": 3,
                  "from": {{ "at": {{ "kind": "point", "x": 7, "y": 0 }}, "leaving": "down",
                             "terminal": {{ "kind": "glyph", "glyph": "▼" }} }},
                  "to": {{ "at": {{ "kind": "reference", "shape": {connector_names},
                                      "anchor": "top" }},
                          "terminal": {{ "kind": "arm" }} }},
                  "stroke": "light" }}
            ]
        }}"#
                )
            };
        // `serde_json` and not [`parse`]: `render_once` takes the `Description` because the window
        // is a parameter now, and `parse` hands back the diagram and nothing else.
        let read = |json: String| serde_json::from_str::<Description>(&json).expect("well-formed");
        let window = (
            Pos { x: 0, y: 0 },
            Size {
                width: 16,
                height: 6,
            },
        );

        // Naming the **box**: the box at `{11, 3}` is `2` in both files and is listed first in one
        // and second in the other, so both draw the same picture.
        let right_listed_first =
            render_once(read(description_with(1, 2, true, 2)), window.0, window.1);
        let right_listed_second =
            render_once(read(description_with(1, 2, false, 2)), window.0, window.1);
        assert_eq!(
            right_listed_first, right_listed_second,
            "a reference naming a shape must not move when the entries are listed in another order"
        );

        // Naming the **place**: `2` is the identity the second entry carries in each file, and the
        // two files put a different box there, so the connector lands on a different box in each.
        // That is what those files mean today, and the half that says the identity won in one
        // direction and not in the other — a reader that made it win in both would have failed the
        // first half.
        let place_right_first =
            render_once(read(description_with(2, 1, true, 2)), window.0, window.1);
        let place_right_second =
            render_once(read(description_with(1, 2, false, 2)), window.0, window.1);
        assert_ne!(
            place_right_first, place_right_second,
            "a reference naming a place must still follow the place it is written at"
        );
    }

    /// A missing identity is refused **by name**, exactly as `canvas`, `shapes`, `leaving`,
    /// `terminal` and `at`'s `kind` already are.
    ///
    /// Asserted on the message and not on the line and column that follow it, which are serde's
    /// and move with the bytes. The `display_with_line_column` half of the claim is the rest of the
    /// format's existing behavior and is already pinned by
    /// `an_omitted_terminal_field_is_refused_by_name`; this pins the two new names beside it.
    #[test]
    fn a_missing_identity_is_refused_by_name() {
        let without_next_id = r#"{
            "canvas": { "origin": { "x": 0, "y": 0 }, "size": { "width": 4, "height": 3 } },
            "shapes": [ { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 },
                          "size": { "width": 4, "height": 3 }, "stroke": "light" } ]
        }"#;
        let without_an_id = r#"{
            "canvas": { "origin": { "x": 0, "y": 0 }, "size": { "width": 4, "height": 3 } },
            "next_id": 2,
            "shapes": [ { "kind": "box", "at": { "x": 0, "y": 0 },
                          "size": { "width": 4, "height": 3 }, "stroke": "light" } ]
        }"#;

        for (json, named) in [(without_next_id, "next_id"), (without_an_id, "id")] {
            let error = refusal(json);
            assert!(
                error
                    .to_string()
                    .contains(&format!("missing field `{named}`")),
                "expected `missing field `{named}``, got: {error}"
            );
        }
    }

    /// Free text is **refused**, and the message names the field it was refused on.
    ///
    /// **Both fields, and both spellings**, because the three identity fields share one
    /// deserializer and the only thing that differs between them is the name it puts in the
    /// message. `serde`'s own wording — `invalid type: string "#1", expected a nonzero u16` — names
    /// neither, so a reader handed it has nothing to work back from; and a wrapper that named
    /// `id` for all three would send a reader after the wrong field on the other two.
    ///
    /// **The spelling is quoted and not summarized**, so a file that wrote `"arrow"` says so rather
    /// than being told it wrote something else. The `next_id` half is
    /// `a_next_id_of_zero_is_refused_and_names_the_field_it_was_refused_on` beside this one.
    #[test]
    fn an_identity_written_as_free_text_is_refused_and_names_the_field() {
        let a_string_id = r#"{
            "canvas": { "origin": { "x": 0, "y": 0 }, "size": { "width": 4, "height": 3 } },
            "next_id": 2,
            "shapes": [ { "kind": "box", "id": "arrow", "at": { "x": 0, "y": 0 },
                          "size": { "width": 4, "height": 3 }, "stroke": "light" } ]
        }"#;
        let a_string_shape = &description_of(&ARROW_WITH_A_REFERENCE.replace(
            "AT",
            r##"{ "kind": "reference", "shape": "#1", "anchor": "right" }"##,
        ));

        for (json, named, said) in [
            (a_string_id, "id", "\"arrow\""),
            (a_string_shape, "shape", "\"#1\""),
        ] {
            let error = refusal(json).to_string();
            assert!(
                error.starts_with(&format!("`{named}` is an ordinal: ")),
                "expected `{named}` to be named first, got: {error}"
            );
            assert!(
                error.contains(said),
                "expected the message to quote what the file said, `{said}`, got: {error}"
            );
        }
    }

    /// A `next_id` of zero is refused and named, because zero is not an identity.
    ///
    /// **`0` is the one value the whole format cannot express**, so a counter that took it would be
    /// a counter seeded with nothing the diagram could carry — and the old reader held it and issued
    /// `"#0"` from it. The refusal names `next_id` for the same reason the other two name theirs.
    #[test]
    fn a_next_id_of_zero_is_refused_and_names_the_field_it_was_refused_on() {
        let json = r#"{
            "canvas": { "origin": { "x": 0, "y": 0 }, "size": { "width": 4, "height": 3 } },
            "next_id": 0,
            "shapes": [ { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 },
                          "size": { "width": 4, "height": 3 }, "stroke": "light" } ]
        }"#;

        let error = refusal(json).to_string();

        assert!(
            error.starts_with("`next_id` is an ordinal: "),
            "expected `next_id` to be named first, got: {error}"
        );
        assert!(
            error.contains('0'),
            "expected the message to quote the zero it was handed, got: {error}"
        );
    }

    /// An ordinal is read everywhere the format names a shape, and the file still draws.
    ///
    /// **The positive case beside the two refusals**, because a reader that refused everything
    /// would pass both of those. The same three fields are here written as `1` and `2`, and the
    /// connector's reference resolves through the ordinal the box carries: **a connector answers no
    /// anchor**, so this draws the connector rather than the window an unresolvable reference leaves,
    /// which is what makes the refusal above and this the same field read two ways.
    #[test]
    fn an_ordinal_is_read_where_the_format_names_a_shape() {
        let json = r#"{
            "canvas": { "origin": { "x": 0, "y": 0 }, "size": { "width": 8, "height": 3 } },
            "next_id": 3,
            "shapes": [
                { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 },
                  "size": { "width": 4, "height": 3 }, "stroke": "light" },
                { "kind": "connector", "id": 2,
                  "from": { "at": { "kind": "reference", "shape": 1, "anchor": "right" },
                            "terminal": { "kind": "glyph", "glyph": ">" } },
                  "to": { "at": { "kind": "point", "x": 7, "y": 1 }, "leaving": "left",
                          "terminal": { "kind": "arm" } },
                  "stroke": "light" }
            ]
        }"#;

        let picture = render_once(
            serde_json::from_str::<Description>(json).expect("an ordinal is an ordinal"),
            Pos { x: 0, y: 0 },
            Size {
                width: 8,
                height: 3,
            },
        );

        assert!(
            picture.contains('>'),
            "the connector must draw, so the reference resolved through the ordinal: {picture:?}"
        );
    }

    #[test]
    fn converting_a_diagram_to_description_and_back_preserves_the_diagram() {
        let json = include_str!("../../monospace/assets/demo.json");
        let original = parse(json).expect("demo parses");
        let description = Description::from_diagram(&original);
        let restored = description.into_diagram();
        let second_description = Description::from_diagram(&restored);
        assert_eq!(second_description, Description::from_diagram(&original));
    }

    #[test]
    fn serialize_produces_two_space_indented_json_ending_in_newline() {
        let json = include_str!("../../monospace/assets/demo.json");
        let diagram = parse(json).expect("demo parses");
        let serialized = super::serialize(&diagram).expect("serializes");

        assert!(
            serialized.ends_with('\n'),
            "serialized JSON has no trailing newline"
        );
        assert!(serialized.contains("  \"next_id\": 28,\n  \"shapes\": ["));

        let read_again = parse(&serialized).expect("reads serialized JSON back");
        let description_after = Description::from_diagram(&read_again);
        assert_eq!(description_after, Description::from_diagram(&diagram));
    }

    /// A reference with a non-zero `out` preserves both `offset` and `out` across serialization,
    /// and a reference with an `out` of zero omits the `out` field from the JSON output.
    #[test]
    fn serializing_a_reference_preserves_its_out_field_and_omits_it_when_zero() {
        let json = r#"{
  "canvas": {
    "origin": { "x": 0, "y": 0 },
    "size": { "width": 10, "height": 5 }
  },
  "next_id": 4,
  "shapes": [
    {
      "kind": "box",
      "id": 1,
      "at": { "x": 0, "y": 0 },
      "size": { "width": 4, "height": 3 },
      "stroke": "light"
    },
    {
      "kind": "connector",
      "id": 2,
      "from": {
        "at": {
          "kind": "reference",
          "shape": 1,
          "anchor": "right",
          "offset": { "dx": 2, "dy": -1 },
          "out": 1
        },
        "terminal": { "kind": "arm" }
      },
      "to": {
        "at": { "kind": "point", "x": 8, "y": 1 },
        "leaving": "left",
        "terminal": { "kind": "arm" }
      },
      "stroke": "light"
    },
    {
      "kind": "connector",
      "id": 3,
      "from": {
        "at": {
          "kind": "reference",
          "shape": 1,
          "anchor": "bottom",
          "offset": { "dx": 1, "dy": 0 }
        },
        "terminal": { "kind": "arm" }
      },
      "to": {
        "at": { "kind": "point", "x": 2, "y": 4 },
        "leaving": "up",
        "terminal": { "kind": "arm" }
      },
      "stroke": "light"
    }
  ]
}"#;

        let diagram = parse(json).expect("valid description parses");
        let serialized = super::serialize(&diagram).expect("serializes cleanly");

        assert!(
            serialized.contains("\"out\": 1"),
            "serialized output must preserve non-zero out: {serialized}"
        );
        assert!(
            serialized.contains("\"dx\": 2") && serialized.contains("\"dy\": -1"),
            "offset must remain separate without folding out into it: {serialized}"
        );

        let round_tripped = parse(&serialized).expect("serialized JSON parses back");
        assert_eq!(
            Description::from_diagram(&round_tripped),
            Description::from_diagram(&diagram),
            "round trip preserves the description structure"
        );

        let desc = serde_json::from_str::<serde_json::Value>(&serialized)
            .expect("serialized JSON is valid JSON");
        let shapes = desc["shapes"].as_array().expect("shapes is array");
        let conn2_from = &shapes[1]["from"]["at"];
        assert_eq!(conn2_from["out"], 1);
        assert_eq!(conn2_from["offset"]["dx"], 2);
        assert_eq!(conn2_from["offset"]["dy"], -1);

        let conn3_from = &shapes[2]["from"]["at"];
        assert!(
            conn3_from.get("out").is_none(),
            "an out of zero is omitted from the serialized reference JSON"
        );
        assert!(
            shapes[1]["from"].get("leaving").is_none(),
            "reference endpoint must omit leaving when serialized"
        );
        assert_eq!(shapes[1]["to"]["leaving"], "left");
    }

    /// A reference endpoint derives its leaving direction from its anchor and must not specify
    /// `leaving`.
    #[test]
    fn a_reference_endpoint_without_leaving_derives_its_leaving_direction_from_the_anchor() {
        let json = r#"{
            "next_id": 3,
            "shapes": [
                { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 },
                  "size": { "width": 4, "height": 3 }, "stroke": "light" },
                { "kind": "connector", "id": 2,
                  "from": { "at": { "kind": "reference", "shape": 1, "anchor": "right" },
                            "terminal": { "kind": "arm" } },
                  "to": { "at": { "kind": "point", "x": 8, "y": 1 }, "leaving": "left",
                          "terminal": { "kind": "arm" } },
                  "stroke": "light" }
            ]
        }"#;

        let diagram = parse(json).expect("valid reference endpoint without leaving parses");
        let connector = diagram.get(ShapeId::new(std::num::NonZeroU16::new(2).unwrap()));
        let Some(DiagramShape::Connector { from, .. }) = connector else {
            panic!("expected connector");
        };
        assert_eq!(from.leaving(), Direction::Right);
    }

    /// A point endpoint requires a leaving direction and is refused by name if `leaving` is missing.
    #[test]
    fn a_point_endpoint_without_leaving_is_refused_by_name() {
        let json = r#"{
            "next_id": 2,
            "shapes": [
                { "kind": "connector", "id": 1,
                  "from": { "at": { "kind": "point", "x": 1, "y": 2 },
                            "terminal": { "kind": "arm" } },
                  "to": { "at": { "kind": "point", "x": 8, "y": 2 }, "leaving": "left",
                          "terminal": { "kind": "arm" } },
                  "stroke": "light" }
            ]
        }"#;

        let error = refusal(json).to_string();
        assert!(
            error.starts_with("missing field `leaving`"),
            "expected missing field `leaving`, got: {error}"
        );
    }

    /// A reference endpoint specifying a leaving direction is rejected.
    #[test]
    fn a_reference_endpoint_with_leaving_is_rejected() {
        let json = r#"{
            "next_id": 3,
            "shapes": [
                { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 },
                  "size": { "width": 4, "height": 3 }, "stroke": "light" },
                { "kind": "connector", "id": 2,
                  "from": { "at": { "kind": "reference", "shape": 1, "anchor": "right" },
                            "leaving": "right",
                            "terminal": { "kind": "arm" } },
                  "to": { "at": { "kind": "point", "x": 8, "y": 1 }, "leaving": "left",
                          "terminal": { "kind": "arm" } },
                  "stroke": "light" }
            ]
        }"#;

        let error = refusal(json).to_string();
        assert!(
            error.contains(
                "a reference endpoint derives its leaving direction from its anchor and must not specify `leaving`"
            ),
            "expected error refusing leaving on reference endpoint, got: {error}"
        );
    }

    /// Serializing a connector omits `leaving` on a reference endpoint and writes it on a point endpoint.
    #[test]
    fn serializing_a_connector_omits_leaving_on_a_reference_and_includes_it_on_a_point() {
        let json = r#"{
            "next_id": 3,
            "shapes": [
                { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 },
                  "size": { "width": 4, "height": 3 }, "stroke": "light" },
                { "kind": "connector", "id": 2,
                  "from": { "at": { "kind": "reference", "shape": 1, "anchor": "right" },
                            "terminal": { "kind": "arm" } },
                  "to": { "at": { "kind": "point", "x": 8, "y": 1 }, "leaving": "left",
                          "terminal": { "kind": "arm" } },
                  "stroke": "light" }
            ]
        }"#;

        let diagram = parse(json).expect("valid description parses");
        let serialized = super::serialize(&diagram).expect("serializes cleanly");
        let desc = serde_json::from_str::<serde_json::Value>(&serialized).expect("valid json");
        let shapes = desc["shapes"].as_array().expect("shapes is array");
        let from = &shapes[1]["from"];
        let to = &shapes[1]["to"];

        assert!(
            from.get("leaving").is_none(),
            "reference endpoint must omit leaving when serialized: {serialized}"
        );
        assert_eq!(
            to["leaving"], "left",
            "point endpoint must include leaving when serialized: {serialized}"
        );
    }
}