monospace-editing 0.1.2

Editing sessions over a plain-text diagram, with undo and redo: commands, steps and history
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
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
//! The contract tests for the editing layer, one per rule of
//! [`specs/197-an-editing-layer-above-the-diagram-model.md`](../../../specs/197-an-editing-layer-above-the-diagram-model.md)'s
//! `## Behavior`, named after the rule each one holds.
//!
//! **Everything here is asserted on a picture**, which is what a caller sees and what the model's
//! worked example is written in. Comparing figures would be a claim about a value nothing outside
//! this crate can see, and comparing a session's diagram against a diagram's would only say the
//! session hands back what it was given.
//!
//! **Two kinds of window are in use and neither is sampled.** `EXAMPLE` is the specification's
//! own `window(8, 3)`, which is exactly wide enough for a four-cell box and a displacement of
//! four, and the worked example in that document is reproduced here number for number. `FIXTURE`
//! is wider and taller because the fixture has two boxes and a connector under them.

use std::num::NonZeroU16;

use monospace_core::{
    Buffer, Direction, Glyph, GlyphCatalog, Orientation, Pos, Size, Stroke, Terminal, Text, Window,
    render,
};
use monospace_diagram::{
    Anchor, Delta, Diagram, End, Endpoint, EndpointAt, Reference, Shape, ShapeId,
};
use monospace_editing::{Command, Session};

/// The specification's window: `window(8, 3)`, wide enough for a four-cell box at the origin and
/// for the same box four cells to the right, which is the largest displacement the worked example
/// uses.
const EXAMPLE: Size = Size {
    width: 8,
    height: 3,
};

/// The window the fixture is drawn in: two boxes on the first three rows and a connector under
/// them.
const FIXTURE: Size = Size {
    width: 12,
    height: 6,
};

/// The origin every window here starts at, so a picture is a window's worth of rows and columns
/// measured from the same place.
const ORIGIN: Pos = Pos { x: 0, y: 0 };

/// The box at the origin, in [`EXAMPLE`]. **The rows carry four cells of padding** because the
/// window is eight wide and a four-cell box leaves the other four blank — written out here so the
/// literals below say which figure they show rather than how wide the window is.
const AS_WRITTEN: &str = "┌──┐    \n│  │    \n└──┘    \n";

/// The same box four cells to the right, which is the displacement the specification's worked
/// example uses and the widest one that fits [`EXAMPLE`] whole.
const FOUR_RIGHT: &str = "    ┌──┐\n    │  │\n    └──┘\n";

/// The same box two cells left of [`AS_WRITTEN`] — three cells in, so the window pads it on the
/// right rather than on the left.
const ONE_RIGHT: &str = "   ┌──┐ \n   │  │ \n   └──┘ \n";

/// The same box two cells right of [`FOUR_RIGHT`], whose last two columns fall outside the window
/// and are not drawn at all — which is why this picture is narrower rather than padded.
const SIX_RIGHT: &str = "      ┌─\n      │ \n      └─\n";

/// An identity of the ordinal `ordinal`, which is how every test below names a figure.
fn id(ordinal: u16) -> ShapeId {
    ShapeId::new(NonZeroU16::new(ordinal).expect("no test names zero"))
}

/// The box the specification's example calls `small_box(0, 0, no fill)`: four cells by three, no
/// interior, drawn in the light table.
fn small_box(at: Pos) -> Shape {
    Shape::Box {
        at,
        size: Size {
            width: 4,
            height: 3,
        },
        stroke: Stroke::from("light"),
        fill: None,
        text: None,
    }
}

/// The smallest a box shrinks to: a `2×2`, under which `BoxShape` draws nothing.
fn smallest_box(at: Pos) -> Shape {
    Shape::Box {
        at,
        size: Size {
            width: 2,
            height: 2,
        },
        stroke: Stroke::from("light"),
        fill: None,
        text: None,
    }
}

/// A diagram holding one of the boxes above and nothing else, so its `add` hands back `1`.
fn one_box(at: Pos) -> Diagram {
    Diagram::new().add(small_box(at)).0
}

/// The drawing of `diagram` into a fresh window of `size`.
///
/// A window of its own every time, because a caller repaints on every event and the claim under
/// test is never about a buffer left over from an earlier one.
fn picture_in(diagram: &Diagram, size: Size) -> String {
    let mut buffer = Buffer::new(Window {
        origin: ORIGIN,
        size,
    });
    diagram.draw(&mut buffer);
    render(&buffer, &GlyphCatalog::light(), buffer.window())
}

/// The drawing of what `session` holds, in the window the specification's example is drawn in.
fn picture(session: &Session) -> String {
    picture_in(session.diagram(), EXAMPLE)
}

/// The drawing of `diagram` the specification's example calls the first picture.
fn example_picture(diagram: &Diagram) -> String {
    picture_in(diagram, EXAMPLE)
}

/// What `command` leaves behind, in the window the fixture is drawn in.
fn after(command: &Command) -> String {
    let session = Session::new(the_fixture()).perform(command.clone());
    picture_in(session.diagram(), FIXTURE)
}

/// What the diagram's own operation leaves behind, over the same fixture.
///
/// **Taken as a function rather than written out four times**, so the two sides of the comparison
/// are the command and the operation and not a restatement of the command written in the diagram's
/// vocabulary, which would make the test agree with itself.
fn after_operating(on_diagram: impl FnOnce(&Diagram) -> Diagram) -> String {
    let diagram = the_fixture();
    picture_in(&on_diagram(&diagram), FIXTURE)
}

/// A diagram with something for every command to act on: two overlapping boxes, where the order
/// decides a shared cell, and a connector whose two ends are both plain points, where hanging one
/// from a side shows.
fn the_fixture() -> Diagram {
    let mut diagram = Diagram::new();
    diagram = diagram.add(small_box(ORIGIN)).0;
    diagram = diagram
        .add(Shape::Box {
            at: Pos { x: 2, y: 0 },
            size: Size {
                width: 4,
                height: 3,
            },
            stroke: Stroke::from("heavy"),
            fill: None,
            text: None,
        })
        .0;
    diagram = diagram
        .add(Shape::Connector {
            from: Endpoint::absolute(Pos { x: 0, y: 4 }, Direction::Right, Terminal::Arm),
            to: Endpoint::absolute(
                Pos { x: 8, y: 4 },
                Direction::Left,
                Terminal::Glyph {
                    glyph: Glyph::new("▶").expect("\"▶\" is one glyph"),
                },
            ),
            stroke: Stroke::from("light"),
        })
        .0;
    diagram
}

/// A figure the fixture does not hold, added by whichever test needs `add` to answer.
fn an_extra_box() -> Shape {
    Shape::Box {
        at: Pos { x: 6, y: 5 },
        size: Size {
            width: 2,
            height: 1,
        },
        stroke: Stroke::from("light"),
        fill: None,
        text: None,
    }
}

/// Rule 1 — the diagram a session holds is the one it was created over.
///
/// **The diagram is taken by value and the caller's copy is a diagram of its own.** Changed however
/// the caller likes afterwards, and the session neither follows it nor is reached by it: what is
/// asserted is that the two are two diagrams, which is the difference between a session owning a
/// diagram and a session sharing one.
#[test]
fn a_session_owns_the_diagram_it_was_created_over() {
    let the_callers_own = one_box(ORIGIN);
    let session = Session::new(the_callers_own.clone());

    assert_eq!(
        picture(&session),
        example_picture(&the_callers_own),
        "a session over a diagram draws that diagram"
    );

    let theirs = the_callers_own.forward(id(1)).remove(id(1));

    assert_ne!(
        picture_in(&theirs, EXAMPLE),
        example_picture(&the_callers_own),
        "the caller's own copy did change"
    );
    assert_eq!(
        picture(&session),
        example_picture(&the_callers_own),
        "and the session, which was given the diagram by value, did not follow it"
    );
}

/// Rule 2 — the diagram a session owns is changed only by a command performed against it.
///
/// **Two sessions over equal diagrams, one command performed on one of them.** What is held back is
/// that the command reached the session it was given and not some diagram both of them share:
/// there is nothing behind the diagram for it to reach through, and this is what a shared handle
/// would look like.
#[test]
fn the_diagram_changes_only_by_a_command_performed_on_it() {
    let given_nothing = Session::new(one_box(ORIGIN));
    let given = given_nothing.perform(Command::Move {
        id: id(1),
        by: Delta { dx: 4, dy: 0 },
    });

    assert_eq!(
        picture(&given_nothing),
        AS_WRITTEN,
        "the session the command was not given still holds what it was created over"
    );
    assert_eq!(
        picture(&given),
        FOUR_RIGHT,
        "and the one it was given moved by four"
    );
}

/// Rule 10 — no method of a session changes the session it was given.
///
/// **Every public method of `Session`, taken as a value of its exact signature.** What this pins is
/// each one, so a method that took `&mut self` or that returned nothing where it returns a session
/// now fails here. **There is no `Command::perform` in the list because there is no such method:**
/// a command is handed to a session and the way in is one method rather than two, which is the
/// change this list exists to record.
///
/// What this does not pin is the absence of a method added later, which no test written against a
/// type can see; the `compile_fail` documentation example on [`Session`] carries that half, and
/// neither of the two is a substitute for reading the surface.
#[test]
fn no_session_method_changes_the_session_it_was_given() {
    let _: fn(Diagram) -> Session = Session::new;
    let _: for<'a> fn(&'a Session) -> &'a Diagram = Session::diagram;
    let _: fn(&Session) -> bool = Session::can_undo;
    let _: fn(&Session) -> bool = Session::can_redo;
    let _: fn(&Session) -> Session = Session::undo;
    let _: fn(&Session) -> Session = Session::redo;
    let _: fn(&Session, Command) -> Session = Session::perform;
    let _: fn(&Session, Shape) -> (Session, ShapeId) = Session::add;
}

/// Rule 4 — every command becomes one of the diagram's seven operations.
///
/// **Each command against the operation it names, over the same fixture and in the same window.**
/// What makes it the mapping and not the command is that the right-hand side is written in the
/// diagram's own vocabulary — `forward`, `replace` with a figure read and rebuilt, `remove` — and
/// so a command that did something else, or something more, disagrees with it.
#[test]
#[expect(
    clippy::too_many_lines,
    reason = "the contract test covers each command in the set against its operation"
)]
fn each_command_becomes_one_of_the_diagrams_seven_operations() {
    let two_down = Delta { dx: 0, dy: 2 };

    assert_eq!(
        after(&Command::Move {
            id: id(1),
            by: two_down,
        }),
        after_operating(|diagram| {
            let moved = diagram.get(id(1)).map(|shape| shape.displaced_by(two_down));
            if let Some(moved) = moved {
                diagram.replace(id(1), moved)
            } else {
                diagram.clone()
            }
        }),
        "`Move` is `replace` with the figure displaced"
    );

    assert_eq!(
        after(&Command::Resize {
            id: id(1),
            by: two_down,
        }),
        after_operating(|diagram| {
            let resized = diagram.get(id(1)).map(|shape| shape.resized_by(two_down));
            if let Some(resized) = resized {
                diagram.replace(id(1), resized)
            } else {
                diagram.clone()
            }
        }),
        "`Resize` is `replace` with the figure resized"
    );

    assert_eq!(
        after(&Command::SetStroke {
            id: id(1),
            stroke: Stroke::from("double"),
        }),
        after_operating(|diagram| {
            let updated = diagram
                .get(id(1))
                .map(|shape| shape.with_stroke(Stroke::from("double")));
            if let Some(updated) = updated {
                diagram.replace(id(1), updated)
            } else {
                diagram.clone()
            }
        }),
        "`SetStroke` is `replace` with the figure's stroke changed"
    );

    assert_eq!(
        after(&Command::SetText {
            id: id(1),
            text: Some(Text::new("hi").unwrap()),
        }),
        after_operating(|diagram| {
            let updated = diagram
                .get(id(1))
                .map(|shape| shape.with_text(Some(Text::new("hi").unwrap())));
            if let Some(updated) = updated {
                diagram.replace(id(1), updated)
            } else {
                diagram.clone()
            }
        }),
        "`SetText` is `replace` with the figure's text changed"
    );

    assert_eq!(
        after(&Command::InvertTerminals { id: id(3) }),
        after_operating(|diagram| {
            let updated = diagram.get(id(3)).map(Shape::with_inverted_terminals);
            if let Some(updated) = updated {
                diagram.replace(id(3), updated)
            } else {
                diagram.clone()
            }
        }),
        "`InvertTerminals` is `replace` with the figure's terminals swapped"
    );

    assert_eq!(
        after(&Command::RotateLine { id: id(1) }),
        after_operating(|diagram| {
            let updated = diagram.get(id(1)).map(Shape::with_rotated_orientation);
            if let Some(updated) = updated {
                diagram.replace(id(1), updated)
            } else {
                diagram.clone()
            }
        }),
        "`RotateLine` is `replace` with the line's orientation toggled"
    );

    assert_eq!(
        after(&Command::MoveEndpoint {
            id: id(3),
            end: End::From,
            by: Delta { dx: 1, dy: 0 },
            out: 0,
        }),
        after_operating(|diagram| {
            let updated = diagram
                .get(id(3))
                .map(|shape| shape.with_endpoint_moved(End::From, Delta { dx: 1, dy: 0 }, 0));
            if let Some(updated) = updated {
                diagram.replace(id(3), updated)
            } else {
                diagram.clone()
            }
        }),
        "`MoveEndpoint` is `replace` with the endpoint moved"
    );

    assert_eq!(
        after(&Command::ResetEndpoint {
            id: id(3),
            end: End::From,
        }),
        after_operating(|diagram| {
            let updated = diagram
                .get(id(3))
                .map(|shape| shape.with_endpoint_reset(End::From));
            if let Some(updated) = updated {
                diagram.replace(id(3), updated)
            } else {
                diagram.clone()
            }
        }),
        "`ResetEndpoint` is `replace` with the endpoint reset"
    );

    assert_eq!(
        after(&Command::SetEndpointTerminal {
            id: id(3),
            end: End::From,
            terminal: Terminal::Glyph {
                glyph: Glyph::new("◆").unwrap(),
            },
        }),
        after_operating(|diagram| {
            let updated = diagram.get(id(3)).map(|shape| {
                shape.with_endpoint_terminal(
                    End::From,
                    Terminal::Glyph {
                        glyph: Glyph::new("◆").unwrap(),
                    },
                )
            });
            if let Some(updated) = updated {
                diagram.replace(id(3), updated)
            } else {
                diagram.clone()
            }
        }),
        "`SetEndpointTerminal` is `replace` with the endpoint terminal set"
    );

    assert_eq!(
        after(&Command::DetachEndpoint {
            id: id(3),
            end: End::From,
        }),
        after_operating(|diagram| {
            let updated = diagram
                .get(id(3))
                .map(|shape| shape.with_endpoint_detached(End::From, diagram));
            if let Some(updated) = updated {
                diagram.replace(id(3), updated)
            } else {
                diagram.clone()
            }
        }),
        "`DetachEndpoint` is `replace` with the endpoint detached"
    );

    assert_eq!(
        after(&Command::SetEndpointLeaving {
            id: id(3),
            end: End::From,
            leaving: Direction::Up,
        }),
        after_operating(|diagram| {
            let updated = diagram
                .get(id(3))
                .map(|shape| shape.with_endpoint_leaving(End::From, Direction::Up));
            if let Some(updated) = updated {
                diagram.replace(id(3), updated)
            } else {
                diagram.clone()
            }
        }),
        "`SetEndpointLeaving` is `replace` with the endpoint leaving direction set"
    );

    assert_eq!(
        after(&Command::Hang {
            id: id(3),
            end: End::From,
            target: id(1),
            anchor: Anchor::Bottom,
        }),
        after_operating(|diagram| {
            if let Some(shape) = diagram.get(id(3)).cloned() {
                diagram.replace(
                    id(3),
                    shape.with_endpoint_attached(
                        End::From,
                        Reference::new(id(1), Anchor::Bottom, Delta::ZERO, 0),
                        diagram,
                    ),
                )
            } else {
                diagram.clone()
            }
        }),
        "`Hang` is `replace` with one end of the connector attached"
    );

    assert_eq!(
        after(&Command::Forward { id: id(1) }),
        after_operating(|diagram| diagram.forward(id(1))),
        "`Forward` is `forward`"
    );

    assert_eq!(
        after(&Command::Backward { id: id(2) }),
        after_operating(|diagram| diagram.backward(id(2))),
        "`Backward` is `backward`"
    );

    assert_eq!(
        after(&Command::ToFront { id: id(1) }),
        after_operating(|diagram| diagram.to_front(id(1))),
        "`ToFront` is `to_front`"
    );

    assert_eq!(
        after(&Command::ToBack { id: id(2) }),
        after_operating(|diagram| diagram.to_back(id(2))),
        "`ToBack` is `to_back`"
    );

    assert_eq!(
        after(&Command::Add {
            shape: an_extra_box(),
        }),
        after_operating(|diagram| diagram.add(an_extra_box()).0),
        "`Add` is `add`"
    );

    assert_eq!(
        after(&Command::Remove { id: id(2) }),
        after_operating(|diagram| diagram.remove(id(2))),
        "`Remove` is `remove`"
    );
}

/// Rule 4 — and no command reaches the diagram by any other way.
///
/// **Every command, once, over one session, and then two readings of what is left.** The figures
/// still there are the fixture's minus the one that was taken out, and the ordinal the next `add`
/// would hand back is the one the fixture issued before any of them ran — which is what says that
/// nothing added a figure on the way, since `add` is the only operation that moves that counter.
#[test]
fn no_command_reaches_the_diagram_by_another_way() {
    let mut session = Session::new(the_fixture());

    for command in [
        Command::Forward { id: id(1) },
        Command::Backward { id: id(2) },
        Command::ToFront { id: id(1) },
        Command::ToBack { id: id(2) },
        Command::Move {
            id: id(1),
            by: Delta { dx: 0, dy: 2 },
        },
        Command::Hang {
            id: id(3),
            end: End::From,
            target: id(1),
            anchor: Anchor::Bottom,
        },
        Command::MoveEndpoint {
            id: id(3),
            end: End::From,
            by: Delta { dx: 1, dy: 0 },
            out: 0,
        },
        Command::ResetEndpoint {
            id: id(3),
            end: End::From,
        },
        Command::Forward { id: id(7) },
        Command::Move {
            id: id(7),
            by: Delta { dx: 1, dy: 1 },
        },
        Command::Resize {
            id: id(7),
            by: Delta { dx: 2, dy: 1 },
        },
        Command::Remove { id: id(2) },
        Command::Remove { id: id(7) },
    ] {
        session = session.perform(command.clone());
    }

    let diagram = session.diagram();
    assert!(
        diagram.get(id(2)).is_none(),
        "`Remove` took the figure it named out"
    );
    assert!(diagram.get(id(1)).is_some(), "the first box is still there");
    assert!(
        diagram.get(id(3)).is_some(),
        "the connector is still there, whatever `Hang` did to one end of it"
    );

    let (copy, issued) = diagram.clone().add(an_extra_box());
    assert_eq!(
        issued,
        id(4),
        "no command reached `add`, so the next ordinal is the one the fixture issued"
    );
    // And the copy is where the addition landed: a copy advances its own counter and the diagram
    // the session hands out is not the one that was added to.
    assert!(
        copy.get(issued).is_some(),
        "the copy holds the figure that was added to it"
    );
    assert!(
        diagram.get(issued).is_none(),
        "and the diagram the session hands out does not"
    );
}

/// Rule 5 — a command that changes nothing is not a step.
///
/// **The specification's fifth line**, a command naming a figure the diagram does not hold. It
/// changes nothing, records no step, and leaves what was ahead of the position untouched — which is
/// the rule as a caller meets it.
#[test]
fn a_command_naming_nothing_records_no_step() {
    let mut session = Session::new(one_box(ORIGIN));
    let as_written = picture(&session);

    session = session.perform(Command::Move {
        id: id(7),
        by: Delta { dx: 1, dy: 0 },
    });

    assert_eq!(
        picture(&session),
        as_written,
        "a command naming a figure the diagram does not hold changes nothing"
    );
    assert!(!session.can_undo(), "and records no step");
    assert!(
        !session.can_redo(),
        "and leaves nothing ahead of a position that did not move"
    );
}

/// Rule 6 — every command is a step of its own and the session merges none.
///
/// **Three commands and then three gives back, each of which moves the figure.** What makes it the
/// merge and not the recording is that the three gives back produce three different pictures: a session
/// that had merged them would have left one step behind, and the first undo would have jumped the
/// whole way back rather than one cell.
#[test]
fn two_commands_are_two_steps_and_are_never_merged() {
    let mut session = Session::new(one_box(ORIGIN));
    let mut forwards = vec![picture(&session)];

    for _ in 0..3 {
        session = session.perform(Command::Move {
            id: id(1),
            by: Delta { dx: 2, dy: 0 },
        });

        forwards.push(picture(&session));
    }

    let mut backwards = Vec::new();
    while session.can_undo() {
        session = session.undo();
        backwards.push(picture(&session));
    }

    let expected: Vec<String> = forwards[..3].iter().rev().cloned().collect();
    assert_eq!(
        backwards, expected,
        "three commands left three steps, and giving them back one at a time walks the pictures \
         back in the order they were made"
    );
}

/// Rule 7 — undo restores the diagram one step back, whole.
///
/// **The specification's second and third blocks.** The picture an undo produces is the one the
/// session held before any command, byte for byte — not a reconstruction of it, and not the box
/// put back where it was, which is what an inverted command would have had to be. **One command is
/// what makes this the end of the history rather than the middle of it**, so what an undo reaches
/// here is the diagram the session was created over, which is the one state no step holds.
#[test]
fn undo_restores_the_diagram_one_step_back() {
    let mut session = Session::new(one_box(ORIGIN));

    session = session.perform(Command::Move {
        id: id(1),
        by: Delta { dx: 4, dy: 0 },
    });

    assert_eq!(
        picture(&session),
        FOUR_RIGHT,
        "the figure moved four to the right"
    );
    assert!(session.can_undo(), "which left a step behind it");

    session = session.undo();

    assert_eq!(
        picture(&session),
        AS_WRITTEN,
        "and the undo brought it back"
    );
    assert!(!session.can_undo(), "with nothing behind it now");
}

/// Rule 8 — redo restores the diagram the step ahead holds, whole.
///
/// **The specification's fourth block**, which is the same picture the second one was: the step
/// ahead holds the state the command left, and the diagram is that state again.
#[test]
fn redo_restores_the_diagram_the_step_ahead_holds() {
    let mut session = Session::new(one_box(ORIGIN));

    session = session.perform(Command::Move {
        id: id(1),
        by: Delta { dx: 4, dy: 0 },
    });

    session = session.undo();
    session = session.redo();

    assert_eq!(
        picture(&session),
        FOUR_RIGHT,
        "the redo brought the move back"
    );
    assert!(!session.can_redo(), "with nothing ahead of it now");
    assert_eq!(
        picture(&session),
        FOUR_RIGHT,
        "and it is the picture the move made, not the one the undo left"
    );
}

/// Rule 9 — undoing with no step behind changes nothing.
///
/// **The seventh block of the specification's example**, which is the end of the history rather than
/// the middle of it: two gives back after two commands put the figure back and then ask a third time.
#[test]
fn undo_with_nothing_behind_changes_nothing() {
    let mut session = Session::new(one_box(ORIGIN));
    let as_written = picture(&session);

    session = session.undo();

    assert_eq!(picture(&session), as_written, "nothing was given back");
    assert!(!session.can_undo(), "and nothing is behind the position");
}

/// Rule 9 — redoing with no step ahead changes nothing.
#[test]
fn redo_with_nothing_ahead_changes_nothing() {
    let mut session = Session::new(one_box(ORIGIN));

    session = session.perform(Command::Move {
        id: id(1),
        by: Delta { dx: 4, dy: 0 },
    });

    let as_left = picture(&session);

    session = session.redo();

    assert_eq!(picture(&session), as_left, "nothing was carried out again");
    assert!(!session.can_redo(), "and nothing is ahead of the position");
}

/// Rule 11 of `specs/212` — a step holds the diagram the command left.
///
/// **The step is the state a command produced, and giving the change back is what shows it.** A
/// session that recorded nothing but the state it was already holding would satisfy every
/// assertion here on its own, so the ones that matter are the ones where a state is reached *from
/// both ends*: the state the session holds, the state one give back reaches, and the state two give
/// back reaches. **All three directions are asserted**, because a history that kept only one of the
/// two states satisfies either assertion alone.
///
/// **A second command on top of the first**, so the state the first left is what the second found
/// and the walk back reaches three states rather than the same one twice. The deltas are four and
/// two columns, which is why `AS_WRITTEN`, `FOUR_RIGHT` and `SIX_RIGHT` are the three pictures
/// rather than three literals written out again.
#[test]
fn a_step_holds_the_diagram_the_command_left() {
    let session = Session::new(one_box(ORIGIN));
    let after_one = session.perform(Command::Move {
        id: id(1),
        by: Delta { dx: 4, dy: 0 },
    });
    let after_two = after_one.perform(Command::Move {
        id: id(1),
        by: Delta { dx: 2, dy: 0 },
    });

    assert_eq!(
        picture(&session),
        AS_WRITTEN,
        "the session the commands were not given is the one it was created over"
    );
    assert_eq!(
        picture(&after_two),
        SIX_RIGHT,
        "and both commands were carried out"
    );
    assert_eq!(
        picture(&after_two.undo()),
        FOUR_RIGHT,
        "one give back is the state the first command left, which is the step behind the position"
    );
    assert_eq!(
        picture(&after_two.redo()),
        SIX_RIGHT,
        "and the step ahead is the state the second left"
    );
    assert_eq!(
        picture(&after_two.undo().undo()),
        AS_WRITTEN,
        "giving both back reaches the diagram as it was rather than the one in between twice"
    );
}

/// Rule 13 of `specs/212` — the history is a line and a position cannot disagree with it.
///
/// **The whole walk both ways, asking at every place whether there is something behind and whether
/// there is something ahead.** The two answers are the position read two ways, so a session that
/// disagreed with itself about where it stood would be caught by one of them; and the two walks
/// are asserted to be reverses of each other, which is what a line is and what a pair of stacks
/// with a shared position could also be — so the pictures are what says it.
///
/// **A place in the middle has both answers true**, and that is asserted rather than left out: it
/// is the only place where `can_undo` and `can_redo` can disagree with each other if one of them
/// is derived from the wrong end.
#[test]
fn the_history_is_a_line_a_position_cannot_disagree_with() {
    let start = Session::new(one_box(ORIGIN));
    let after_one = start.perform(Command::Move {
        id: id(1),
        by: Delta { dx: 4, dy: 0 },
    });
    let after_two = after_one.perform(Command::Move {
        id: id(1),
        by: Delta { dx: 2, dy: 0 },
    });

    assert!(
        after_two.can_undo() && !after_two.can_redo(),
        "at the newest position there is something behind and nothing ahead"
    );

    let mut backwards = vec![picture(&after_two)];
    let mut behind = after_two.clone();
    while behind.can_undo() {
        behind = behind.undo();
        backwards.push(picture(&behind));
    }
    assert_eq!(
        backwards,
        vec![SIX_RIGHT, FOUR_RIGHT, AS_WRITTEN],
        "walking back passes through every state in the order it was made, the other way round"
    );

    assert!(
        !behind.can_undo(),
        "and at the oldest there is nothing behind"
    );
    assert!(
        behind.can_redo(),
        "while everything that was walked over is ahead, which is the same position read twice"
    );
    assert_eq!(
        picture(&behind.undo()),
        AS_WRITTEN,
        "and asking again at the oldest end answers with the session as it stands"
    );

    let mut forwards = vec![picture(&behind)];
    let mut ahead = behind;
    while ahead.can_redo() {
        ahead = ahead.redo();
        forwards.push(picture(&ahead));
    }
    assert_eq!(
        forwards,
        vec![AS_WRITTEN, FOUR_RIGHT, SIX_RIGHT],
        "walking forward retraces the same pictures in the other order"
    );
    assert!(
        !ahead.can_redo(),
        "and at the newest end there is nothing ahead"
    );
    assert_eq!(
        picture(&ahead.redo()),
        SIX_RIGHT,
        "and asking again at the newest end answers with the session as it stands"
    );
}

/// Rule 10 — a command carried out with steps ahead of the position discards them.
///
/// **Move, move, give one back, and move again**, which is the only way a position can be behind
/// the end. What is held is not that `redo` is unavailable afterwards — that alone would also be
/// true of a history truncated rather than discarded — but that **the undo out of the new command
/// reaches the state the first move left and not the state the second one left**, which is what the
/// discard dropped. The two differ by one cell, and the walk back over the discarded step would
/// land on the wrong one.
#[test]
fn a_command_with_steps_ahead_discards_them() {
    let mut session = Session::new(one_box(ORIGIN));

    session = session.perform(Command::Move {
        id: id(1),
        by: Delta { dx: 4, dy: 0 },
    });

    session = session.perform(Command::Move {
        id: id(1),
        by: Delta { dx: -1, dy: 0 },
    });

    session = session.undo();
    assert_eq!(
        picture(&session),
        FOUR_RIGHT,
        "one give back is the state the first move left"
    );

    session = session.perform(Command::Move {
        id: id(1),
        by: Delta { dx: 2, dy: 0 },
    });

    assert_eq!(
        picture(&session),
        SIX_RIGHT,
        "the new command was carried out from where the session stood"
    );
    assert!(
        !session.can_redo(),
        "the step that was ahead of the position was discarded"
    );

    session = session.undo();
    assert_eq!(
        picture(&session),
        FOUR_RIGHT,
        "one back is the state the first move left"
    );
    assert_ne!(
        picture(&session),
        ONE_RIGHT,
        "and not the state the discarded step held, which stood one cell nearer"
    );

    session = session.undo();
    assert_eq!(
        picture(&session),
        AS_WRITTEN,
        "and the second back is the diagram the session began with"
    );
}

/// Rule 11 — whether undo and redo are available is answerable without carrying either out.
///
/// **Asked at every position, drawing between the questions.** What is claimed is that answering
/// leaves the picture exactly where it was, which is what lets a caller grey out a control rather
/// than guess, and that the answers are right at each of the three positions a run passes through.
#[test]
fn whether_undo_is_available_is_answerable_without_carrying_it_out() {
    let mut session = Session::new(one_box(ORIGIN));
    let as_written = picture(&session);

    assert!(
        (session.can_undo(), session.can_redo()) == (false, false),
        "a session with nothing behind it has nothing to give back and nothing to carry out"
    );

    session = session.perform(Command::Move {
        id: id(1),
        by: Delta { dx: 4, dy: 0 },
    });

    assert!(
        (session.can_undo(), session.can_redo()) == (true, false),
        "after one command there is a step behind and none ahead"
    );
    assert!(
        session.can_undo(),
        "asked again, and the picture is untouched by being asked"
    );

    session = session.undo();

    assert!(
        (session.can_undo(), session.can_redo()) == (false, true),
        "at the oldest position it is the other way round"
    );
    assert!(session.can_redo());
    assert_eq!(
        picture(&session),
        as_written,
        "and every question left the picture where it was"
    );
}

/// Rule 12 — the diagram is drawn by borrowing it.
///
/// **A buffer drawn from `session.diagram()` and one drawn from the diagram the session was
/// created over, without anything copied in between.** The borrow is the claim: no `Diagram` is
/// taken, none is cloned, and the picture is the one the diagram model already draws. **The second
/// half is that a copy taken anyway is unconnected**: §7 of the model says a session hands out a
/// reference for drawing and a copy for keeping, and a copy a caller keeps does not follow the
/// session.
#[test]
fn drawing_what_a_session_holds_needs_no_copy() {
    let diagram = one_box(ORIGIN);

    let mut as_created = Buffer::new(Window {
        origin: ORIGIN,
        size: EXAMPLE,
    });
    diagram.draw(&mut as_created);

    let session = Session::new(diagram);
    let mut borrowed = Buffer::new(Window {
        origin: ORIGIN,
        size: EXAMPLE,
    });
    session.diagram().draw(&mut borrowed);

    assert_eq!(
        render(&borrowed, &GlyphCatalog::light(), borrowed.window()),
        render(&as_created, &GlyphCatalog::light(), as_created.window()),
        "a drawing of what a session holds is a drawing of the diagram it was created over"
    );
    assert_eq!(
        render(&borrowed, &GlyphCatalog::light(), borrowed.window()),
        AS_WRITTEN,
        "and it is the picture that diagram draws"
    );

    // And a copy is a diagram like any other: free of the session and unconnected to it, which is
    // what §7 is about. Nothing here is handed out but a borrow, so the copy is the caller's own.
    let theirs = session.diagram().clone();
    let mut session = session;
    session = session.perform(Command::Move {
        id: id(1),
        by: Delta { dx: 4, dy: 0 },
    });

    assert_eq!(
        picture_in(&theirs, EXAMPLE),
        AS_WRITTEN,
        "the copy did not move with the session's diagram"
    );
    assert_eq!(picture(&session), FOUR_RIGHT, "which did");
}

#[test]
fn a_resize_command_changes_the_size() {
    let session = Session::new(the_fixture()).perform(Command::Resize {
        id: id(1),
        by: Delta { dx: 2, dy: 1 },
    });

    let Shape::Box { size, .. } = session.diagram().get(id(1)).expect("box is still there") else {
        panic!("expected box");
    };

    assert_eq!(
        *size,
        Size {
            width: 6,
            height: 4
        }
    );
}

#[test]
fn a_resize_naming_nothing_leaves_the_diagram_untouched_and_records_no_step() {
    let session = Session::new(the_fixture()).perform(Command::Resize {
        id: id(999),
        by: Delta { dx: 2, dy: 1 },
    });
    assert_eq!(
        picture_in(session.diagram(), FIXTURE),
        picture_in(&the_fixture(), FIXTURE)
    );
    assert!(!session.can_undo(), "and no step was recorded");
}

#[test]
fn a_resize_at_the_smallest_size_records_no_step() {
    let diagram = Diagram::new().add(smallest_box(ORIGIN)).0;
    let session = Session::new(diagram);
    let before = picture_in(session.diagram(), EXAMPLE);

    let shrunk = session.perform(Command::Resize {
        id: id(1),
        by: Delta { dx: -1, dy: -1 },
    });
    assert_eq!(
        picture_in(shrunk.diagram(), EXAMPLE),
        before,
        "shrinking a 2×2 box changes nothing"
    );
    assert!(!shrunk.can_undo(), "and records no step");

    let grown = shrunk.perform(Command::Resize {
        id: id(1),
        by: Delta { dx: 1, dy: 0 },
    });
    assert!(
        grown.can_undo(),
        "but growing it again records its step as any other command"
    );
}

#[test]
fn hanging_an_end_where_it_already_hangs_records_no_step() {
    let session = Session::new(the_fixture());
    let initial_pic = picture_in(session.diagram(), FIXTURE);

    let hung = session.perform(Command::Hang {
        id: id(3),
        end: End::From,
        target: id(1),
        anchor: Anchor::Bottom,
    });
    assert!(hung.can_undo(), "hanging an end records its step");

    let hung_again = hung.perform(Command::Hang {
        id: id(3),
        end: End::From,
        target: id(1),
        anchor: Anchor::Bottom,
    });
    assert_eq!(
        picture_in(hung_again.diagram(), FIXTURE),
        picture_in(hung.diagram(), FIXTURE),
        "hanging it where it already hangs changes nothing"
    );

    let undone = hung_again.undo();
    assert_eq!(
        picture_in(undone.diagram(), FIXTURE),
        initial_pic,
        "so a single undo returns to the initial state"
    );
}

#[test]
fn attaching_the_to_end_attaches_to_the_target() {
    let session = Session::new(the_fixture());
    let initial_pic = picture_in(session.diagram(), FIXTURE);

    let attached = session.perform(Command::Hang {
        id: id(3),
        end: End::To,
        target: id(2),
        anchor: Anchor::Bottom,
    });
    assert!(attached.can_undo(), "attaching the to end records its step");
    assert_ne!(
        picture_in(attached.diagram(), FIXTURE),
        initial_pic,
        "attaching the to end changes the diagram"
    );

    let Shape::Connector { to, from, .. } = attached.diagram().get(id(3)).unwrap() else {
        panic!("id(3) must be a connector");
    };
    assert_eq!(
        to.at,
        EndpointAt::Reference(Reference::new(id(2), Anchor::Bottom, Delta::ZERO, 0))
    );
    assert!(matches!(from.at, EndpointAt::Absolute { .. }));

    let undone = attached.undo();
    assert_eq!(
        picture_in(undone.diagram(), FIXTURE),
        initial_pic,
        "undo returns to the initial state"
    );
}

#[test]
fn attaching_to_a_missing_target_records_no_step() {
    let session = Session::new(the_fixture());
    let initial_pic = picture_in(session.diagram(), FIXTURE);

    let attempted = session.perform(Command::Hang {
        id: id(3),
        end: End::From,
        target: id(99),
        anchor: Anchor::Bottom,
    });
    assert!(
        !attempted.can_undo(),
        "attaching to a missing target records no step"
    );
    assert_eq!(
        picture_in(attempted.diagram(), FIXTURE),
        initial_pic,
        "attaching to a missing target leaves diagram unchanged"
    );
}

#[test]
fn attaching_to_a_connector_records_no_step() {
    let session = Session::new(the_fixture());
    let initial_pic = picture_in(session.diagram(), FIXTURE);

    // id(3) is a connector in the_fixture, and connectors have no anchors
    let attempted = session.perform(Command::Hang {
        id: id(3),
        end: End::From,
        target: id(3),
        anchor: Anchor::Top,
    });
    assert!(
        !attempted.can_undo(),
        "attaching to a connector records no step"
    );
    assert_eq!(
        picture_in(attempted.diagram(), FIXTURE),
        initial_pic,
        "attaching to a connector leaves diagram unchanged"
    );
}

#[test]
fn attaching_an_already_attached_end_records_no_step() {
    let session = Session::new(the_fixture());

    let hung = session.perform(Command::Hang {
        id: id(3),
        end: End::From,
        target: id(1),
        anchor: Anchor::Bottom,
    });
    assert!(hung.can_undo());

    // Attempting to attach an already-attached end to a different target or anchor records no step
    let hung_again = hung.perform(Command::Hang {
        id: id(3),
        end: End::From,
        target: id(2),
        anchor: Anchor::Top,
    });
    assert_eq!(
        hung_again.diagram().get(id(3)),
        hung.diagram().get(id(3)),
        "attaching an already attached end leaves shape unchanged"
    );
    assert_eq!(
        picture_in(hung_again.diagram(), FIXTURE),
        picture_in(hung.diagram(), FIXTURE)
    );
    let undone = hung_again.undo();
    assert_eq!(
        picture_in(undone.diagram(), FIXTURE),
        picture_in(session.diagram(), FIXTURE),
        "only the first attach was recorded"
    );
}

#[test]
fn a_forward_of_the_front_most_figure_records_no_step() {
    let session = Session::new(the_fixture());
    let initial_pic = picture_in(session.diagram(), FIXTURE);

    let no_op = session.perform(Command::Forward { id: id(3) });
    assert_eq!(
        picture_in(no_op.diagram(), FIXTURE),
        initial_pic,
        "forwarding the front-most figure changes nothing"
    );
    assert!(!no_op.can_undo(), "and records no step");

    let moved = session.perform(Command::Forward { id: id(1) });
    assert!(
        moved.can_undo(),
        "forwarding an obscured figure records a step"
    );
}

#[test]
fn a_remove_naming_nothing_records_no_step() {
    let session = Session::new(one_box(ORIGIN));
    let initial_pic = picture(&session);

    let after_remove = session.perform(Command::Remove { id: id(9) });
    assert_eq!(picture(&after_remove), initial_pic);
    assert!(!after_remove.can_undo());
}

#[test]
fn a_move_by_nothing_records_no_step() {
    let session = Session::new(one_box(ORIGIN));
    let initial_pic = picture(&session);

    let after_move = session.perform(Command::Move {
        id: id(1),
        by: Delta { dx: 0, dy: 0 },
    });
    assert_eq!(picture(&after_move), initial_pic);
    assert!(!after_move.can_undo());
}

#[test]
fn a_command_that_changes_nothing_leaves_what_was_ahead() {
    let session = Session::new(one_box(ORIGIN));
    let moved = session.perform(Command::Move {
        id: id(1),
        by: Delta { dx: 2, dy: 0 },
    });
    let moved_pic = picture(&moved);

    let undone = moved.undo();
    assert!(undone.can_redo());

    let no_op = undone.perform(Command::Move {
        id: id(9),
        by: Delta { dx: 1, dy: 0 },
    });
    assert!(
        no_op.can_redo(),
        "a command that changed nothing preserves what was ahead"
    );

    let redone = no_op.redo();
    assert_eq!(
        picture(&redone),
        moved_pic,
        "and redo restores the state that was ahead"
    );
}

#[test]
fn two_resizes_are_two_steps() {
    let session = Session::new(one_box(ORIGIN));
    let after_one = session.perform(Command::Resize {
        id: id(1),
        by: Delta { dx: 1, dy: 0 },
    });
    let after_two = after_one.perform(Command::Resize {
        id: id(1),
        by: Delta { dx: 0, dy: 1 },
    });

    let Shape::Box { size: size_two, .. } = after_two.diagram().get(id(1)).expect("box") else {
        panic!("expected box");
    };
    assert_eq!(
        *size_two,
        Size {
            width: 5,
            height: 4
        }
    );

    let undone = after_two.undo();
    let Shape::Box { size: size_one, .. } = undone.diagram().get(id(1)).expect("box") else {
        panic!("expected box");
    };
    assert_eq!(
        *size_one,
        Size {
            width: 5,
            height: 3
        }
    );

    let undone_twice = undone.undo();
    let Shape::Box {
        size: size_orig, ..
    } = undone_twice.diagram().get(id(1)).expect("box")
    else {
        panic!("expected box");
    };
    assert_eq!(
        *size_orig,
        Size {
            width: 4,
            height: 3
        }
    );
}

#[test]
fn setting_a_figures_stroke_records_one_step() {
    let session = Session::new(one_box(ORIGIN));
    let updated = session.perform(Command::SetStroke {
        id: id(1),
        stroke: Stroke::from("double"),
    });

    assert!(
        updated.can_undo(),
        "setting a different stroke records a step"
    );
    let Shape::Box { stroke, .. } = updated.diagram().get(id(1)).expect("box") else {
        panic!("expected box");
    };
    assert_eq!(*stroke, Stroke::from("double"));

    let undone = updated.undo();
    let Shape::Box {
        stroke: orig_stroke,
        ..
    } = undone.diagram().get(id(1)).expect("box")
    else {
        panic!("expected box");
    };
    assert_eq!(*orig_stroke, Stroke::from("light"));
}

#[test]
fn setting_the_stroke_a_figure_already_has_records_no_step() {
    let session = Session::new(one_box(ORIGIN));
    let moved = session.perform(Command::Move {
        id: id(1),
        by: Delta { dx: 1, dy: 0 },
    });
    let moved_pic = picture(&moved);

    let undone = moved.undo();
    assert!(undone.can_redo());

    let no_op = undone.perform(Command::SetStroke {
        id: id(1),
        stroke: Stroke::from("light"),
    });
    assert!(
        no_op.can_redo(),
        "setting the stroke the figure already has preserves what was ahead"
    );

    let redone = no_op.redo();
    assert_eq!(
        picture(&redone),
        moved_pic,
        "and redo restores the state that was ahead"
    );
}

#[test]
fn setting_the_stroke_of_a_figure_the_diagram_does_not_hold_changes_nothing() {
    let session = Session::new(one_box(ORIGIN));
    let initial_pic = picture(&session);

    let no_op = session.perform(Command::SetStroke {
        id: id(999),
        stroke: Stroke::from("heavy"),
    });
    assert_eq!(picture(&no_op), initial_pic);
    assert!(!no_op.can_undo(), "and no step was recorded");
}

#[test]
fn a_set_text_command_changes_only_a_box() {
    let text = Text::new("hi").expect("\"hi\" holds no control character");

    assert_eq!(
        after(&Command::SetText {
            id: id(1),
            text: Some(text.clone()),
        }),
        after_operating(|diagram| {
            let updated = diagram
                .get(id(1))
                .map(|shape| shape.with_text(Some(text.clone())));
            if let Some(updated) = updated {
                diagram.replace(id(1), updated)
            } else {
                diagram.clone()
            }
        }),
        "`SetText` is `replace` with the figure's text changed"
    );
}

#[test]
fn an_invert_terminals_command_changes_only_a_connector() {
    assert_eq!(
        after(&Command::InvertTerminals { id: id(3) }),
        after_operating(|diagram| {
            let updated = diagram.get(id(3)).map(Shape::with_inverted_terminals);
            if let Some(updated) = updated {
                diagram.replace(id(3), updated)
            } else {
                diagram.clone()
            }
        }),
        "`InvertTerminals` is `replace` with the figure's terminals swapped"
    );
}

#[test]
fn setting_the_same_text_records_no_step() {
    let text = Text::new("hi").expect("\"hi\" holds no control character");
    let with_text = Session::new(one_box(ORIGIN)).perform(Command::SetText {
        id: id(1),
        text: Some(text.clone()),
    });

    let twice = with_text.perform(Command::SetText {
        id: id(1),
        text: Some(text),
    });
    let back = twice.undo();

    let Shape::Box { text: restored, .. } = back.diagram().get(id(1)).expect("box") else {
        panic!("expected box");
    };
    assert_eq!(
        *restored, None,
        "the second command recorded a step, so one undo stayed on the same text"
    );
}

#[test]
fn clearing_a_text_is_one_step() {
    let text = Text::new("hi").expect("\"hi\" holds no control character");
    let with_text = Session::new(one_box(ORIGIN)).perform(Command::SetText {
        id: id(1),
        text: Some(text.clone()),
    });
    let cleared = with_text.perform(Command::SetText {
        id: id(1),
        text: None,
    });

    assert!(cleared.can_undo(), "clearing the text recorded no step");
    let Shape::Box { text: now, .. } = cleared.diagram().get(id(1)).expect("box") else {
        panic!("expected box");
    };
    assert_eq!(*now, None);

    let undone = cleared.undo();
    let Shape::Box { text: restored, .. } = undone.diagram().get(id(1)).expect("box") else {
        panic!("expected box");
    };
    assert_eq!(*restored, Some(text), "one undo did not give the text back");
}

/// A movement at the end it is already at changes nothing and records no step.
#[test]
fn the_moves_that_change_nothing_record_no_step() {
    let session = Session::new(the_fixture());
    let initial_pic = picture_in(session.diagram(), FIXTURE);

    for command in [
        Command::Backward { id: id(1) },
        Command::ToFront { id: id(3) },
        Command::ToBack { id: id(1) },
    ] {
        let no_op = session.perform(command.clone());
        assert_eq!(
            picture_in(no_op.diagram(), FIXTURE),
            initial_pic,
            "{command:?} changed the picture"
        );
        assert!(!no_op.can_undo(), "{command:?} recorded a step");
    }
}

/// `Home` and `End` are one command each, so one undo reverses them whole.
#[test]
fn each_absolute_move_is_one_step_that_undo_reverses() {
    for command in [
        Command::ToFront { id: id(1) },
        Command::ToBack { id: id(2) },
    ] {
        let session = Session::new(the_fixture());
        let before = picture_in(session.diagram(), FIXTURE);
        let moved = session.perform(command.clone());

        assert!(moved.can_undo(), "{command:?} recorded no step");
        assert!(!moved.can_redo(), "{command:?} recorded more than one step");
        assert_eq!(
            picture_in(moved.undo().diagram(), FIXTURE),
            before,
            "one undo did not reverse {command:?}"
        );
    }
}

#[test]
fn inverting_terminals_swaps_terminals_and_records_one_step() {
    let session = Session::new(the_fixture());
    let before_pic = picture_in(session.diagram(), FIXTURE);

    let inverted = session.perform(Command::InvertTerminals { id: id(3) });
    assert!(inverted.can_undo(), "inverting terminals recorded no step");
    assert!(
        !inverted.can_redo(),
        "inverting terminals recorded more than one step"
    );

    let Shape::Connector { from, to, .. } = inverted.diagram().get(id(3)).expect("connector")
    else {
        panic!("expected connector");
    };
    assert_eq!(
        from.terminal,
        Terminal::Glyph {
            glyph: Glyph::new("▶").expect("glyph"),
        }
    );
    assert_eq!(to.terminal, Terminal::Arm);

    let after_pic = picture_in(inverted.diagram(), FIXTURE);
    assert_ne!(
        before_pic, after_pic,
        "picture should change after terminal swap"
    );

    let undone = inverted.undo();
    assert_eq!(
        picture_in(undone.diagram(), FIXTURE),
        before_pic,
        "single undo should restore initial terminals"
    );
}

#[test]
fn inverting_identical_terminals_records_no_step() {
    let mut diagram = Diagram::new();
    diagram = diagram
        .add(Shape::Connector {
            from: Endpoint::absolute(Pos { x: 0, y: 0 }, Direction::Right, Terminal::Arm),
            to: Endpoint::absolute(Pos { x: 5, y: 0 }, Direction::Left, Terminal::Arm),
            stroke: Stroke::from("light"),
        })
        .0;

    let session = Session::new(diagram);
    let initial_pic = picture_in(session.diagram(), EXAMPLE);

    let no_op = session.perform(Command::InvertTerminals { id: id(1) });
    assert_eq!(
        picture_in(no_op.diagram(), EXAMPLE),
        initial_pic,
        "identical terminals should not change picture"
    );
    assert!(
        !no_op.can_undo(),
        "identical terminals should record no step (#285)"
    );
}

#[test]
fn inverting_terminals_on_a_box_or_nonexistent_shape_records_no_step() {
    let session = Session::new(the_fixture());
    let initial_pic = picture_in(session.diagram(), FIXTURE);

    // Box id(1)
    let no_op_box = session.perform(Command::InvertTerminals { id: id(1) });
    assert_eq!(picture_in(no_op_box.diagram(), FIXTURE), initial_pic);
    assert!(
        !no_op_box.can_undo(),
        "inverting terminals on a box should record no step"
    );

    // Nonexistent id(99)
    let no_op_missing = session.perform(Command::InvertTerminals { id: id(99) });
    assert_eq!(picture_in(no_op_missing.diagram(), FIXTURE), initial_pic);
    assert!(
        !no_op_missing.can_undo(),
        "inverting terminals on nonexistent shape should record no step"
    );
}

#[test]
fn rotating_a_line_toggles_its_orientation_and_records_one_step() {
    let mut diagram = Diagram::new();
    diagram = diagram
        .add(Shape::Line {
            at: Pos { x: 1, y: 1 },
            len: 5,
            orientation: Orientation::Vertical,
            stroke: Stroke::from("light"),
        })
        .0;

    let session = Session::new(diagram);
    let initial_pic = picture_in(session.diagram(), FIXTURE);

    let rotated = session.perform(Command::RotateLine { id: id(1) });
    assert!(rotated.can_undo(), "rotating a line should record one step");
    assert!(!rotated.can_redo());

    let Shape::Line {
        orientation,
        at,
        len,
        stroke,
    } = rotated.diagram().get(id(1)).expect("line")
    else {
        panic!("expected line");
    };
    assert_eq!(*orientation, Orientation::Horizontal);
    assert_eq!(*at, Pos { x: 1, y: 1 });
    assert_eq!(*len, 5);
    assert_eq!(*stroke, Stroke::from("light"));

    let rotated_pic = picture_in(rotated.diagram(), FIXTURE);
    assert_ne!(initial_pic, rotated_pic);

    let undone = rotated.undo();
    assert_eq!(picture_in(undone.diagram(), FIXTURE), initial_pic);
}

#[test]
fn rotating_a_box_connector_or_nonexistent_shape_records_no_step() {
    let session = Session::new(the_fixture());
    let initial_pic = picture_in(session.diagram(), FIXTURE);

    // Box id(1)
    let no_op_box = session.perform(Command::RotateLine { id: id(1) });
    assert_eq!(picture_in(no_op_box.diagram(), FIXTURE), initial_pic);
    assert!(
        !no_op_box.can_undo(),
        "rotating a box should record no step"
    );

    // Connector id(3)
    let no_op_conn = session.perform(Command::RotateLine { id: id(3) });
    assert_eq!(picture_in(no_op_conn.diagram(), FIXTURE), initial_pic);
    assert!(
        !no_op_conn.can_undo(),
        "rotating a connector should record no step"
    );

    // Nonexistent id(99)
    let no_op_missing = session.perform(Command::RotateLine { id: id(99) });
    assert_eq!(picture_in(no_op_missing.diagram(), FIXTURE), initial_pic);
    assert!(
        !no_op_missing.can_undo(),
        "rotating nonexistent shape should record no step"
    );
}

#[test]
fn moving_an_endpoint_records_one_step_and_zero_delta_records_none() {
    let mut diagram = Diagram::new();
    diagram = diagram.add(small_box(ORIGIN)).0; // id(1): 4x3 at (0,0)
    diagram = diagram
        .add(Shape::Connector {
            from: Endpoint::reference(
                Reference::new(id(1), Anchor::Top, Delta::ZERO, 0),
                Terminal::Arm,
            ),
            to: Endpoint::absolute(Pos { x: 10, y: 0 }, Direction::Down, Terminal::Arm),
            stroke: Stroke::from("light"),
        })
        .0; // id(2)

    let session = Session::new(diagram);
    assert!(!session.can_undo());

    // Move horizontally records one step
    let moved_x = session.perform(Command::MoveEndpoint {
        id: id(2),
        end: End::From,
        by: Delta { dx: 1, dy: 0 },
        out: 0,
    });
    assert!(
        moved_x.can_undo(),
        "moving endpoint horizontally records a step"
    );

    // Move vertically records another step
    let moved_xy = moved_x.perform(Command::MoveEndpoint {
        id: id(2),
        end: End::From,
        by: Delta { dx: 0, dy: 2 },
        out: 0,
    });
    assert!(
        moved_xy.can_undo(),
        "moving endpoint vertically records a step"
    );
    let Shape::Connector { from, .. } = moved_xy.diagram().get(id(2)).unwrap() else {
        panic!()
    };
    let monospace_diagram::EndpointAt::Reference(ref r) = from.at else {
        panic!()
    };
    assert_eq!(r.offset, Delta { dx: 1, dy: 2 });

    // Moving with zero delta and zero out records no step (#285)
    let pic_before = picture_in(moved_xy.diagram(), FIXTURE);
    let no_op = moved_xy.perform(Command::MoveEndpoint {
        id: id(2),
        end: End::From,
        by: Delta::ZERO,
        out: 0,
    });
    assert_eq!(picture_in(no_op.diagram(), FIXTURE), pic_before);
    let undone = no_op.undo();
    let Shape::Connector { from, .. } = undone.diagram().get(id(2)).unwrap() else {
        panic!()
    };
    let monospace_diagram::EndpointAt::Reference(ref r) = from.at else {
        panic!()
    };
    assert_eq!(
        r.offset,
        Delta { dx: 1, dy: 0 },
        "zero delta move was a no-op so undo stepped back to moved_x"
    );
}

#[test]
fn adjusting_endpoint_out_via_move_endpoint_records_one_step_including_negative_out() {
    let mut diagram = Diagram::new();
    diagram = diagram.add(small_box(ORIGIN)).0; // id(1)
    diagram = diagram
        .add(Shape::Connector {
            from: Endpoint::reference(
                Reference::new(id(1), Anchor::Top, Delta::ZERO, 0),
                Terminal::Arm,
            ),
            to: Endpoint::absolute(Pos { x: 10, y: 0 }, Direction::Down, Terminal::Arm),
            stroke: Stroke::from("light"),
        })
        .0; // id(2)

    let session = Session::new(diagram);

    // Increase out by 1
    let out_plus = session.perform(Command::MoveEndpoint {
        id: id(2),
        end: End::From,
        by: Delta::ZERO,
        out: 1,
    });
    assert!(out_plus.can_undo(), "adjusting out records a step");
    let Shape::Connector { from, .. } = out_plus.diagram().get(id(2)).unwrap() else {
        panic!()
    };
    let monospace_diagram::EndpointAt::Reference(ref r) = from.at else {
        panic!()
    };
    assert_eq!(r.out, 1);

    // Decrease out to negative (-1)
    let out_neg = out_plus.perform(Command::MoveEndpoint {
        id: id(2),
        end: End::From,
        by: Delta::ZERO,
        out: -2,
    });
    assert!(out_neg.can_undo(), "negative out records a step");
    let Shape::Connector { from, .. } = out_neg.diagram().get(id(2)).unwrap() else {
        panic!()
    };
    let monospace_diagram::EndpointAt::Reference(ref r) = from.at else {
        panic!()
    };
    assert_eq!(r.out, -1);
}

#[test]
fn resetting_an_endpoint_clears_offset_and_out_in_one_step_and_zero_endpoint_records_none() {
    let mut diagram = Diagram::new();
    diagram = diagram.add(small_box(ORIGIN)).0; // id(1)
    diagram = diagram
        .add(Shape::Connector {
            from: Endpoint::reference(
                Reference::new(id(1), Anchor::Top, Delta { dx: 1, dy: 0 }, 2),
                Terminal::Arm,
            ),
            to: Endpoint::absolute(Pos { x: 10, y: 0 }, Direction::Down, Terminal::Arm),
            stroke: Stroke::from("light"),
        })
        .0; // id(2)

    let session = Session::new(diagram);
    assert!(!session.can_undo());

    // Resetting displaced endpoint records one step and clears both offset and out
    let reset = session.perform(Command::ResetEndpoint {
        id: id(2),
        end: End::From,
    });
    assert!(
        reset.can_undo(),
        "resetting non-zero endpoint records a step"
    );
    let Shape::Connector { from, .. } = reset.diagram().get(id(2)).unwrap() else {
        panic!()
    };
    let monospace_diagram::EndpointAt::Reference(ref r) = from.at else {
        panic!()
    };
    assert_eq!(r.offset, Delta::ZERO);
    assert_eq!(r.out, 0);

    // Resetting when already at zero records no step (#285)
    let no_op = reset.perform(Command::ResetEndpoint {
        id: id(2),
        end: End::From,
    });
    // Undoing should undo the first reset, proving no new step was pushed
    let undone = no_op.undo();
    let Shape::Connector { from, .. } = undone.diagram().get(id(2)).unwrap() else {
        panic!()
    };
    let monospace_diagram::EndpointAt::Reference(ref r) = from.at else {
        panic!()
    };
    assert_eq!(r.offset, Delta { dx: 1, dy: 0 });
    assert_eq!(r.out, 2);
}

#[test]
fn setting_endpoint_terminal_records_one_step_and_identical_terminal_records_none() {
    let mut diagram = Diagram::new();
    diagram = diagram.add(small_box(ORIGIN)).0; // id(1)
    diagram = diagram
        .add(Shape::Connector {
            from: Endpoint::reference(
                Reference::new(id(1), Anchor::Top, Delta { dx: 1, dy: 0 }, 2),
                Terminal::Arm,
            ),
            to: Endpoint::absolute(Pos { x: 10, y: 0 }, Direction::Down, Terminal::Arm),
            stroke: Stroke::from("light"),
        })
        .0; // id(2)

    let session = Session::new(diagram);
    assert!(!session.can_undo());

    let glyph_terminal = Terminal::Glyph {
        glyph: Glyph::new("◆").unwrap(),
    };

    // Setting a different terminal records one step and updates the targeted endpoint
    let updated = session.perform(Command::SetEndpointTerminal {
        id: id(2),
        end: End::From,
        terminal: glyph_terminal.clone(),
    });
    assert!(
        updated.can_undo(),
        "setting different terminal records a step"
    );
    let Shape::Connector { from, to, .. } = updated.diagram().get(id(2)).unwrap() else {
        panic!()
    };
    assert_eq!(from.terminal, glyph_terminal);
    assert_eq!(to.terminal, Terminal::Arm);

    // Setting identical terminal records no step (#285)
    let no_op = updated.perform(Command::SetEndpointTerminal {
        id: id(2),
        end: End::From,
        terminal: glyph_terminal,
    });
    // Undoing should undo the first set, proving no new step was pushed
    let undone = no_op.undo();
    let Shape::Connector { from, .. } = undone.diagram().get(id(2)).unwrap() else {
        panic!()
    };
    assert_eq!(from.terminal, Terminal::Arm);
}

#[test]
fn setting_endpoint_terminal_on_non_connector_records_none() {
    let mut diagram = Diagram::new();
    diagram = diagram.add(small_box(ORIGIN)).0; // id(1)

    let session = Session::new(diagram);
    assert!(!session.can_undo());

    let no_op = session.perform(Command::SetEndpointTerminal {
        id: id(1),
        end: End::From,
        terminal: Terminal::Glyph {
            glyph: Glyph::new("◆").unwrap(),
        },
    });

    assert!(
        !no_op.can_undo(),
        "setting endpoint terminal on non-connector records no step"
    );
}

#[test]
fn detaching_attached_endpoint_records_one_step_and_already_detached_records_none() {
    use monospace_diagram::EndpointAt;

    let mut diagram = Diagram::new();
    diagram = diagram.add(small_box(ORIGIN)).0; // id(1)
    diagram = diagram
        .add(Shape::Connector {
            from: Endpoint::reference(
                Reference::new(id(1), Anchor::Top, Delta { dx: 1, dy: 0 }, 2),
                Terminal::Arm,
            ),
            to: Endpoint::absolute(Pos { x: 10, y: 0 }, Direction::Down, Terminal::Arm),
            stroke: Stroke::from("light"),
        })
        .0; // id(2)

    let session = Session::new(diagram);
    assert!(!session.can_undo());

    // Detaching the attached From endpoint records one step and freezes to Absolute
    let detached_session = session.perform(Command::DetachEndpoint {
        id: id(2),
        end: End::From,
    });
    assert!(
        detached_session.can_undo(),
        "detaching attached endpoint records a step"
    );
    let Shape::Connector { from, to, .. } = detached_session.diagram().get(id(2)).unwrap() else {
        panic!()
    };
    assert!(
        matches!(from.at, EndpointAt::Absolute { .. }),
        "targeted endpoint becomes Absolute"
    );
    assert_eq!(
        to.at,
        EndpointAt::Absolute {
            at: Pos { x: 10, y: 0 },
            leaving: Direction::Down
        }
    );

    // Detaching an already-detached endpoint records no step (#285)
    let no_op_from = detached_session.perform(Command::DetachEndpoint {
        id: id(2),
        end: End::From,
    });
    assert_eq!(
        no_op_from.diagram().get(id(2)),
        detached_session.diagram().get(id(2)),
        "detaching already-detached endpoint does not modify shape"
    );

    let no_op_to = no_op_from.perform(Command::DetachEndpoint {
        id: id(2),
        end: End::To,
    });
    assert_eq!(
        no_op_to.diagram().get(id(2)),
        detached_session.diagram().get(id(2)),
        "detaching already-detached endpoint does not modify shape"
    );

    // Undoing should undo the first detachment, proving no extra step was pushed
    let undone = no_op_to.undo();
    let Shape::Connector {
        from: undone_from, ..
    } = undone.diagram().get(id(2)).unwrap()
    else {
        panic!()
    };
    assert!(
        matches!(undone_from.at, EndpointAt::Reference(_)),
        "undo restores reference endpoint"
    );
    assert!(!undone.can_undo(), "only one step was recorded");
}

#[test]
fn setting_endpoint_leaving_records_one_step_and_identical_or_attached_records_none() {
    use monospace_diagram::EndpointAt;

    let mut diagram = Diagram::new();
    diagram = diagram.add(small_box(ORIGIN)).0; // id(1)
    diagram = diagram
        .add(Shape::Connector {
            from: Endpoint::absolute(Pos { x: 5, y: 5 }, Direction::Right, Terminal::Arm),
            to: Endpoint::reference(
                Reference::new(id(1), Anchor::Top, Delta::ZERO, 0),
                Terminal::Arm,
            ),
            stroke: Stroke::from("light"),
        })
        .0; // id(2)

    let session = Session::new(diagram);
    assert!(!session.can_undo());

    // Setting a different leaving direction on detached endpoint records one step
    let updated = session.perform(Command::SetEndpointLeaving {
        id: id(2),
        end: End::From,
        leaving: Direction::Down,
    });
    assert!(
        updated.can_undo(),
        "setting different leaving direction records a step"
    );
    let Shape::Connector { from, to, .. } = updated.diagram().get(id(2)).unwrap() else {
        panic!()
    };
    assert_eq!(
        from.at,
        EndpointAt::Absolute {
            at: Pos { x: 5, y: 5 },
            leaving: Direction::Down
        }
    );
    assert!(
        matches!(to.at, EndpointAt::Reference(_)),
        "attached endpoint remains unchanged"
    );

    // Setting identical leaving records no step (#285)
    let no_op_identical = updated.perform(Command::SetEndpointLeaving {
        id: id(2),
        end: End::From,
        leaving: Direction::Down,
    });
    assert_eq!(
        no_op_identical.diagram().get(id(2)),
        updated.diagram().get(id(2)),
        "setting identical leaving records no step"
    );

    // Setting leaving on attached endpoint (To) records no step (#285)
    let no_op_attached = no_op_identical.perform(Command::SetEndpointLeaving {
        id: id(2),
        end: End::To,
        leaving: Direction::Left,
    });
    assert_eq!(
        no_op_attached.diagram().get(id(2)),
        updated.diagram().get(id(2)),
        "setting leaving on attached endpoint records no step"
    );

    // Undoing should undo the first set, proving no extra steps were pushed
    let undone = no_op_attached.undo();
    let Shape::Connector {
        from: undone_from, ..
    } = undone.diagram().get(id(2)).unwrap()
    else {
        panic!()
    };
    assert_eq!(
        undone_from.at,
        EndpointAt::Absolute {
            at: Pos { x: 5, y: 5 },
            leaving: Direction::Right
        }
    );
    assert!(!undone.can_undo(), "only one step was recorded");
}

#[test]
fn adding_a_shape_via_session_add_assigns_id_records_one_step_and_undo_redo_walk_it() {
    let session = Session::new(Diagram::new());
    assert!(!session.can_undo());
    assert!(!session.can_redo());
    assert_eq!(session.diagram().shape_count(), 0);

    let (added, assigned_id) = session.add(small_box(ORIGIN));
    assert_eq!(assigned_id, id(1));
    assert_eq!(added.diagram().shape_count(), 1);
    assert!(added.diagram().get(assigned_id).is_some());
    assert!(added.can_undo());
    assert!(!added.can_redo());
    assert_eq!(picture(&added), AS_WRITTEN);

    let undone = added.undo();
    assert_eq!(undone.diagram().shape_count(), 0);
    assert!(!undone.can_undo());
    assert!(undone.can_redo());

    let redone = undone.redo();
    assert_eq!(redone.diagram().shape_count(), 1);
    assert_eq!(picture(&redone), AS_WRITTEN);
    assert_eq!(
        redone.diagram().get(assigned_id),
        added.diagram().get(assigned_id)
    );
}

#[test]
fn adding_a_shape_truncates_redo_history_when_called_after_undo() {
    let session = Session::new(Diagram::new());
    let (s1, id1) = session.add(small_box(ORIGIN));
    let s2 = s1.perform(Command::Move {
        id: id1,
        by: Delta { dx: 4, dy: 0 },
    });
    assert_eq!(picture(&s2), FOUR_RIGHT);

    let s_undone = s2.undo();
    assert_eq!(picture(&s_undone), AS_WRITTEN);
    assert!(s_undone.can_redo());

    // Adding a shape while in the middle of history truncates what was ahead
    let (s_branched, id2) = s_undone.add(an_extra_box());
    assert_eq!(id2, id(2));
    assert!(!s_branched.can_redo(), "redo history is truncated");
    assert!(s_branched.can_undo());
    assert_eq!(s_branched.diagram().shape_count(), 2);
}

#[test]
fn performing_command_add_via_session_perform_records_step_and_adds_shape() {
    let session = Session::new(Diagram::new());
    let added = session.perform(Command::Add {
        shape: small_box(ORIGIN),
    });
    assert_eq!(added.diagram().shape_count(), 1);
    assert_eq!(picture(&added), AS_WRITTEN);
    assert!(added.can_undo());

    let undone = added.undo();
    assert_eq!(undone.diagram().shape_count(), 0);
}

/// **Rules 1–4 of the specification**: the figure a step records is the one its command named, and
/// the session answers it in both directions without walking.
///
/// **Every command that names a figure is here, and the awkward one is `Hang`**: what it touches is
/// the connector whose end moves, not the `target` it hangs from. `DetachEndpoint`, `ResetEndpoint`
/// and `RotateLine` need a state to change and are checked from the state they change.
#[test]
fn affected_by_undo_and_redo_name_the_figure_each_step_touched() {
    let fixture = the_fixture();

    for (command, expected) in commands_that_name_their_figure() {
        holds_the_figure(&fixture, &command, expected);
    }

    let line = Diagram::new()
        .add(Shape::Line {
            at: ORIGIN,
            len: 4,
            orientation: Orientation::Horizontal,
            stroke: Stroke::from("light"),
        })
        .0;
    let rotated = Session::new(line).perform(Command::RotateLine { id: id(1) });
    assert_eq!(
        rotated.affected_by_undo(),
        Some(id(1)),
        "`RotateLine` named another figure"
    );

    let hung = Session::new(fixture.clone()).perform(Command::Hang {
        id: id(3),
        end: End::From,
        target: id(1),
        anchor: Anchor::Right,
    });
    let detached = hung.perform(Command::DetachEndpoint {
        id: id(3),
        end: End::From,
    });
    assert_eq!(
        detached.affected_by_undo(),
        Some(id(3)),
        "`DetachEndpoint` named another figure"
    );

    let moved = Session::new(fixture).perform(Command::MoveEndpoint {
        id: id(3),
        end: End::From,
        by: Delta { dx: 1, dy: 0 },
        out: 2,
    });
    let reset = moved.perform(Command::ResetEndpoint {
        id: id(3),
        end: End::From,
    });
    assert_eq!(
        reset.affected_by_undo(),
        Some(id(3)),
        "`ResetEndpoint` named another figure"
    );
}

/// Every command that names the figure it touches, beside the identity it names.
///
/// **A table rather than fourteen cases**, so "every command that names one" is a list a reader can
/// check against the enum rather than an argument made by repetition.
fn commands_that_name_their_figure() -> [(Command, ShapeId); 14] {
    let text = Text::new("hi").expect("\"hi\" holds no control character");

    [
        (
            Command::Move {
                id: id(1),
                by: Delta { dx: 1, dy: 0 },
            },
            id(1),
        ),
        (
            Command::Resize {
                id: id(1),
                by: Delta { dx: 1, dy: 0 },
            },
            id(1),
        ),
        (
            Command::SetStroke {
                id: id(2),
                stroke: Stroke::from("double"),
            },
            id(2),
        ),
        (
            Command::SetText {
                id: id(1),
                text: Some(text),
            },
            id(1),
        ),
        (Command::InvertTerminals { id: id(3) }, id(3)),
        (
            Command::MoveEndpoint {
                id: id(3),
                end: End::From,
                by: Delta { dx: 1, dy: 1 },
                out: 2,
            },
            id(3),
        ),
        (
            Command::SetEndpointTerminal {
                id: id(3),
                end: End::To,
                terminal: Terminal::Arm,
            },
            id(3),
        ),
        (
            Command::SetEndpointLeaving {
                id: id(3),
                end: End::To,
                leaving: Direction::Up,
            },
            id(3),
        ),
        (
            Command::Hang {
                id: id(3),
                end: End::From,
                target: id(1),
                anchor: Anchor::Right,
            },
            id(3),
        ),
        (Command::Forward { id: id(1) }, id(1)),
        (Command::Backward { id: id(3) }, id(3)),
        (Command::ToFront { id: id(1) }, id(1)),
        (Command::ToBack { id: id(2) }, id(2)),
        (Command::Remove { id: id(2) }, id(2)),
    ]
}

/// Carries `command` out over `diagram` and holds that the step it records names `expected`, that
/// nothing is ahead of it, and that walking it back names the same figure in the other direction.
///
/// **Both directions and the empty ends are asserted**, which is rules 1 and 2 together with rule 3:
/// a session recording the first command's identity forever would pass the first read and fail the
/// second, and one recording anything always would fail the empty ones.
fn holds_the_figure(diagram: &Diagram, command: &Command, expected: ShapeId) {
    let session = Session::new(diagram.clone());
    assert_eq!(
        session.affected_by_undo(),
        None,
        "a session with no history named a figure behind it"
    );
    assert_eq!(
        session.affected_by_redo(),
        None,
        "a session with no history named a figure ahead of it"
    );

    let walked = session.perform(command.clone());

    assert_eq!(
        walked.affected_by_undo(),
        Some(expected),
        "{command:?} recorded the wrong figure"
    );
    assert_eq!(
        walked.affected_by_redo(),
        None,
        "{command:?} left a step ahead"
    );

    let given_back = walked.undo();

    assert_eq!(
        given_back.affected_by_undo(),
        None,
        "{command:?} left a second step behind"
    );
    assert_eq!(
        given_back.affected_by_redo(),
        Some(expected),
        "{command:?} lost its figure when it was walked back"
    );
}

/// **Rule 5 of the specification**: the one command that cannot name what it made records the
/// identity the diagram assigned.
///
/// **Both doors record it, and both record the same one**: `Session::add` learns the identity from
/// `Diagram::add` to hand it to the caller, and `Session::perform(Command::Add)` records it from the
/// answer `apply_to` gives. The second `add` is here so that a session recording a constant would
/// not pass.
#[test]
fn the_affected_figure_of_an_add_is_the_one_the_diagram_assigned() {
    let (added, assigned) = Session::new(Diagram::new()).add(small_box(ORIGIN));

    assert_eq!(assigned, id(1), "the diagram assigned another identity");
    assert_eq!(
        added.affected_by_undo(),
        Some(assigned),
        "`add` recorded another figure"
    );

    let performed = Session::new(Diagram::new()).perform(Command::Add {
        shape: small_box(ORIGIN),
    });
    assert_eq!(
        performed.affected_by_undo(),
        Some(assigned),
        "`perform(Add)` recorded another figure than `add`"
    );

    let second = added.add(small_box(Pos { x: 2, y: 0 })).0;
    assert_eq!(
        second.affected_by_undo(),
        Some(id(2)),
        "the second add recorded the first identity"
    );
    assert_eq!(
        second.undo().affected_by_redo(),
        Some(id(2)),
        "walking the second add back lost its figure"
    );
}