logisheets_controller 1.16.1

Core spreadsheet engine for LogiSheets: formula evaluation, dependency tracking, and undo/redo.
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
use crate::conditional_formatting_manager::spec::CfRuleSpec;
use gents_derives::TS;
use logisheets_base::{BlockId, CellId, ColId, EphemeralId, RowId, SheetId, async_func::Task};

/// Marker for payload structs, so [`PayloadsAction::add_payload`] can take
/// them directly.
pub trait Payload: Into<EditPayload> {}

/// `EditAction` represents your update behavior to the workbook.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "edit_action.ts", tag = "type")]
pub enum EditAction {
    /// Step back one undoable transaction (inside an active temp branch,
    /// one step of that branch).
    Undo,
    Redo,
    /// Apply a transaction. Any other action than `Undo`/`Redo` discards an
    /// active temp branch first.
    Payloads(PayloadsAction),
    /// Re-evaluate these cells and their dependents without changing any
    /// input. Not recorded in history.
    Recalc(Vec<RecalcCell>),
}

/// A cell to re-evaluate, by stable ids.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "recalc_cell.ts", rename_all = "camelCase")]
pub struct RecalcCell {
    pub sheet_id: SheetId,
    pub cell_id: CellId,
}

impl EditAction {
    pub fn undo() -> Self {
        Self::Undo
    }

    pub fn redo() -> Self {
        Self::Redo
    }
}

impl From<PayloadsAction> for EditAction {
    fn from(value: PayloadsAction) -> Self {
        EditAction::Payloads(value)
    }
}

/// A `PayloadsAction` contains one or more `EditPayload`.
/// These `EditPayload`s will be withdrawn at the same time if user undo it.
/// And if one of the payload is failed to be executed, this `EditAction` will
/// not do anything at all.
///
/// An `EditPayload` represents an atomic update of a workbook and they will be
/// executed in sequence. That means it is a totally different result between
/// updating a cell at B4 before inserting and after inserting.
#[derive(Debug, Default, Clone, TS)]
#[ts(file_name = "payloads_action.ts")]
pub struct PayloadsAction {
    pub payloads: Vec<EditPayload>,
    /// Record the transaction as one undo step. `false` still applies and
    /// commits it; it just cannot be undone.
    pub undoable: bool,
    /// Build a workbook's opening state rather than edit it: the resulting
    /// status becomes the new history baseline (clearing undo/redo), and the
    /// block-key uniqueness and pivot-conflict guards are skipped so a file
    /// that already violates them still opens. Not for user edits.
    pub init: bool,
}

impl PayloadsAction {
    /// An empty, NON-undoable transaction. Call `set_undoable(true)` for a
    /// user edit.
    pub fn new() -> Self {
        PayloadsAction {
            payloads: vec![],
            undoable: false,
            init: false,
        }
    }

    pub fn set_undoable(mut self, v: bool) -> Self {
        self.undoable = v;
        self
    }

    /// Also clears `undoable`, whichever value `v` has.
    pub fn set_init(mut self, v: bool) -> Self {
        self.init = v;
        self.undoable = false;
        self
    }

    pub fn add_payload<P: Payload>(mut self, payload: P) -> Self {
        self.payloads.push(payload.into());
        self
    }
}

/// `EditPayload` is the basic update unit of the Workbook. Developers can config their own
/// `EditAction` (e.g. setting a button to create a table) to facilitate their users.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "edit_payload.ts", tag = "type")]
pub enum EditPayload {
    // Block
    BlockInput(BlockInput),
    MoveBlock(MoveBlock),
    RemoveBlock(RemoveBlock),
    CreateBlock(CreateBlock),
    ResizeBlock(ResizeBlock),
    ConvertBlock(ConvertBlock),
    CreateLink(CreateLink),
    BindFormSchema(BindFormSchema),
    UpsertFieldFormulas(UpsertFieldFormulas),
    BindRandomSchema(BindRandomSchema),
    UpsertFieldRenderInfo(UpsertFieldRenderInfo),
    MoveBlockLine(MoveBlockLine),
    ReorderBlockLines(ReorderBlockLines),

    // DiyCell
    CreateDiyCell(CreateDiyCell),
    CreateDiyCellById(CreateDiyCellById),
    RemoveDiyCell(RemoveDiyCell),
    RemoveDiyCellById(RemoveDiyCellById),

    // Appendix
    CreateAppendix(CreateAppendix),
    RemoveAppendix(RemoveAppendix),

    // Style
    CellStyleUpdate(CellStyleUpdate),
    EphemeralCellStyleUpdate(EphemeralCellStyleUpdate),
    LineStyleUpdate(LineStyleUpdate),
    BlockStyleUpdate(BlockStyleUpdate),
    BlockLineStyleUpdate(BlockLineStyleUpdate),
    BlockLineNameFieldUpdate(BlockLineNameFieldUpdate),
    SetBlockDescription(SetBlockDescription),
    SetBlockPermissions(SetBlockPermissions),
    SetBlockAnalyzes(SetBlockAnalyzes),
    UpsertEnumSet(UpsertEnumSet),
    RemoveEnumSet(RemoveEnumSet),

    // Defined names (workbook scope)
    DefineName(DefineName),
    RenameName(RenameName),
    RemoveName(RemoveName),

    CellFormatBrush(CellFormatBrush),
    LineFormatBrush(LineFormatBrush),

    CellInput(CellInput),
    EphemeralCellInput(EphemeralCellInput),
    EphemeralCellRemove(EphemeralCellRemove),
    CellClear(CellClear),

    // Cell images (stored as SpreadsheetDrawingML pictures on save).
    SetCellImage(SetCellImage),
    DeleteCellImage(DeleteCellImage),
    MoveChart(MoveChart),
    CreateConditionalFormattingRule(CreateConditionalFormattingRule),
    UpdateConditionalFormattingRule(UpdateConditionalFormattingRule),
    MoveConditionalFormattingRule(MoveConditionalFormattingRule),
    DeleteConditionalFormattingRule(DeleteConditionalFormattingRule),
    DeleteChart(DeleteChart),
    CreateChart(CreateChart),
    UpdateChart(UpdateChart),
    SetColWidth(SetColWidth),
    SetRowHeight(SetRowHeight),
    SetVisible(SetVisible),
    // Merge cells
    MergeCells(MergeCells),
    SplitMergedCells(SplitMergedCells),

    // Comments (threaded + @mentions). See `cell_attachments::comment`.
    AddComment(AddComment),
    EditComment(EditComment),
    DeleteComment(DeleteComment),
    ResolveComment(ResolveComment),
    UpsertPerson(UpsertPerson),

    // Sheet
    SheetRename(SheetRename),
    CreateSheet(CreateSheet),
    DeleteSheet(DeleteSheet),
    SetSheetColor(SetSheetColor),
    SetSheetVisible(SetSheetVisible),
    // Shifting
    InsertCols(InsertCols),
    DeleteCols(DeleteCols),
    InsertRows(InsertRows),
    DeleteRows(DeleteRows),
    InsertColsInBlock(InsertColsInBlock),
    DeleteColsInBlock(DeleteColsInBlock),
    InsertRowsInBlock(InsertRowsInBlock),
    DeleteRowsInBlock(DeleteRowsInBlock),

    // Reproduce
    ReproduceCells(ReproduceCells),

    // Named in-memory checkpoints. Save / delete are workbook methods
    // (they don't touch sheet state). Restore is here because it DOES
    // mutate state — replacing the live status with a previously-saved
    // snapshot — and must go through the undoable-tx pipeline so the
    // user can Ctrl-Z to reverse it.
    RestoreCheckpoint(RestoreCheckpoint),
}

#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "upsert_field_render_info.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct UpsertFieldRenderInfo {
    pub render_id: String,
    pub diy_render: bool,
    pub style_update: StyleUpdateType,
}

/// Replace the controller's live `Status` with a previously-saved
/// snapshot from the `CheckpointManager`. The state-swap is recorded
/// as a normal undoable transaction so the user can Ctrl-Z to reverse
/// it (which restores whatever the live status was right before the
/// restore — not the snapshot).
///
/// Fails loud (`CheckpointNotFound`) if no checkpoint exists for the
/// given label. The redo stack is cleared per standard tx semantics.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "restore_checkpoint.ts", builder, rename_all = "camelCase")]
pub struct RestoreCheckpoint {
    /// Label passed to `Workbook::save_checkpoint` earlier in this
    /// session.
    pub label: String,
}

impl From<RestoreCheckpoint> for EditPayload {
    fn from(value: RestoreCheckpoint) -> Self {
        EditPayload::RestoreCheckpoint(value)
    }
}

#[derive(Debug, Clone, TS)]
/// Insert a new, empty sheet.
#[ts(file_name = "create_sheet.ts", builder, rename_all = "camelCase")]
pub struct CreateSheet {
    /// Tab position of the new sheet, `0..=sheet count`; later sheets shift
    /// right.
    pub idx: usize,
    /// Must not name an existing sheet.
    pub new_name: String,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "delete_sheet.ts", builder, rename_all = "camelCase")]
pub struct DeleteSheet {
    /// The engine accepts deleting any sheet, but a UI host that is still
    /// rendering this sheet must move its view to another sheet first.
    pub idx: usize,
}

#[derive(Debug, Clone, TS)]
/// Set a sheet's tab color.
#[ts(file_name = "set_sheet_color.ts", builder, rename_all = "camelCase")]
pub struct SetSheetColor {
    pub idx: usize,
    /// Stored unvalidated and written verbatim as OOXML `<tabColor rgb>`, so
    /// use 8-digit ARGB hex with no `#` (`"FFFF0000"`).
    pub color: String,
}

#[derive(Debug, Clone, TS)]
/// Hide or show a sheet tab.
///
/// Known gap: the executor currently ignores `visible` and always hides the
/// sheet; there is no payload that unhides one.
#[ts(file_name = "set_sheet_visible.ts", builder, rename_all = "camelCase")]
pub struct SetSheetVisible {
    pub idx: usize,
    pub visible: bool,
}

/// Rename a sheet, found by `old_name` or else by `idx`.
///
/// `old_name` wins when both are set, and an unknown `old_name` is a silent
/// no-op. An out-of-range `idx` is rejected, as is setting neither. Formulas
/// referencing the sheet keep working: they hold its id, not its name.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "sheet_rename.ts", builder, rename_all = "camelCase")]
pub struct SheetRename {
    pub old_name: Option<String>,
    pub idx: Option<usize>,
    pub new_name: String,
}

#[derive(Debug, Clone, TS)]
/// Format painter: copy one cell's style onto every cell of the inclusive
/// rectangle `dst_row_start..=dst_row_end` x `dst_col_start..=dst_col_end`.
///
/// Known gap: the executor resolves the destination on the SOURCE sheet;
/// `dst_sheet_idx` is currently ignored.
#[ts(file_name = "cell_format_brush.ts", builder, rename_all = "camelCase")]
pub struct CellFormatBrush {
    pub src_sheet_idx: usize,
    pub src_row: usize,
    pub src_col: usize,
    pub dst_sheet_idx: usize,
    pub dst_row_start: usize,
    pub dst_col_start: usize,
    pub dst_row_end: usize,
    pub dst_col_end: usize,
}

#[derive(Debug, Clone, TS)]
/// Copy one cell's style onto whole rows (`row == true`) or columns
/// `from..=to` (inclusive). Sets the line style only; existing cells keep
/// their own.
///
/// Known gap: like [`CellFormatBrush`], `dst_sheet_idx` is currently ignored.
#[ts(file_name = "line_format_brush.ts", builder, rename_all = "camelCase")]
pub struct LineFormatBrush {
    pub src_sheet_idx: usize,
    pub src_row: usize,
    pub src_col: usize,
    pub dst_sheet_idx: usize,
    pub row: bool,
    pub from: usize,
    pub to: usize,
}

#[derive(Debug, Clone, TS)]
/// Delete `count` sheet rows starting at `start`, with their cells. For rows
/// inside a block use [`DeleteRowsInBlock`].
#[ts(file_name = "delete_rows.ts", builder, rename_all = "camelCase")]
pub struct DeleteRows {
    pub sheet_idx: usize,
    pub start: usize,
    pub count: usize,
}

#[derive(Debug, Clone, TS)]
/// Insert `count` empty rows so that the first new row sits at index `start`;
/// the row previously at `start` moves down. References shift with the cells.
#[ts(file_name = "insert_rows.ts", builder, rename_all = "camelCase")]
pub struct InsertRows {
    pub sheet_idx: usize,
    pub start: usize,
    pub count: usize,
}

#[derive(Debug, Clone, TS)]
/// Column counterpart of [`DeleteRows`].
#[ts(file_name = "delete_cols.ts", builder, rename_all = "camelCase")]
pub struct DeleteCols {
    pub sheet_idx: usize,
    pub start: usize,
    pub count: usize,
}

#[derive(Debug, Clone, TS)]
/// Column counterpart of [`InsertRows`].
#[ts(file_name = "insert_cols.ts", builder, rename_all = "camelCase")]
pub struct InsertCols {
    pub sheet_idx: usize,
    pub start: usize,
    pub count: usize,
}

/// Place an image inside a cell. The image fills the cell and resizes with it.
/// `data` is the base64-encoded image bytes; `format` is the image format
/// (e.g. `png`, `jpeg`); `image_id` is a stable, workbook-unique identifier
/// chosen by the caller (used to name the media part on save).
#[derive(Debug, Clone, TS)]
#[ts(file_name = "set_cell_image.ts", builder, rename_all = "camelCase")]
pub struct SetCellImage {
    pub sheet_idx: usize,
    pub row: usize,
    pub col: usize,
    pub image_id: String,
    pub format: String,
    pub data: String,
}

/// Remove the image placed in a cell, if any.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "delete_cell_image.ts", builder, rename_all = "camelCase")]
pub struct DeleteCellImage {
    pub sheet_idx: usize,
    pub row: usize,
    pub col: usize,
}

/// Delete a chart from a sheet, identified by `chart_id`.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "delete_chart.ts", builder, rename_all = "camelCase")]
pub struct DeleteChart {
    pub sheet_idx: usize,
    pub chart_id: String,
}

/// Reconfigure an existing chart in place, keeping its anchor. Any field left
/// `None` keeps the chart's current value; an empty string clears a text field
/// (title, axis title, number format).
///
/// `chart_type` is one of `col|bar|line|area|pie|doughnut|scatter|radar|
/// bubble|stock|ofPie|barOfPie|surface|surface3d`; `legend_pos` is
/// `top|bottom|left|right|none`.
#[derive(Debug, Clone, Default, TS)]
#[ts(file_name = "update_chart.ts", builder, rename_all = "camelCase")]
pub struct UpdateChart {
    pub sheet_idx: usize,
    pub chart_id: String,
    pub chart_type: Option<String>,
    pub title: Option<String>,
    pub legend_pos: Option<String>,
    /// Stack the series (bar/column, line, area). Ignored by pie and scatter.
    pub stacked: Option<bool>,
    pub cat_axis_title: Option<String>,
    pub val_axis_title: Option<String>,
    /// Show the value next to each data point.
    pub show_data_labels: Option<bool>,
    /// Also show the category name / series name / percentage in the label.
    pub show_category_labels: Option<bool>,
    pub show_series_labels: Option<bool>,
    pub show_percent_labels: Option<bool>,
    /// Where the label sits: `ctr|inEnd|outEnd|inBase|bestFit`.
    pub data_label_position: Option<String>,
    /// Excel number-format code applied to the value axis and to data labels
    /// (e.g. `#,##0.00`, `0%`). Empty clears it, falling back to the source
    /// cells' own format.
    pub num_fmt: Option<String>,
    /// Replace the category (X) reference, e.g. `Sheet1!$A$2:$A$5`.
    pub categories_ref: Option<String>,
    /// Replace the whole series list. Colors of series that keep their position
    /// are preserved when the new entry does not name one.
    pub series: Option<Vec<CreateChartSeries>>,
    /// Replace the value axis' scale wholesale. Unlike the other fields this
    /// is all-or-nothing: sending it sets every part of the scale, so a `None`
    /// inside means "auto" rather than "keep". That is the only way to clear a
    /// fixed minimum back to automatic.
    pub val_axis_scale: Option<AxisScaleUpdate>,
    /// The same for the category (X) axis.
    pub cat_axis_scale: Option<AxisScaleUpdate>,
    /// Replace how a pie-of-pie / bar-of-pie splits its series. Like the axis
    /// scales this is all-or-nothing rather than a patch.
    pub of_pie_split: Option<OfPieSplitUpdate>,
    /// Bind the chart to a block, or rebind it to different fields. The series
    /// then come from the block and `series`/`categories_ref` are ignored.
    ///
    /// To unbind, state `series` instead: naming fixed ranges is exactly the
    /// statement that the chart no longer tracks a block.
    pub block_source: Option<ChartBlockSource>,
}

/// The division between an of-pie chart's two plots.
#[derive(Debug, Clone, Default, TS)]
#[ts(
    file_name = "of_pie_split_update.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct OfPieSplitUpdate {
    /// `auto | cust | percent | pos | val`. Anything else is treated as `auto`.
    pub by: Option<String>,
    /// Read according to `by`: a count of trailing points for `pos`, a
    /// threshold for `val`, a percentage for `percent`.
    pub pos: Option<f64>,
    /// The second plot's size, as a percentage of the first (Excel: 5..=200).
    pub second_size: Option<f64>,
}

/// An axis' scale. Every field `None`/`false` is a fully automatic axis, which
/// is Excel's default.
#[derive(Debug, Clone, Default, TS)]
#[ts(file_name = "axis_scale_update.ts", builder, rename_all = "camelCase")]
pub struct AxisScaleUpdate {
    pub min: Option<f64>,
    pub max: Option<f64>,
    /// Log scale base (Excel allows 2..=1000). `None` is a linear axis.
    pub log_base: Option<f64>,
    /// Draw the axis in the opposite direction.
    pub reversed: bool,
    /// Spacing between major ticks / gridlines. `None` is automatic.
    pub major_unit: Option<f64>,
    pub minor_unit: Option<f64>,
}

/// One series for [`CreateChart`] / [`UpdateChart`]: an optional name, the
/// value reference formula (e.g. `Sheet1!$B$2:$E$2`) and an optional explicit
/// fill color as an RGB hex string (`"4472C4"`).
#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "create_chart_series.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct CreateChartSeries {
    pub name: Option<String>,
    pub value_ref: String,
    pub color: Option<String>,
    /// Bubble sizes for this series (`Sheet1!$D$2:$D$6`). Only a bubble chart
    /// reads it; other kinds keep it in the model but never draw it.
    pub size_ref: Option<String>,
    /// Draw this one series as a different kind — `col|bar|line|area` — which
    /// is how a combo chart is expressed. `None` follows the chart's own type.
    /// An override the chart cannot combine with is ignored.
    pub series_type: Option<String>,
}

/// Create a new chart anchored at `from`..`to`. `chart_type` is one of
/// `col|bar|line|area|pie|doughnut|scatter|radar|bubble|stock|ofPie|barOfPie|
/// surface|surface3d`. `chart_id` must be workbook-unique
/// (the caller generates it; it also names the chart part). Series values are
/// read live from the referenced ranges, so no cached values are needed here.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "create_chart.ts", builder, rename_all = "camelCase")]
pub struct CreateChart {
    pub sheet_idx: usize,
    pub chart_id: String,
    pub chart_type: String,
    pub from_row: usize,
    pub from_col: usize,
    pub from_col_off: i64,
    pub from_row_off: i64,
    pub to_row: usize,
    pub to_col: usize,
    pub to_col_off: i64,
    pub to_row_off: i64,
    pub title: Option<String>,
    pub categories_ref: Option<String>,
    pub series: Vec<CreateChartSeries>,
    /// Plot a block instead of fixed ranges. When set, `series` and
    /// `categories_ref` are ignored — the block says where its fields are, and
    /// the chart re-reads that on every render and every save, so it follows
    /// the block as records are added or columns move.
    pub block_source: Option<ChartBlockSource>,
}

/// Binds a chart to a block: which block, which of its fields to plot, and
/// which field labels the categories. Fields are named, the identity
/// `#FIELD("qty")` formulas use — a renamed field breaks the link, a moved one
/// does not. A block with a `random` schema has no field axis and cannot be
/// charted this way.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "chart_block_source.ts", builder, rename_all = "camelCase")]
pub struct ChartBlockSource {
    pub block_id: usize,
    pub category_field: Option<String>,
    pub value_fields: Vec<String>,
}

/// Add a conditional-formatting rule over `start`..`end` (corners may be given
/// in any order). The range is anchored on cell ids, so it tracks later row and
/// column edits; the rule takes the next free `priority`, applying after the
/// ones already on the sheet.
#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "create_conditional_formatting_rule.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct CreateConditionalFormattingRule {
    pub sheet_idx: usize,
    pub start_row: usize,
    pub start_col: usize,
    pub end_row: usize,
    pub end_col: usize,
    pub rule: CfRuleSpec,
}

/// Replace a rule's condition and format, keeping its id, its range and its
/// `priority` — so editing a rule never reorders it.
#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "update_conditional_formatting_rule.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct UpdateConditionalFormattingRule {
    pub sheet_idx: usize,
    /// From `CellInfo::conditional_format`, or `get_conditional_formatting_rules`.
    /// Session-scoped: ids are re-minted on load and must not be persisted.
    pub rule_id: u32,
    pub rule: CfRuleSpec,
}

/// Re-target an existing rule at a different range, keeping everything else.
#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "move_conditional_formatting_rule.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct MoveConditionalFormattingRule {
    pub sheet_idx: usize,
    pub rule_id: u32,
    pub start_row: usize,
    pub start_col: usize,
    pub end_row: usize,
    pub end_col: usize,
}

/// Remove a rule. The `<conditionalFormatting>` element is dropped with it when
/// it held no other rules.
#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "delete_conditional_formatting_rule.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct DeleteConditionalFormattingRule {
    pub sheet_idx: usize,
    pub rule_id: u32,
}

#[derive(Debug, Clone, TS)]
/// Move (and/or resize) a chart to a new anchor. The chart is identified by
/// `chart_id` on the given sheet. `from`/`to` are the new top-left and
/// bottom-right anchor corners, each a cell position plus an EMU offset into
/// that cell (1px = 9525 EMU at 96 DPI). Anchoring to cells (not pixels) is how
/// the chart shifts with row/column edits.
#[ts(file_name = "move_chart.ts", builder, rename_all = "camelCase")]
pub struct MoveChart {
    pub sheet_idx: usize,
    pub chart_id: String,
    pub from_row: usize,
    pub from_col: usize,
    pub from_col_off: i64,
    pub from_row_off: i64,
    pub to_row: usize,
    pub to_col: usize,
    pub to_col_off: i64,
    pub to_row_off: i64,
}

/// Take the `content` as input to the cell. The type of the `content` can be referred automatically.
///
/// A formula (`content` starting with `=`) must evaluate to one scalar: the
/// engine has no dynamic arrays, so nothing spills into neighbouring cells and
/// array criteria are not evaluated. Lay out helper columns instead.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "cell_input.ts", builder, rename_all = "camelCase")]
pub struct CellInput {
    pub sheet_idx: usize,
    pub row: usize,
    pub col: usize,
    pub content: String,
}

#[derive(Debug, Clone, TS)]
/// [`CellInput`] for an ephemeral cell (see `CellId::EphemeralCell`): the
/// cell is created on first write, can hold a formula that reads the sheet,
/// and is never saved. `sheet_idx` is the sheet unqualified references in the
/// formula resolve against.
#[ts(
    file_name = "ephemeral_cell_input.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct EphemeralCellInput {
    pub sheet_idx: usize,
    pub id: EphemeralId,
    pub content: String,
}

/// Remove an ephemeral cell previously written via `EphemeralCellInput`.
/// Frees the slot in the container and detaches the cell from the
/// dependency graph so it no longer participates in recompute. Safe to
/// call on an id that was never written — the operation is a no-op.
#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "ephemeral_cell_remove.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct EphemeralCellRemove {
    pub sheet_idx: usize,
    pub id: EphemeralId,
}

#[derive(Debug, Clone, TS)]
/// Empty a cell: its value and formula go, and dependents recalculate.
///
/// Use this, not a [`CellInput`] with empty `content`, to blank a cell. A
/// cell whose value a block field template computes is left untouched.
#[ts(file_name = "cell_clear.ts", builder, rename_all = "camelCase")]
pub struct CellClear {
    pub sheet_idx: usize,
    pub row: usize,
    pub col: usize,
}

/// Create a new block.
///
/// Note that the block id is assigned by you and must be unused on the sheet
/// (see `Workbook::get_available_block_id`); an id already in use rejects the
/// transaction. `master_row`/`master_col` is the top-left corner and must be
/// an ordinary cell, not inside another block.
///
/// `owner`, `modify_policy`, `permissions` and `description` are metadata the
/// host uses to gate write access at runtime — ask
/// `Workbook::may_modify_block` rather than reading them apart. The engine
/// does not enforce them itself: a payload carries no trace of who prompted
/// it, so only the host knows whether an edit came from a person or a craft.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "create_block.ts", builder, rename_all = "camelCase")]
pub struct CreateBlock {
    pub sheet_idx: usize,
    pub id: usize,
    pub master_row: usize,
    pub master_col: usize,
    pub row_cnt: usize,
    pub col_cnt: usize,
    pub owner: Option<String>,
    pub modify_policy: Option<ModifyPolicy>,
    /// Per-operation overrides of `modify_policy`. Omitted, the single policy
    /// governs every operation.
    pub permissions: Option<BlockPermissions>,
    /// What the block is for, in prose, for an AI or a person reading the
    /// sheet later. A craft creating a block should say what it is for here.
    pub description: Option<String>,
    /// Which block this one analyses, when it is an analysis block. Set here
    /// rather than in a follow-up payload so the block is never briefly a
    /// stray table — the whole creation lands as one transaction, and a reader
    /// between two payloads never sees a total row it would mistake for a
    /// record. See `design/block-analysis.md`.
    pub analyzes: Option<usize>,
    /// When the block is a PIVOT, the recipe its cells and its shape derive
    /// from. Requires `analyzes`: a pivot with no source is refused, because
    /// every cell of it would aggregate nothing. See `design/block-pivot.md`.
    pub pivot: Option<crate::block_manager::schema_manager::field_type::PivotSpecParts>,
}

/// Rewrite a block's prose description, or clear it with an empty string.
///
/// Governed by `BlockOp::ModifyDescription`, which the host is expected to
/// check first: a description is how the block explains itself to whoever
/// reads the sheet next, so an owner may well want it left alone.
#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "set_block_description.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct SetBlockDescription {
    pub sheet_idx: usize,
    pub block_id: usize,
    pub description: String,
}

/// Declare (or clear) a block's whole analysis declaration: what it analyses,
/// and — when it is a pivot — the recipe.
///
/// Both at once, deliberately. A pivot without a source is meaningless, so two
/// payloads that could disagree would only create states to defend against.
/// Sending this always states both: omitting `pivot` makes the block a plain
/// analysis (a total row), and omitting `analyzes` makes it an ordinary block.
///
/// Governed by `BlockOp::ModifySchema`: what a block analyses is as much a
/// structural fact about it as its fields are, and pointing an existing block
/// at a different source changes what every one of its cells computes.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "set_block_analyzes.ts", builder, rename_all = "camelCase")]
pub struct SetBlockAnalyzes {
    pub sheet_idx: usize,
    pub block_id: usize,
    /// The block being analysed, or `None` to make this an ordinary block
    /// again. Must be on the same sheet, and must not be the block itself.
    pub analyzes: Option<usize>,
    /// The pivot recipe, or `None` for a plain analysis block. Requires
    /// `analyzes`.
    pub pivot: Option<crate::block_manager::schema_manager::field_type::PivotSpecParts>,
}

impl From<SetBlockAnalyzes> for EditPayload {
    fn from(value: SetBlockAnalyzes) -> Self {
        EditPayload::SetBlockAnalyzes(value)
    }
}

/// Replace a block's per-operation policies, and optionally its default one.
///
/// All-or-nothing on `permissions`: what is sent becomes the whole set, so an
/// operation left `None` in the payload goes back to deferring to the default
/// policy. That is the only way to clear an override, and it means the caller
/// always states the block's full stance rather than patching it blind.
#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "set_block_permissions.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct SetBlockPermissions {
    pub sheet_idx: usize,
    pub block_id: usize,
    pub permissions: BlockPermissions,
    /// `None` keeps the block's current default policy.
    pub modify_policy: Option<ModifyPolicy>,
}

/// Controls who is allowed to write to a block at the frontend runtime layer.
/// Reads are always allowed regardless of policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, TS)]
#[ts(file_name = "modify_policy.ts", tag = "type")]
pub enum ModifyPolicy {
    /// Anyone (any craft or the user) can write.
    All,
    /// Only the owner can write.
    OwnerOnly,
    /// The owner and the user can write; other crafts cannot.
    OwnerAndUser,
}

impl Default for ModifyPolicy {
    fn default() -> Self {
        ModifyPolicy::All
    }
}

impl ModifyPolicy {
    /// String form used for .xlsx persistence. Mirrors the camelCase wire
    /// format produced by the TypeScript binding.
    pub fn as_wire_str(&self) -> &'static str {
        match self {
            ModifyPolicy::All => "all",
            ModifyPolicy::OwnerOnly => "ownerOnly",
            ModifyPolicy::OwnerAndUser => "ownerAndUser",
        }
    }

    /// Parse the persisted string form. Unknown values fall back to `All`.
    pub fn from_wire_str(s: &str) -> Self {
        match s {
            "ownerOnly" => ModifyPolicy::OwnerOnly,
            "ownerAndUser" => ModifyPolicy::OwnerAndUser,
            _ => ModifyPolicy::All,
        }
    }
}

/// The operations a block's permissions can speak about separately.
///
/// One policy for the whole block is too blunt for the case this exists to
/// serve: a block a craft or Watson built usually wants the user to keep
/// *typing into it* while refusing to let them pull rows out from under it or
/// re-point its schema, which would take the block out of the owner's control
/// for good.
#[derive(Debug, Clone, Copy, PartialEq, Eq, TS)]
#[ts(file_name = "block_op.ts", tag = "type")]
pub enum BlockOp {
    /// Insert or delete rows/columns inside the block.
    InsertDeleteLines,
    /// Delete the whole block. Kept apart from the rest because it is the one
    /// operation there is no recovering from by editing: the records, the
    /// schema and this policy itself all go at once.
    RemoveBlock,
    /// Bind a different schema, or change the fields of the current one.
    ModifySchema,
    /// Write a value into one of the block's cells.
    CellInput,
    /// Reorder the records by one of the fields.
    SortByField,
    /// Rewrite the prose description.
    ModifyDescription,
    /// Write a value into a block cell that its field's validation rule
    /// rejects.
    ///
    /// Distinct from `CellInput` because the two answer different questions:
    /// `CellInput` is "may this actor write here at all", this one is "may
    /// this actor write something the schema says is wrong". A craft that
    /// maintains a table often has to seed a row it knows is incomplete —
    /// a required field it fills in on the next round — while a person typing
    /// into the same block should be held to the rule. Left at `All` (the
    /// default), a violating write lands and is flagged, which is what every
    /// block did before this op existed.
    OverrideValidation,
}

impl BlockOp {
    /// Which operation a payload counts as, keyed by the payload's wire type
    /// name (`EditPayload`'s `type` tag). `None` when the payload is not
    /// something a block can single out.
    ///
    /// The mapping belongs to the engine because the engine defines the
    /// operations. Every host that enforces a policy needs it — the app, the
    /// craft runtime, Watson — and each keeping its own table is how the same
    /// payload comes to be governed differently in different hosts. A payload
    /// this returns `None` for is not unguarded: the caller falls back to its
    /// owner check, which is what the app already did.
    pub fn for_payload_type(payload_type: &str) -> Option<BlockOp> {
        BLOCK_OP_BY_PAYLOAD
            .iter()
            .find(|(name, _)| *name == payload_type)
            .map(|(_, op)| *op)
    }

    /// Every operation, so a caller can render or check the whole set without
    /// having to keep its own list in step with this one.
    pub const ALL: [BlockOp; 7] = [
        BlockOp::InsertDeleteLines,
        BlockOp::RemoveBlock,
        BlockOp::ModifySchema,
        BlockOp::CellInput,
        BlockOp::SortByField,
        BlockOp::ModifyDescription,
        BlockOp::OverrideValidation,
    ];

    /// Attribute name used for .xlsx persistence.
    pub fn as_wire_str(&self) -> &'static str {
        match self {
            BlockOp::InsertDeleteLines => "insertDeleteLines",
            BlockOp::RemoveBlock => "removeBlock",
            BlockOp::ModifySchema => "modifySchema",
            BlockOp::CellInput => "cellInput",
            BlockOp::SortByField => "sortByField",
            BlockOp::ModifyDescription => "modifyDescription",
            BlockOp::OverrideValidation => "overrideValidation",
        }
    }
}

/// Which [`BlockOp`] each payload counts as, by wire type name.
///
/// One table, so the answer cannot differ between the engine and a host. Names
/// are `EditPayload`'s `type` tag — the camelCase form of the variant.
pub const BLOCK_OP_BY_PAYLOAD: &[(&str, BlockOp)] = &[
    ("insertRowsInBlock", BlockOp::InsertDeleteLines),
    ("deleteRowsInBlock", BlockOp::InsertDeleteLines),
    ("insertColsInBlock", BlockOp::InsertDeleteLines),
    ("deleteColsInBlock", BlockOp::InsertDeleteLines),
    ("resizeBlock", BlockOp::InsertDeleteLines),
    ("removeBlock", BlockOp::RemoveBlock),
    ("bindFormSchema", BlockOp::ModifySchema),
    ("bindRandomSchema", BlockOp::ModifySchema),
    ("upsertFieldFormulas", BlockOp::ModifySchema),
    ("upsertFieldRenderInfo", BlockOp::ModifySchema),
    ("blockLineNameFieldUpdate", BlockOp::ModifySchema),
    // Handing a block's policies over is itself a schema-level change —
    // otherwise anyone could unlock a block simply by asking to.
    ("setBlockPermissions", BlockOp::ModifySchema),
    ("setBlockAnalyzes", BlockOp::ModifySchema),
    ("cellInput", BlockOp::CellInput),
    ("blockInput", BlockOp::CellInput),
    ("reorderBlockLines", BlockOp::SortByField),
    ("moveBlockLine", BlockOp::SortByField),
    ("setBlockDescription", BlockOp::ModifyDescription),
];

/// Per-operation overrides of a block's [`ModifyPolicy`].
///
/// `None` on an operation defers to the block's own `modify_policy`, so a
/// block that says nothing here behaves exactly as it did when one policy
/// governed everything — which is what every block in a file written before
/// this existed says.
#[derive(Debug, Clone, Default, PartialEq, Eq, TS)]
#[ts(file_name = "block_permissions.ts", builder, rename_all = "camelCase")]
pub struct BlockPermissions {
    pub insert_delete_lines: Option<ModifyPolicy>,
    pub remove_block: Option<ModifyPolicy>,
    pub modify_schema: Option<ModifyPolicy>,
    pub cell_input: Option<ModifyPolicy>,
    pub sort_by_field: Option<ModifyPolicy>,
    pub modify_description: Option<ModifyPolicy>,
    pub override_validation: Option<ModifyPolicy>,
}

impl BlockPermissions {
    /// The policy for one operation, or `fallback` when this block does not
    /// single that operation out.
    pub fn policy_for(&self, op: BlockOp, fallback: ModifyPolicy) -> ModifyPolicy {
        self.explicit(op).unwrap_or(fallback)
    }

    pub fn set(&mut self, op: BlockOp, policy: Option<ModifyPolicy>) {
        match op {
            BlockOp::InsertDeleteLines => self.insert_delete_lines = policy,
            BlockOp::RemoveBlock => self.remove_block = policy,
            BlockOp::ModifySchema => self.modify_schema = policy,
            BlockOp::CellInput => self.cell_input = policy,
            BlockOp::SortByField => self.sort_by_field = policy,
            BlockOp::ModifyDescription => self.modify_description = policy,
            BlockOp::OverrideValidation => self.override_validation = policy,
        }
    }

    /// `true` when nothing is singled out, i.e. the block is governed by its
    /// single policy alone. Lets the writer omit the attributes entirely.
    pub fn is_empty(&self) -> bool {
        BlockOp::ALL.iter().all(|op| self.explicit(*op).is_none())
    }

    /// The policy stated for `op`, if this block states one.
    pub fn explicit(&self, op: BlockOp) -> Option<ModifyPolicy> {
        match op {
            BlockOp::InsertDeleteLines => self.insert_delete_lines,
            BlockOp::RemoveBlock => self.remove_block,
            BlockOp::ModifySchema => self.modify_schema,
            BlockOp::CellInput => self.cell_input,
            BlockOp::SortByField => self.sort_by_field,
            BlockOp::ModifyDescription => self.modify_description,
            BlockOp::OverrideValidation => self.override_validation,
        }
    }
}

/// Who is asking to change a block.
///
/// The engine cannot tell these apart on its own — every payload arrives from
/// the host process, whoever prompted it — so this is what the host states
/// when it asks whether an operation is allowed. Keeping the *decision* here
/// rather than in each host means the browser, node, the desktop app and the
/// craft runtime cannot drift apart on what a policy means.
#[derive(Debug, Clone, PartialEq, Eq, TS)]
#[ts(file_name = "block_actor.ts", tag = "type")]
pub enum BlockActor {
    /// A person editing the sheet.
    User,
    /// A craft, named by its craft id. Watson counts as one.
    Craft(String),
}

impl ModifyPolicy {
    /// Whether `actor` may write to a block owned by `owner` under this policy.
    ///
    /// A block with no owner has nobody to privilege, so `OwnerOnly` on it
    /// would lock everyone out including whoever set it; it is read as `All`
    /// instead.
    pub fn allows(&self, actor: &BlockActor, owner: &str) -> bool {
        match self {
            ModifyPolicy::All => true,
            _ if owner.is_empty() => true,
            ModifyPolicy::OwnerOnly => matches!(actor, BlockActor::Craft(id) if id == owner),
            ModifyPolicy::OwnerAndUser => match actor {
                BlockActor::User => true,
                BlockActor::Craft(id) => id == owner,
            },
        }
    }
}

/// Read-only view of a block's frontend-runtime write policy. Returned by
/// `Workbook::get_block_modify_info` so the JS validate hook can decide
/// whether a caller is allowed to write to a given block.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "block_modify_info.ts", rename_all = "camelCase")]
pub struct BlockModifyInfo {
    pub owner: String,
    /// The block's default policy — what an operation absent from
    /// `permissions` falls back to.
    pub modify_policy: ModifyPolicy,
    pub permissions: BlockPermissions,
    pub description: String,
}

#[derive(Debug, Clone, TS)]
/// Change a block's record/field counts. `None` keeps that dimension.
#[ts(file_name = "resize_block.ts", builder, rename_all = "camelCase")]
pub struct ResizeBlock {
    pub sheet_idx: usize,
    pub id: usize,
    pub new_row_cnt: Option<usize>,
    pub new_col_cnt: Option<usize>,
}

/// Convert a cell range to a block.
///
/// It is similar to `create_block`, but it will keep the old cells and formulas.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "convert_block.ts", builder, rename_all = "camelCase")]
pub struct ConvertBlock {
    pub sheet_idx: usize,
    pub id: usize,
    pub master_row: usize,
    pub master_col: usize,
    pub row_cnt: usize,
    pub col_cnt: usize,
}

/// Link a source cell range to an existing block, so references to the source
/// (e.g. `A1:A10`) transparently resolve to the block's cells. The source cells
/// are left untouched (a facade); the block is the real, growable backing store.
/// The source's column count must equal the block's column count.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "create_link.ts", builder, rename_all = "camelCase")]
pub struct CreateLink {
    /// Sheet holding the SOURCE range (the facade the user references).
    pub sheet_idx: usize,
    /// Top-left of the source range.
    pub master_row: usize,
    pub master_col: usize,
    /// Source range extent. `col_cnt` must match the target block's columns.
    pub row_cnt: usize,
    pub col_cnt: usize,
    /// The existing block that backs the source range.
    pub block_id: usize,
    /// Sheet holding the backing BLOCK. `None` = same sheet as the source; set it
    /// for a cross-sheet link (e.g. a hidden block backing a visible-sheet range).
    pub block_sheet_idx: Option<usize>,
}

#[derive(Debug, Clone, TS)]
/// Mark a block cell as host-rendered ("DIY"): the engine assigns it a
/// `DiyCellId` and the host draws it. The cell must be inside a block.
#[ts(file_name = "create_diy_cell.ts", builder, rename_all = "camelCase")]
pub struct CreateDiyCell {
    pub sheet_idx: usize,
    pub row: usize,
    pub col: usize,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "remove_diy_cell.ts", builder, rename_all = "camelCase")]
pub struct RemoveDiyCell {
    pub sheet_idx: usize,
    pub row: usize,
    pub col: usize,
}

#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "create_diy_cell_by_id.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct CreateDiyCellById {
    pub sheet_id: SheetId,
    pub block_id: BlockId,
    pub row_idx: usize,
    pub col_idx: usize,
}

#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "remove_diy_cell_by_id.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct RemoveDiyCellById {
    pub sheet_id: SheetId,
    pub block_id: BlockId,
    pub row_idx: usize,
    pub col_idx: usize,
}

#[derive(Debug, Clone, TS)]
/// Attach an opaque craft-owned record to a block cell. `row_idx`/`col_idx`
/// are 0-based within the block. Give `sheet_idx` or `sheet_id`; `sheet_idx`
/// wins when both are set, and neither is rejected.
#[ts(file_name = "create_appendix.ts", builder, rename_all = "camelCase")]
pub struct CreateAppendix {
    pub sheet_id: Option<SheetId>,
    pub sheet_idx: Option<usize>,
    pub block_id: BlockId,
    pub row_idx: usize,
    pub col_idx: usize,
    pub craft_id: String,
    pub tag: u8,
    pub content: String,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "remove_appendix.ts", builder, rename_all = "camelCase")]
pub struct RemoveAppendix {
    pub sheet_id: Option<SheetId>,
    pub sheet_idx: Option<usize>,
    pub block_id: BlockId,
    pub row_idx: usize,
    pub col_idx: usize,
}

#[derive(Debug, Clone, TS)]
/// Set a custom row height, in points (Excel's unit; the default is 15).
#[ts(file_name = "set_row_height.ts", builder, rename_all = "camelCase")]
pub struct SetRowHeight {
    pub sheet_idx: usize,
    pub row: usize,
    pub height: f64,
}

#[derive(Debug, Clone, TS)]
/// Set a custom column width, in Excel character-width units (the default is
/// 8.43), not pixels.
#[ts(file_name = "set_col_width.ts", builder, rename_all = "camelCase")]
pub struct SetColWidth {
    pub sheet_idx: usize,
    pub col: usize,
    pub width: f64,
}

#[derive(Debug, Clone, TS)]
/// Move a block so its top-left corner lands at the new sheet position. Its
/// cells keep their `BlockCellId`s, so formulas follow it.
#[ts(file_name = "move_block.ts", builder, rename_all = "camelCase")]
pub struct MoveBlock {
    pub sheet_idx: usize,
    pub id: usize,
    pub new_master_row: usize,
    pub new_master_col: usize,
}

#[derive(Debug, Clone, TS)]
/// Delete a block with its cells and schema. Analysis blocks that analyse it
/// are removed in the same transaction.
#[ts(file_name = "remove_block.ts", builder, rename_all = "camelCase")]
pub struct RemoveBlock {
    pub sheet_idx: usize,
    pub id: usize,
}

#[derive(Debug, Clone, TS)]
/// [`CellInput`] addressed inside a block: `row`/`col` are 0-based offsets
/// from the block's top-left. Input to a cell whose field has a value
/// template is dropped; the template computes it.
#[ts(file_name = "block_input.ts", builder, rename_all = "camelCase")]
pub struct BlockInput {
    pub sheet_idx: usize,
    pub block_id: usize,
    pub row: usize,
    pub col: usize,
    pub input: String,
}

impl From<BlockInput> for EditPayload {
    fn from(value: BlockInput) -> Self {
        EditPayload::BlockInput(value)
    }
}

impl From<UpsertFieldRenderInfo> for EditPayload {
    fn from(value: UpsertFieldRenderInfo) -> Self {
        EditPayload::UpsertFieldRenderInfo(value)
    }
}

#[derive(Debug, Clone, TS)]
/// Move one block row (`is_row`) or column from position `from` to `to`
/// (0-based within the block, both `< len`), shifting the lines between.
#[ts(file_name = "move_block_line.ts", builder, rename_all = "camelCase")]
pub struct MoveBlockLine {
    pub sheet_idx: usize,
    pub block_id: usize,
    pub from: usize,
    pub to: usize,
    pub is_row: bool,
}

impl From<MoveBlockLine> for EditPayload {
    fn from(value: MoveBlockLine) -> Self {
        EditPayload::MoveBlockLine(value)
    }
}

#[derive(Debug, Clone, TS)]
/// Permute a block's rows (`is_row`) or columns in one step:
/// `new_order[i]` is the CURRENT index of the line that ends up at position
/// `i`. Its length must equal the line count. Lines carry their cells, so
/// formulas follow them.
///
/// Only length and range are checked, not that `new_order` is a
/// permutation: a repeated index duplicates one line's id and drops
/// another's.
#[ts(file_name = "reorder_block_lines.ts", rename_all = "camelCase")]
pub struct ReorderBlockLines {
    pub sheet_idx: usize,
    pub block_id: usize,
    pub is_row: bool,
    pub new_order: Vec<usize>,
}

impl From<ReorderBlockLines> for EditPayload {
    fn from(value: ReorderBlockLines) -> Self {
        EditPayload::ReorderBlockLines(value)
    }
}

/// One field of a form schema: its identity, the three rule templates that
/// guard it, and its declaration.
///
/// This replaced five positionally-aligned `Vec`s on [`BindFormSchema`]
/// (`fields` / `render_ids` / `field_formulas` / `validation_formulas` /
/// `editability_formulas`), each with its own "an empty vec means all-None"
/// convention. Adding the declaration would have made it ten, so the shape had
/// to go before the declaration could arrive.
///
/// Everything but `name` and `render_id` is optional; an omitted entry means
/// "nobody said", not "clear it".
#[derive(Debug, Clone, TS)]
#[ts(file_name = "schema_field_spec.ts", builder, rename_all = "camelCase")]
pub struct SchemaFieldSpec {
    pub name: String,
    /// Generated by the host. Ties the field to its render behaviour
    /// (`FieldRenderManager`) and, for now, to the host's own field metadata.
    pub render_id: String,
    /// Template making the field engine-computed. Uses `#FIELD("name")` for a
    /// sibling cell in the same record and `#KEY` for the record's key. When
    /// set, user writes to the field are dropped — the formula is the
    /// constraint.
    pub value_formula: Option<String>,
    /// Boolean template evaluated per record. FALSE raises a
    /// `ShadowKind::Validation` warning; the value still commits. Also accepts
    /// `#PLACEHOLDER` for the cell itself.
    pub validation_formula: Option<String>,
    /// Boolean template evaluated per record. FALSE installs a
    /// `ShadowKind::UserEditable` lock the host permission layer reads.
    pub editability_formula: Option<String>,
    /// What kind of value belongs here. Omitted reads as unspecified.
    pub field_type: Option<crate::block_manager::schema_manager::field_type::FieldTypeParts>,
    /// What the field means, in prose, for whoever reads the block next.
    pub description: Option<String>,
    /// Every record must carry a value here. Omitted reads as false.
    pub required: Option<bool>,
    /// No two records may carry the same value here. Omitted reads as false.
    pub unique: Option<bool>,
    /// What a newly-added record starts with.
    pub default_value: Option<String>,
    /// Who may write to this field's cells: `inherit` (or omitted) |
    /// `ownerOnly` | `anyone`. A declaration the host decides with — the engine
    /// does not know who is writing. Omitted inherits the block's own rules.
    pub write_policy: Option<String>,
    /// When the block analyses another one: how this field aggregates it.
    /// `SUM` | `COUNT` | `AVERAGE` | `MIN` | `MAX`, over `agg_field` of the
    /// analysed block. Both are needed — one without the other is not a
    /// declaration anybody made — and both omitted is an ordinary field.
    ///
    /// The value formula is generated from this; do not also send one.
    pub agg_func: Option<String>,
    pub agg_field: Option<String>,
    /// When the block is a PIVOT and this column is hand-declared rather than
    /// derived from the column dimension's values.
    ///
    /// `pivot_col_value` is the value it filters on; `*` means EVERY value,
    /// which is a row total. `pivot_measure` / `pivot_func` override the
    /// block's recipe for this column alone, which is how a pivot carries a
    /// second measure. All omitted is an ordinary derived column — the
    /// field's own name is the value — and that is every column of a plain
    /// cross-tab. See `design/block-pivot.md` §9.
    pub pivot_col_value: Option<String>,
    pub pivot_measure: Option<String>,
    pub pivot_func: Option<String>,
}

/// One option of an enum set.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "enum_variant_spec.ts", builder, rename_all = "camelCase")]
pub struct EnumVariantSpec {
    /// What the cell stores.
    pub id: String,
    /// What a reader sees. Omit when it is the same as the id — the shape a set
    /// inferred from a column's distinct values takes.
    pub label: Option<String>,
}

/// Create or replace one of the workbook's enum sets: the option list an
/// `enum` / `multiSelect` field draws from.
///
/// Replaces rather than merges. A set is the complete list of what is allowed,
/// so a caller sending four variants means four — and removing an option has to
/// be expressible.
///
/// Ids and labels only. A variant's colour is presentation and stays in the
/// host, keyed by variant id; the engine needs the options in order to judge a
/// value and needs nothing else.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "upsert_enum_set.ts", builder, rename_all = "camelCase")]
pub struct UpsertEnumSet {
    pub id: String,
    /// Human-readable name. Omit for a set nobody named.
    pub name: Option<String>,
    /// Refused when empty: a set with no options allows nothing, which would
    /// light up every cell in every field that uses it.
    pub variants: Vec<EnumVariantSpec>,
}

impl From<UpsertEnumSet> for EditPayload {
    fn from(value: UpsertEnumSet) -> Self {
        EditPayload::UpsertEnumSet(value)
    }
}

/// Drop an enum set. Fields still declaring it keep the declaration; their
/// membership rule then has no options to check against, which surfaces as a
/// violation rather than as silent acceptance.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "remove_enum_set.ts", builder, rename_all = "camelCase")]
pub struct RemoveEnumSet {
    pub id: String,
}

impl From<RemoveEnumSet> for EditPayload {
    fn from(value: RemoveEnumSet) -> Self {
        EditPayload::RemoveEnumSet(value)
    }
}

/// Create or replace a workbook-scoped defined name — `TaxRate` → `0.08`,
/// `Sales` → `Sheet1!$B$2:$B$100`.
///
/// `formula` is what the name refers to, written like a cell formula (the
/// leading `=` is optional). A reference without a sheet prefix is read against
/// `sheet_idx`. References are stored by cell id, so inserting or deleting rows
/// moves the name's range the way it moves any formula's.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "define_name.ts", builder, rename_all = "camelCase")]
pub struct DefineName {
    pub name: String,
    pub formula: String,
    pub sheet_idx: usize,
}

impl From<DefineName> for EditPayload {
    fn from(value: DefineName) -> Self {
        EditPayload::DefineName(value)
    }
}

/// Rename a defined name. Formulas that use it follow the rename — they hold
/// the name's id, not its spelling.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "rename_name.ts", builder, rename_all = "camelCase")]
pub struct RenameName {
    pub old_name: String,
    pub new_name: String,
}

impl From<RenameName> for EditPayload {
    fn from(value: RenameName) -> Self {
        EditPayload::RenameName(value)
    }
}

/// Delete a defined name. Formulas that still use it evaluate to `#NAME?`,
/// and come back to life if the name is defined again.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "remove_name.ts", builder, rename_all = "camelCase")]
pub struct RemoveName {
    pub name: String,
}

impl From<RemoveName> for EditPayload {
    fn from(value: RemoveName) -> Self {
        EditPayload::RemoveName(value)
    }
}

impl SchemaFieldSpec {
    /// A field with nothing declared and no rules — the shape a plain column
    /// takes. Chain the setters for whatever it actually has.
    pub fn new(name: impl Into<String>, render_id: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            render_id: render_id.into(),
            value_formula: None,
            validation_formula: None,
            editability_formula: None,
            field_type: None,
            description: None,
            required: None,
            unique: None,
            default_value: None,
            write_policy: None,
            agg_func: None,
            pivot_col_value: None,
            pivot_measure: None,
            pivot_func: None,
            agg_field: None,
        }
    }

    pub fn with_value_formula(mut self, f: Option<String>) -> Self {
        self.value_formula = f;
        self
    }

    pub fn with_validation_formula(mut self, f: Option<String>) -> Self {
        self.validation_formula = f;
        self
    }

    pub fn with_editability_formula(mut self, f: Option<String>) -> Self {
        self.editability_formula = f;
        self
    }

    pub fn with_field_type(
        mut self,
        t: crate::block_manager::schema_manager::field_type::FieldType,
    ) -> Self {
        self.field_type = Some(t.to_parts());
        self
    }

    pub fn with_description(mut self, d: Option<String>) -> Self {
        self.description = d;
        self
    }

    pub fn with_required(mut self, r: bool) -> Self {
        self.required = Some(r);
        self
    }

    pub fn with_unique(mut self, u: bool) -> Self {
        self.unique = Some(u);
        self
    }

    pub fn with_default_value(mut self, v: Option<String>) -> Self {
        self.default_value = v;
        self
    }

    pub fn with_write_policy(
        mut self,
        p: crate::block_manager::schema_manager::field_type::FieldWritePolicy,
    ) -> Self {
        self.write_policy = Some(p.as_str().to_string());
        self
    }

    /// Declare this column a pivot ROW TOTAL: it spans every value of the
    /// column dimension instead of one of them.
    pub fn with_pivot_total(mut self) -> Self {
        self.pivot_col_value =
            Some(crate::block_manager::schema_manager::field_type::PIVOT_COL_ALL.to_string());
        self
    }

    /// Declare this pivot column's own measure and function, so one pivot can
    /// show `SUM of amt` beside `COUNT of orders`. `col_value` is the column
    /// dimension value it belongs to, or `None` for a total across all of them.
    pub fn with_pivot_column(
        mut self,
        col_value: Option<&str>,
        func: crate::block_manager::schema_manager::field_type::AggFunc,
        measure: impl Into<String>,
    ) -> Self {
        self.pivot_col_value = Some(
            col_value
                .unwrap_or(crate::block_manager::schema_manager::field_type::PIVOT_COL_ALL)
                .to_string(),
        );
        self.pivot_func = Some(func.as_str().to_string());
        self.pivot_measure = Some(measure.into());
        self
    }

    pub fn with_aggregate(
        mut self,
        func: crate::block_manager::schema_manager::field_type::AggFunc,
        source_field: impl Into<String>,
    ) -> Self {
        self.agg_func = Some(func.as_str().to_string());
        self.agg_field = Some(source_field.into());
        self
    }
}

/// One `unique_together` group: the field names whose values must not repeat
/// in combination.
///
/// A named type rather than a bare `Vec<Vec<String>>` because the binding
/// generator renders a nested list as `readonly readonly string[][]`, which is
/// not valid TypeScript. Wrapping the inner list also gives the concept a name
/// on both sides of the wire, and matches the shape it is persisted in.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "unique_together_group.ts", rename_all = "camelCase")]
pub struct UniqueTogetherGroup {
    pub fields: Vec<String>,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "bind_form_schema.ts", builder, rename_all = "camelCase")]
pub struct BindFormSchema {
    pub ref_name: String,
    pub sheet_idx: usize,
    pub block_id: usize,
    // Form schema fields start from this index.
    pub field_from: usize,
    // Form schema keys start from this index.
    pub key_idx: usize,
    /// The fields, in order along the schema's field axis.
    pub fields: Vec<SchemaFieldSpec>,
    pub row: bool,
    /// Index along the RECORD axis of the line that holds field NAMES rather
    /// than a record — row 0 for a table with a header row above its data.
    ///
    /// `None` (the default, and what every caller sent before this existed)
    /// means the names live only in the schema, and every line of the block is
    /// a record. Declaring one is what makes a header travel with the block:
    /// it is part of the block rather than a stray row above it, and it is the
    /// schema that says so, because which line is names is a matter of how the
    /// block is READ.
    pub header_idx: Option<usize>,
    /// Field-name groups whose values must not repeat in COMBINATION.
    ///
    /// `Option` so a caller that predates this keeps working; absent and empty
    /// mean the same thing. A group of fewer than two names is ignored —
    /// single-field uniqueness is `SchemaFieldSpec::unique`, which already
    /// derives its own rule.
    pub unique_together: Option<Vec<UniqueTogetherGroup>>,
}

impl From<BindFormSchema> for EditPayload {
    fn from(value: BindFormSchema) -> Self {
        EditPayload::BindFormSchema(value)
    }
}

/// Replace the per-field rule templates on a block whose
/// `BindFormSchema` has already been applied. Lets callers stage
/// schema registration and templated-formula installation as two
/// separate payloads in the same transaction — useful when several
/// blocks BLOCKREF each other and the parser needs every block's
/// refName + field set to be registered before any formula is parsed.
///
/// Index alignment matches the original BindFormSchema: entry `i` is
/// the formula for the field at index `i` of the bound schema's
/// `fields` list. `None` / empty string clears the field's formula
/// (a previously-templated field becomes free-form again). The vec
/// length must equal the bound schema's field count.
///
/// Any of the three rule vecs (`field_formulas`, `validation_formulas`,
/// `editability_formulas`) may be sent as `[]` to mean "leave this rule
/// kind untouched" — the engine preserves the existing per-field values.
/// To explicitly clear all rules of a kind, send `vec![None; N]`. Any
/// non-empty vec replaces every per-field value for that kind.
#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "upsert_field_formulas.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct UpsertFieldFormulas {
    pub sheet_idx: usize,
    pub block_id: usize,
    pub field_formulas: Vec<Option<String>>,
    pub validation_formulas: Vec<Option<String>>,
    pub editability_formulas: Vec<Option<String>>,
}

impl From<UpsertFieldFormulas> for EditPayload {
    fn from(value: UpsertFieldFormulas) -> Self {
        EditPayload::UpsertFieldFormulas(value)
    }
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "bind_random_schema.ts", builder, rename_all = "camelCase")]
pub struct BindRandomSchema {
    pub ref_name: String,
    pub sheet_idx: usize,
    pub block_id: usize,
    pub units: Vec<RandomSchemaUnit>,
}

impl From<BindRandomSchema> for EditPayload {
    fn from(value: BindRandomSchema) -> Self {
        EditPayload::BindRandomSchema(value)
    }
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "random_schema_unit.ts", builder, rename_all = "camelCase")]
pub struct RandomSchemaUnit {
    pub key: String,
    pub render_id: String,
    pub row: usize,
    pub col: usize,
}

#[derive(Debug, Clone, TS)]
/// Delete `cnt` block rows starting at `start` (0-based within the block).
/// Only the block shrinks; the sheet's rows are untouched.
#[ts(
    file_name = "delete_rows_in_block.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct DeleteRowsInBlock {
    pub sheet_idx: usize,
    pub block_id: usize,
    pub start: usize,
    pub cnt: usize,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "reproduce_cells.ts", builder, rename_all = "camelCase")]
pub struct ReproduceCells {
    pub sheet_idx: usize,
    pub start_row: usize,
    pub start_col: usize,
    // We assume that these cells are extracted sequentially,
    // and we take the first one as the anchor and it will be
    // placed to the (start_row, start_col).
    pub cells: Vec<ReproducibleCell>,
}

#[derive(Debug, Clone, TS)]
/// Insert `cnt` block rows so the first lands at `start` (0-based within the
/// block). Only the block grows; the sheet's rows are untouched.
#[ts(
    file_name = "insert_rows_in_block.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct InsertRowsInBlock {
    pub sheet_idx: usize,
    pub block_id: usize,
    pub start: usize,
    pub cnt: usize,
}

#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "insert_cols_in_block.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct InsertColsInBlock {
    pub sheet_idx: usize,
    pub block_id: usize,
    pub start: usize,
    pub cnt: usize,
}

#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "delete_cols_in_block.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct DeleteColsInBlock {
    pub sheet_idx: usize,
    pub block_id: usize,
    pub start: usize,
    pub cnt: usize,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "block_style_update.ts", builder, rename_all = "camelCase")]
pub struct BlockStyleUpdate {
    pub sheet_idx: usize,
    pub block_id: usize,
    pub row: usize,
    pub col: usize,
    pub style_update: StyleUpdateType,
}

/// Hide or show a row or column.
///
/// Known gap: no executor handles this payload yet, so it currently changes
/// nothing (it is only recorded in the version diff).
#[derive(Default, Debug, Clone, TS)]
#[ts(file_name = "set_visible.ts", builder, rename_all = "camelCase")]
pub struct SetVisible {
    pub is_row: bool,
    pub sheet_idx: usize,
    pub start: usize,
    pub visible: bool,
}

#[derive(Debug, Clone, TS)]
/// A cell by stable ids, as reported in [`ActionEffect`].
#[ts(file_name = "sheet_cell_id.ts", builder, rename_all = "camelCase")]
pub struct SheetCellId {
    pub sheet_id: SheetId,
    pub cell_id: CellId,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "sheet_row_id.ts", builder, rename_all = "camelCase")]
pub struct SheetRowId {
    pub sheet_id: SheetId,
    pub row_id: RowId,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "sheet_col_id.ts", builder, rename_all = "camelCase")]
pub struct SheetColId {
    pub sheet_id: SheetId,
    pub col_id: ColId,
}

/// `ActionEffect` represents the result of handling an `EditAction`.
///
/// Additionally, since `LogiSheets` allows developers to define their own functions,
/// the engine may encounter functions it cannot compute directly. In such cases,
/// the engine will return these tasks to the JavaScript side for further processing.
#[derive(Default, Debug, Clone, TS)]
#[ts(file_name = "action_effect.ts", builder, rename_all = "camelCase")]
pub struct ActionEffect {
    /// The undo-history version after the action: it advances only when an
    /// undoable transaction is recorded. Undo, redo and rejections report 0.
    /// For change detection use `Workbook::get_version` (the revision).
    pub version: u32,
    /// Tasks should be calculated outside this engine(mainly because of network limitations and customer defined)
    pub async_tasks: Vec<Task>,
    /// `Err` when the engine rejected the action. A rejection is reported
    /// here, not raised: callers that need the write to land must check it.
    pub status: StatusCode,

    /// Cells whose value changed, including recalculated dependents. Undo
    /// and redo swap whole snapshots and leave all the change lists empty,
    /// so a host must re-read everything after them.
    pub value_changed: Vec<SheetCellId>,
    pub cell_removed: Vec<SheetCellId>,
    pub style_changed: Vec<SheetCellId>,

    pub row_inserted: Vec<SheetRowId>,
    pub row_removed: Vec<SheetRowId>,
    /// Never populated at present.
    pub row_updated: Vec<SheetRowId>,

    pub col_inserted: Vec<SheetColId>,
    pub col_removed: Vec<SheetColId>,
    /// Never populated at present.
    pub col_updated: Vec<SheetColId>,

    /// Sheet indices whose row-heights or column-widths changed. Lets the
    /// frontend re-render row/column headers (and any UI chrome whose
    /// position depends on row/column metrics) for those sheets without
    /// invalidating cell content.
    pub header_updated: Vec<u32>,

    /// Why the action failed, when `status` is `Err`. The status code is a
    /// placeholder — every rejection is code 1 — so this is the only part a
    /// caller can act on. A rejected transaction names and quotes the payload
    /// it stopped at.
    pub error_message: Option<String>,
}

impl ActionEffect {
    pub fn rejected(reason: String) -> Self {
        ActionEffect {
            status: StatusCode::Err(1),
            error_message: Some(reason),
            ..Default::default()
        }
    }

    pub fn from(version: u32, tasks: Vec<Task>, ty: WorkbookUpdateType) -> Self {
        ActionEffect {
            version,
            async_tasks: tasks,
            status: StatusCode::Ok(ty),
            ..Default::default()
        }
    }
}

/// The results of the tasks which are passed to JS side to calculate previously.
#[derive(Default, Debug, Clone, TS)]
#[ts(file_name = "async_func_result.ts", builder, rename_all = "camelCase")]
pub struct AsyncFuncResult {
    pub tasks: Vec<Task>,
    /// These strings can be numbers, strings and other things.
    /// Note that now error types are hardcoded, which means if the
    /// value is equal to the a specific string like `#TIMEOUT!`,
    /// it is reagarded as an error.
    pub values: Vec<String>,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "status_code.ts", tag = "type", rename_all = "camelCase")]
/// Outcome of an action. `Err`'s code is always 1; the reason is in
/// `ActionEffect::error_message`.
pub enum StatusCode {
    Ok(WorkbookUpdateType),
    Err(u8),
}

#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "workbook_update_type.ts",
    tag = "type",
    rename_all = "camelCase"
)]
/// What a successful action touched, so a host knows how much to redraw.
pub enum WorkbookUpdateType {
    /// Applied, but changed nothing.
    DoNothing,
    Cell,
    /// The sheet list or a sheet's properties (create, delete, rename,
    /// color, visibility), or a checkpoint restore.
    Sheet,
    SheetAndCell,
    /// `Undo` with nothing to undo.
    UndoNothing,
    RedoNothing,
    Undo,
    Redo,
    /// Not produced by the engine at present.
    EphemeralCells,
}

impl Default for StatusCode {
    fn default() -> Self {
        Self::Ok(WorkbookUpdateType::Cell)
    }
}

use crate::{ReproducibleCell, controller::style::PatternFill};
use logisheets_workbook::prelude::*;

#[derive(Debug, Clone, TS)]
/// Apply a partial style change to one cell.
#[ts(file_name = "cell_style_update.ts", builder, rename_all = "camelCase")]
pub struct CellStyleUpdate {
    pub sheet_idx: usize,
    pub row: usize,
    pub col: usize,
    pub ty: StyleUpdateType,
}

#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "ephemeral_cell_style_update.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct EphemeralCellStyleUpdate {
    pub sheet_idx: usize,
    pub id: EphemeralId,
    pub ty: StyleUpdateType,
}

#[derive(Debug, Clone, TS)]
/// Apply a partial style change to whole rows (`row == true`) or columns
/// `from..=to` (inclusive). Where a line crosses a styled column (or row),
/// the change is also written onto that intersection cell, whose own style
/// would otherwise win.
#[ts(file_name = "line_style_update.ts", builder, rename_all = "camelCase")]
pub struct LineStyleUpdate {
    pub sheet_idx: usize,
    pub from: usize,
    pub to: usize,
    pub ty: StyleUpdateType,
    pub row: bool,
}

#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "block_line_style_update.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct BlockLineStyleUpdate {
    pub sheet_idx: usize,
    pub block_id: BlockId,
    pub from: usize,
    pub to: usize,
    pub ty: StyleUpdateType,
    pub row: bool,
}

#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "block_line_name_field_update.ts",
    builder,
    rename_all = "camelCase"
)]
pub struct BlockLineNameFieldUpdate {
    pub sheet_idx: usize,
    pub block_id: BlockId,
    pub line: usize,
    pub row: bool,
    pub name: Option<String>,
    pub field_id: String,
    // If this is set to true, the block line will skip the default render function
    // and it is the app's responsibility to render the block line
    pub diy_render: Option<bool>,
}

/// A font or border color: 8 hex digits in "standard ARGB" order, no `#`
/// (`"FF0B0F19"` is opaque near-black). `#RRGGBB` or 6-digit hex is too short
/// to parse and yields no color, so the style silently does not render.
///
/// Fills use a different shape — see `PatternFill`, which takes
/// `{red, green, blue}` channels.
pub type Color = String;

#[derive(Debug, Clone, TS)]
#[ts(file_name = "alignment.ts", rename_all = "camelCase")]
pub struct Alignment {
    pub horizontal: Option<HorizontalAlignment>,
    pub vertical: Option<VerticalAlignment>,
    pub wrap_text: Option<bool>,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "vertical_alignment.ts", rename_all = "camelCase")]
pub enum VerticalAlignment {
    Center,
    Top,
    Bottom,
    Justify,
    Distributed,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "horizontal_alignment.ts", tag = "type")]
pub enum HorizontalAlignment {
    General,
    Left,
    Center,
    Right,
    Fill,
    Justify,
    CenterContinuous,
    Distributed,
}

/// A partial style change: every `Some` field is applied, `None` fields keep
/// the cell's current value.
///
/// Colors come in two shapes. Font and border colors (`set_font_color`,
/// `set_*_border_color`) are 8-hex-digit ARGB strings with no `#`, e.g.
/// `"FF1976D2"`; a `#RRGGBB` or 6-digit value yields no color and silently
/// does not render. Fill colors go through `set_pattern_fill`, whose
/// `fg_color`/`bg_color` are `{red, green, blue}` objects with 0–255 channels.
#[derive(Debug, Clone, Default, TS)]
#[ts(file_name = "style_update_type.ts", builder, rename_all = "camelCase")]
pub struct StyleUpdateType {
    pub set_font_bold: Option<bool>,
    pub set_font_italic: Option<bool>,
    pub set_font_underline: Option<StUnderlineValues>,
    pub set_font_color: Option<Color>,
    pub set_font_size: Option<f64>,
    pub set_font_name: Option<String>,
    pub set_font_outline: Option<bool>,
    pub set_font_shadow: Option<bool>,
    pub set_font_strike: Option<bool>,
    pub set_font_condense: Option<bool>,
    pub set_left_border_color: Option<Color>,
    pub set_right_border_color: Option<Color>,
    pub set_top_border_color: Option<Color>,
    pub set_bottom_border_color: Option<Color>,
    pub set_left_border_style: Option<StBorderStyle>,
    pub set_right_border_style: Option<StBorderStyle>,
    pub set_top_border_style: Option<StBorderStyle>,
    pub set_bottom_border_style: Option<StBorderStyle>,
    pub set_border_giagonal_up: Option<bool>,
    pub set_border_giagonal_down: Option<bool>,
    pub set_border_outline: Option<bool>,
    pub set_pattern_fill: Option<PatternFill>,
    pub set_alignment: Option<Alignment>,
    pub set_num_fmt: Option<String>,
}

#[derive(Debug, Clone, Default, TS)]
/// Merge the inclusive rectangle. Both corners must be ordinary (non-block)
/// cells. Overlap with an existing merge is not checked.
#[ts(file_name = "merge_cells.ts", builder, rename_all = "camelCase")]
pub struct MergeCells {
    pub sheet_idx: usize,
    pub start_row: usize,
    pub start_col: usize,
    pub end_row: usize,
    pub end_col: usize,
}
#[derive(Debug, Clone, Default, TS)]
/// Unmerge the merge whose TOP-LEFT cell is `(row, col)`. Any other cell,
/// including one inside a merge, is a no-op.
#[ts(file_name = "split_merged_cells.ts", builder, rename_all = "camelCase")]
pub struct SplitMergedCells {
    pub sheet_idx: usize,
    pub row: usize,
    pub col: usize,
}

/// A person's identity as supplied by the host. In the open-source `src` app
/// only `display_name` is set (the author types their own name); enterprise
/// deployments fill in `user_id` + `provider_id` from their corporate
/// directory. The core dedupes these into stable persons.
#[derive(Debug, Clone, Default, TS)]
#[ts(file_name = "author_input.ts", rename_all = "camelCase")]
pub struct AuthorInput {
    pub display_name: String,
    pub user_id: Option<String>,
    pub provider_id: Option<String>,
}

/// A `@mention` span inside a comment's text. `start`/`len` are unicode-scalar
/// offsets into `content` (matching OOXML `startIndex`/`length`). `mention_id`
/// is optional; the core generates one when absent.
#[derive(Debug, Clone, Default, TS)]
#[ts(file_name = "comment_mention.ts", rename_all = "camelCase")]
pub struct CommentMention {
    pub start: usize,
    pub len: usize,
    pub author: AuthorInput,
    pub mention_id: Option<String>,
}

/// Add a root comment or a reply to a cell. `comment_id` is a client-generated
/// GUID (so the host can edit/reply/delete without a round-trip); `parent_id`
/// set makes this note a reply to that root. `dt` is a host-provided ISO-8601
/// timestamp (the host owns the clock).
#[derive(Debug, Clone, Default, TS)]
#[ts(file_name = "add_comment.ts", builder, rename_all = "camelCase")]
pub struct AddComment {
    pub sheet_idx: usize,
    pub row: usize,
    pub col: usize,
    pub comment_id: String,
    pub parent_id: Option<String>,
    pub author: AuthorInput,
    pub dt: String,
    pub content: String,
    pub mentions: Vec<CommentMention>,
}

#[derive(Debug, Clone, Default, TS)]
#[ts(file_name = "edit_comment.ts", builder, rename_all = "camelCase")]
pub struct EditComment {
    pub sheet_idx: usize,
    pub comment_id: String,
    pub content: String,
    pub mentions: Vec<CommentMention>,
}

#[derive(Debug, Clone, Default, TS)]
#[ts(file_name = "delete_comment.ts", builder, rename_all = "camelCase")]
pub struct DeleteComment {
    pub sheet_idx: usize,
    pub comment_id: String,
}

/// Mark a comment thread as resolved / reopened (OOXML `done`).
#[derive(Debug, Clone, Default, TS)]
#[ts(file_name = "resolve_comment.ts", builder, rename_all = "camelCase")]
pub struct ResolveComment {
    pub sheet_idx: usize,
    pub comment_id: String,
    pub resolved: bool,
}

/// Register or refresh a person without authoring a comment — e.g. to
/// pre-load directory users so they can be mentioned before they've posted.
#[derive(Debug, Clone, Default, TS)]
#[ts(file_name = "upsert_person.ts", builder, rename_all = "camelCase")]
pub struct UpsertPerson {
    pub display_name: String,
    pub user_id: Option<String>,
    pub provider_id: Option<String>,
}

impl From<MergeCells> for EditPayload {
    fn from(value: MergeCells) -> Self {
        EditPayload::MergeCells(value)
    }
}

impl From<SplitMergedCells> for EditPayload {
    fn from(value: SplitMergedCells) -> Self {
        EditPayload::SplitMergedCells(value)
    }
}

impl From<AddComment> for EditPayload {
    fn from(value: AddComment) -> Self {
        EditPayload::AddComment(value)
    }
}

impl From<EditComment> for EditPayload {
    fn from(value: EditComment) -> Self {
        EditPayload::EditComment(value)
    }
}

impl From<DeleteComment> for EditPayload {
    fn from(value: DeleteComment) -> Self {
        EditPayload::DeleteComment(value)
    }
}

impl From<ResolveComment> for EditPayload {
    fn from(value: ResolveComment) -> Self {
        EditPayload::ResolveComment(value)
    }
}

impl From<UpsertPerson> for EditPayload {
    fn from(value: UpsertPerson) -> Self {
        EditPayload::UpsertPerson(value)
    }
}

impl From<BlockStyleUpdate> for EditPayload {
    fn from(value: BlockStyleUpdate) -> Self {
        EditPayload::BlockStyleUpdate(value)
    }
}
impl From<CellInput> for EditPayload {
    fn from(value: CellInput) -> Self {
        EditPayload::CellInput(value)
    }
}
impl From<SetCellImage> for EditPayload {
    fn from(value: SetCellImage) -> Self {
        EditPayload::SetCellImage(value)
    }
}
impl From<DeleteCellImage> for EditPayload {
    fn from(value: DeleteCellImage) -> Self {
        EditPayload::DeleteCellImage(value)
    }
}
impl Payload for SetCellImage {}
impl Payload for DeleteCellImage {}
impl From<MoveChart> for EditPayload {
    fn from(value: MoveChart) -> Self {
        EditPayload::MoveChart(value)
    }
}
impl Payload for MoveChart {}
impl From<CreateConditionalFormattingRule> for EditPayload {
    fn from(value: CreateConditionalFormattingRule) -> Self {
        EditPayload::CreateConditionalFormattingRule(value)
    }
}
impl Payload for CreateConditionalFormattingRule {}
impl From<UpdateConditionalFormattingRule> for EditPayload {
    fn from(value: UpdateConditionalFormattingRule) -> Self {
        EditPayload::UpdateConditionalFormattingRule(value)
    }
}
impl Payload for UpdateConditionalFormattingRule {}
impl From<MoveConditionalFormattingRule> for EditPayload {
    fn from(value: MoveConditionalFormattingRule) -> Self {
        EditPayload::MoveConditionalFormattingRule(value)
    }
}
impl Payload for MoveConditionalFormattingRule {}
impl From<DeleteConditionalFormattingRule> for EditPayload {
    fn from(value: DeleteConditionalFormattingRule) -> Self {
        EditPayload::DeleteConditionalFormattingRule(value)
    }
}
impl Payload for DeleteConditionalFormattingRule {}
impl From<DeleteChart> for EditPayload {
    fn from(value: DeleteChart) -> Self {
        EditPayload::DeleteChart(value)
    }
}
impl Payload for DeleteChart {}
impl From<CreateChart> for EditPayload {
    fn from(value: CreateChart) -> Self {
        EditPayload::CreateChart(value)
    }
}
impl Payload for CreateChart {}
impl From<UpdateChart> for EditPayload {
    fn from(value: UpdateChart) -> Self {
        EditPayload::UpdateChart(value)
    }
}
impl Payload for UpdateChart {}
impl From<CreateBlock> for EditPayload {
    fn from(value: CreateBlock) -> Self {
        EditPayload::CreateBlock(value)
    }
}
impl From<SetBlockDescription> for EditPayload {
    fn from(value: SetBlockDescription) -> Self {
        EditPayload::SetBlockDescription(value)
    }
}
impl From<SetBlockPermissions> for EditPayload {
    fn from(value: SetBlockPermissions) -> Self {
        EditPayload::SetBlockPermissions(value)
    }
}
impl From<MoveBlock> for EditPayload {
    fn from(value: MoveBlock) -> Self {
        EditPayload::MoveBlock(value)
    }
}
impl From<RemoveBlock> for EditPayload {
    fn from(value: RemoveBlock) -> Self {
        EditPayload::RemoveBlock(value)
    }
}
impl From<SetColWidth> for EditPayload {
    fn from(value: SetColWidth) -> Self {
        EditPayload::SetColWidth(value)
    }
}
impl From<SetRowHeight> for EditPayload {
    fn from(value: SetRowHeight) -> Self {
        EditPayload::SetRowHeight(value)
    }
}
impl From<SetVisible> for EditPayload {
    fn from(value: SetVisible) -> Self {
        EditPayload::SetVisible(value)
    }
}
impl From<SheetRename> for EditPayload {
    fn from(value: SheetRename) -> Self {
        EditPayload::SheetRename(value)
    }
}
impl From<CellStyleUpdate> for EditPayload {
    fn from(value: CellStyleUpdate) -> Self {
        EditPayload::CellStyleUpdate(value)
    }
}
impl From<LineStyleUpdate> for EditPayload {
    fn from(value: LineStyleUpdate) -> Self {
        EditPayload::LineStyleUpdate(value)
    }
}

impl From<InsertCols> for EditPayload {
    fn from(value: InsertCols) -> Self {
        EditPayload::InsertCols(value)
    }
}
impl From<InsertRows> for EditPayload {
    fn from(value: InsertRows) -> Self {
        EditPayload::InsertRows(value)
    }
}
impl From<DeleteRows> for EditPayload {
    fn from(value: DeleteRows) -> Self {
        EditPayload::DeleteRows(value)
    }
}
impl From<DeleteCols> for EditPayload {
    fn from(value: DeleteCols) -> Self {
        EditPayload::DeleteCols(value)
    }
}

impl From<InsertColsInBlock> for EditPayload {
    fn from(value: InsertColsInBlock) -> Self {
        EditPayload::InsertColsInBlock(value)
    }
}
impl From<InsertRowsInBlock> for EditPayload {
    fn from(value: InsertRowsInBlock) -> Self {
        EditPayload::InsertRowsInBlock(value)
    }
}

impl From<DeleteRowsInBlock> for EditPayload {
    fn from(value: DeleteRowsInBlock) -> Self {
        EditPayload::DeleteRowsInBlock(value)
    }
}

impl From<DeleteColsInBlock> for EditPayload {
    fn from(value: DeleteColsInBlock) -> Self {
        EditPayload::DeleteColsInBlock(value)
    }
}

impl From<CreateSheet> for EditPayload {
    fn from(value: CreateSheet) -> Self {
        EditPayload::CreateSheet(value)
    }
}

impl From<DeleteSheet> for EditPayload {
    fn from(value: DeleteSheet) -> Self {
        EditPayload::DeleteSheet(value)
    }
}

impl From<CellFormatBrush> for EditPayload {
    fn from(value: CellFormatBrush) -> Self {
        EditPayload::CellFormatBrush(value)
    }
}

impl From<LineFormatBrush> for EditPayload {
    fn from(value: LineFormatBrush) -> Self {
        EditPayload::LineFormatBrush(value)
    }
}

impl From<EphemeralCellInput> for EditPayload {
    fn from(value: EphemeralCellInput) -> Self {
        EditPayload::EphemeralCellInput(value)
    }
}
impl From<EphemeralCellRemove> for EditPayload {
    fn from(value: EphemeralCellRemove) -> Self {
        EditPayload::EphemeralCellRemove(value)
    }
}
impl From<ConvertBlock> for EditPayload {
    fn from(value: ConvertBlock) -> Self {
        EditPayload::ConvertBlock(value)
    }
}
impl From<CreateLink> for EditPayload {
    fn from(value: CreateLink) -> Self {
        EditPayload::CreateLink(value)
    }
}

impl Payload for CreateLink {}
impl Payload for BlockInput {}
impl Payload for BlockStyleUpdate {}
impl Payload for CellInput {}
impl Payload for CreateBlock {}
impl Payload for MoveBlock {}
impl Payload for RemoveBlock {}
impl Payload for SetColWidth {}
impl Payload for SetRowHeight {}
impl Payload for SetVisible {}
impl Payload for SheetRename {}
impl Payload for CreateSheet {}
impl Payload for DeleteSheet {}
impl Payload for CellStyleUpdate {}
impl Payload for LineStyleUpdate {}
impl Payload for InsertCols {}
impl Payload for InsertRows {}
impl Payload for DeleteCols {}
impl Payload for DeleteRows {}
impl Payload for InsertColsInBlock {}
impl Payload for InsertRowsInBlock {}
impl Payload for DeleteColsInBlock {}
impl Payload for DeleteRowsInBlock {}
impl Payload for CellFormatBrush {}
impl Payload for LineFormatBrush {}
impl Payload for EphemeralCellInput {}
impl Payload for EphemeralCellRemove {}
impl Payload for ConvertBlock {}
impl Payload for UpsertFieldRenderInfo {}
impl Payload for BindFormSchema {}
impl Payload for UpsertFieldFormulas {}
impl Payload for BindRandomSchema {}
impl Payload for RestoreCheckpoint {}
impl Payload for MergeCells {}
impl Payload for SplitMergedCells {}
impl Payload for AddComment {}
impl Payload for EditComment {}
impl Payload for DeleteComment {}
impl Payload for ResolveComment {}
impl Payload for UpsertPerson {}

#[cfg(test)]
mod tests {
    use super::VerticalAlignment;

    #[test]
    fn test_should_have_double_quote() {
        let s1 = "\"center\"".to_string();
        let _: VerticalAlignment = serde_json::from_str(&s1).unwrap();
    }
}