logisheets_controller 1.13.0

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
use crate::conditional_formatting_manager::spec::CfRuleSpec;
use gents_derives::TS;
use logisheets_base::{BlockId, CellId, ColId, EphemeralId, RowId, SheetId, async_func::Task};

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 {
    Undo,
    Redo,
    Payloads(PayloadsAction),
    Recalc(Vec<RecalcCell>),
}

#[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>,
    pub undoable: bool,
    // An action that is used to customize the initial status of a new workbook.
    // This action is `undoable` but its new status should be recorded to history.
    pub init: bool,
}

impl PayloadsAction {
    pub fn new() -> Self {
        PayloadsAction {
            payloads: vec![],
            undoable: false,
            init: false,
        }
    }

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

    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),

    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)]
#[ts(file_name = "create_sheet.ts", builder, rename_all = "camelCase")]
pub struct CreateSheet {
    pub idx: usize,
    pub new_name: String,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "delete_sheet.ts", builder, rename_all = "camelCase")]
pub struct DeleteSheet {
    pub idx: usize,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "set_sheet_color.ts", builder, rename_all = "camelCase")]
pub struct SetSheetColor {
    pub idx: usize,
    pub color: String,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "set_sheet_visible.ts", builder, rename_all = "camelCase")]
pub struct SetSheetVisible {
    pub idx: usize,
    pub visible: bool,
}

/// Find a sheet by its name and rename it. If no sheet is found, do nothing.
#[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)]
#[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)]
#[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)]
#[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)]
#[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)]
#[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)]
#[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,
}

/// 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.
/// 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 and data
/// references. Any field left `None` keeps the chart's current value.
/// `chart_type` is one of `col|bar|line|area|pie|doughnut|scatter`.
#[derive(Debug, Clone, 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>,
}

/// One series for [`CreateChart`]: an optional name and a value reference
/// formula (e.g. `Sheet1!$B$2:$E$2`).
#[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,
}

/// Create a new chart anchored at `from`..`to`. `chart_type` is one of
/// `col|bar|line|area|pie|doughnut|scatter`. `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>,
}

/// 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)]
#[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.
#[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)]
#[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)]
#[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. You are supposed to
/// manage all your blocks. If the `block id` is already existed, engines
/// will remove the old one.
///
/// `owner` and `modify_policy` are optional metadata used by the frontend
/// to gate write access at runtime. They are not enforced by the engine
/// itself.
#[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>,
}

/// Controls who is allowed to write to a block at the frontend runtime layer.
/// Reads are always allowed regardless of policy.
#[derive(Debug, Clone, 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,
        }
    }
}

/// 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,
    pub modify_policy: ModifyPolicy,
}

#[derive(Debug, Clone, TS)]
#[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)]
#[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)]
#[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)]
#[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)]
#[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)]
#[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)]
#[ts(file_name = "remove_block.ts", builder, rename_all = "camelCase")]
pub struct RemoveBlock {
    pub sheet_idx: usize,
    pub id: usize,
}

#[derive(Debug, Clone, TS)]
#[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)]
#[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)]
#[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)
    }
}

#[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,
    pub fields: Vec<String>,
    // Generated by frontend app.
    // It is used to customize the fields' render behaviors.
    // The length of this vector should be the same as `fields`.
    pub render_ids: Vec<String>,
    pub row: bool,
    /// Per-field value-formula templates. Same indexing as `fields` —
    /// entry `i` is the formula for field `fields[i]`, or `None` for
    /// free-form fields. `Some("")` is treated as `None` after trim.
    ///
    /// Templates use `#FIELD("name")` (substituted with a reference to
    /// the same row's sibling cell) and `#KEY` (substituted with this
    /// row's key value as a string literal). When a field has a
    /// template, the engine derives the cell value from it; user
    /// `blockInput` payloads targeting that field are ignored (the
    /// formula is the constraint).
    ///
    /// Callers must always send this vec (use `[]` for "no templates").
    /// The vec length, when non-empty, must equal `fields.len()` — index
    /// alignment is positional.
    pub field_formulas: Vec<Option<String>>,
    /// Per-field validation-formula templates. Same indexing as `fields`.
    /// Each template is evaluated per row as a boolean: FALSE surfaces
    /// a `ShadowKind::Validation` warning on the cell (advisory; the
    /// cell value still commits). Empty vec = all None. Supports the
    /// same placeholders as `field_formulas`, plus `#PLACEHOLDER` which
    /// expands to a reference to the cell itself.
    pub validation_formulas: Vec<Option<String>>,
    /// Per-field editability-formula templates. Same indexing as `fields`.
    /// Each template is evaluated per row as a boolean: FALSE installs
    /// a `ShadowKind::UserEditable` lock so the host permission patch
    /// refuses writes to that cell. Empty vec = all None. Same
    /// placeholder support as `validation_formulas`.
    pub editability_formulas: Vec<Option<String>>,
}

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)]
#[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)]
#[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,
}

#[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)]
#[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`.
/// The `version` will be incremented if the action is successfully handled.
///
/// 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 latest version after processing an action. 0 means latest version
    pub version: u32,
    /// Tasks should be calculated outside this engine(mainly because of network limitations and customer defined)
    pub async_tasks: Vec<Task>,
    pub status: StatusCode,

    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>,
    pub row_updated: Vec<SheetRowId>,

    pub col_inserted: Vec<SheetColId>,
    pub col_removed: Vec<SheetColId>,
    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 error codes are a placeholder — every rejection is currently code 1 —
    /// so the code alone tells a caller nothing. The executor's real message was
    /// already being captured, but only to be printed: `println!` goes nowhere
    /// under wasm, and the wasm layer merely forwarded it to the browser
    /// console. Carrying it here means every host (Node, tests, an agent tool
    /// layer) gets the reason, atomically with the failure it belongs to.
    pub error_message: Option<String>,
}

impl ActionEffect {
    pub fn from_err(e: u8) -> Self {
        ActionEffect {
            status: StatusCode::Err(e),
            ..Default::default()
        }
    }

    /// A failure that carries the executor's own explanation.
    pub fn from_err_with_message(e: u8, message: Option<String>) -> Self {
        ActionEffect {
            status: StatusCode::Err(e),
            error_message: message,
            ..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")]
pub enum StatusCode {
    Ok(WorkbookUpdateType), // when there is no other history version for undo/redo, return false.
    Err(u8),
}

#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "workbook_update_type.ts",
    tag = "type",
    rename_all = "camelCase"
)]
pub enum WorkbookUpdateType {
    DoNothing,
    Cell,
    Sheet,
    SheetAndCell,
    UndoNothing,
    RedoNothing,
    Undo,
    Redo,
    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)]
#[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)]
#[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>,
}

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,
}

#[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)]
#[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)]
#[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<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();
    }
}