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
use logisheets_base::{
    BlockCellId, BlockId, CellId, CellValue, NormalCellId, SheetId, TextId, errors::BasicError,
    matrix_value::cross_product_usize,
};

use crate::{
    Error,
    cell::Cell,
    edit_action::{CellStyleUpdate, EditPayload},
    utils::resize_rect_diff,
};

use super::{DataContainer, ctx::ContainerExecCtx};

/// True when `cell_id` is a block cell sitting in a field that carries a
/// value-formula template. Such a cell is engine-owned: the schema's
/// template decides what it holds, and a write from anywhere else — a
/// person typing in the grid, a paste, a clear — has to be dropped, or
/// the row silently loses the column's formula.
fn is_templated_cell<C: ContainerExecCtx>(ctx: &C, sheet_id: SheetId, cell_id: &CellId) -> bool {
    match cell_id {
        CellId::BlockCell(bcid) => ctx.is_block_cell_templated(sheet_id, bcid),
        _ => false,
    }
}

pub struct ContainerExecutor {
    pub container: DataContainer,
    pub cells_removed: Vec<(SheetId, CellId)>,
    pub value_changed: Vec<(SheetId, CellId)>,
}

impl ContainerExecutor {
    pub fn new(container: DataContainer) -> Self {
        Self {
            container,
            cells_removed: vec![],
            value_changed: vec![],
        }
    }

    pub fn execute<C: ContainerExecCtx>(
        mut self,
        ctx: &mut C,
        payload: EditPayload,
    ) -> Result<(Self, bool), Error> {
        match payload {
            EditPayload::BlockInput(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let cell_id = ctx.get_block_cell_id(sheet_id, p.block_id, p.row, p.col)?;
                // Templated fields are a constraint: drop user-supplied
                // content here. The formula manager will populate this
                // cell from the schema's template (substituted with
                // this row's #FIELD refs and #KEY value), and the
                // computed value flows back into the container via
                // normal formula evaluation. Returning `false` skips
                // the value_changed dirty notification too — the
                // formula path raises its own.
                if ctx.is_block_cell_templated(sheet_id, &cell_id) {
                    return Ok((self, false));
                }
                let cell_value =
                    CellValue::from_string(p.input, &mut |t| -> TextId { ctx.fetch_text_id(t) });
                self.container
                    .update_value(sheet_id, CellId::BlockCell(cell_id), cell_value);
                self.value_changed
                    .push((sheet_id, CellId::BlockCell(cell_id)));
                Ok((self, true))
            }
            EditPayload::MoveBlock(_) => Ok((self, false)),
            EditPayload::RemoveBlock(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let cells = ctx
                    .get_all_block_cells(sheet_id, p.id)?
                    .into_iter()
                    .map(|bid| CellId::BlockCell(bid))
                    .collect();
                let container = self.container.delete_cells(sheet_id, &cells);

                let mut cells_removed = self.cells_removed;
                cells.into_iter().map(|c| (sheet_id, c)).for_each(|c| {
                    cells_removed.push(c);
                });
                Ok((
                    Self {
                        container,
                        cells_removed,
                        value_changed: self.value_changed,
                    },
                    true,
                ))
            }
            EditPayload::ConvertBlock(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let coords = cross_product_usize(
                    p.master_row,
                    p.master_row + p.row_cnt - 1,
                    p.master_col,
                    p.master_col + p.col_cnt - 1,
                );
                // This block has not been created literally at this point.
                // Since this is a new block, we can get the cell id by row and col.
                let get_block_cell_id = |block_id: &BlockId, row: usize, col: usize| BlockCellId {
                    block_id: block_id.clone(),
                    row: row as u32,
                    col: col as u32,
                };
                let result = coords.into_iter().fold(self, |mut prev, (r, c)| {
                    let ori_cell_id = ctx.fetch_norm_cell_id(&sheet_id, r, c);
                    let new_cell_id = get_block_cell_id(&p.id, r - p.master_row, c - p.master_col);
                    match ori_cell_id {
                        Ok(n) => {
                            let container = prev.container.convert_cell(
                                sheet_id,
                                CellId::NormalCell(n),
                                CellId::BlockCell(new_cell_id),
                            );
                            prev.container = container;
                            prev
                        }
                        _ => prev,
                    }
                });
                Ok((result, true))
            }
            EditPayload::ResizeBlock(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let (row_cnt, col_cnt) = ctx.get_block_size(sheet_id, p.id)?;
                let master_cell = ctx.get_master_cell(sheet_id, p.id)?;
                let (master_row, master_col) =
                    ctx.fetch_normal_cell_index(&sheet_id, &master_cell)?;
                let new_row_cnt = p.new_row_cnt.unwrap_or(row_cnt);
                let new_col_cnt = p.new_col_cnt.unwrap_or(col_cnt);
                let removing_cells = resize_rect_diff(
                    master_row,
                    master_col,
                    row_cnt,
                    col_cnt,
                    new_row_cnt,
                    new_col_cnt,
                )
                .into_iter()
                .flat_map(|(r, c)| ctx.fetch_cell_id(&sheet_id, r, c))
                .collect::<Vec<_>>();
                let container = self.container.delete_cells(sheet_id, &removing_cells);
                let mut cells_removed = self.cells_removed;
                removing_cells.into_iter().for_each(|c| {
                    cells_removed.push((sheet_id, c));
                });
                Ok((
                    Self {
                        container,
                        cells_removed,
                        value_changed: self.value_changed,
                    },
                    true,
                ))
            }
            EditPayload::CreateBlock(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let start_row = p.master_row;
                let start_col = p.master_col;
                let end_row = start_row + p.row_cnt - 1;
                let end_col = start_col + p.col_cnt - 1;
                let cells = cross_product_usize(start_row, end_row, start_col, end_col)
                    .into_iter()
                    .map(|(r, c)| ctx.fetch_cell_id(&sheet_id, r, c))
                    .filter_map(|c| c.ok())
                    .collect::<Vec<_>>();
                let container = self.container.delete_cells(sheet_id, &cells);

                let mut cells_removed = self.cells_removed;
                cells.into_iter().for_each(|c| {
                    cells_removed.push((sheet_id, c));
                });
                Ok((
                    Self {
                        container,
                        cells_removed,
                        value_changed: self.value_changed,
                    },
                    true,
                ))
            }
            EditPayload::ReproduceCells(p) => {
                if p.cells.is_empty() {
                    return Ok((self, true));
                }
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let mut exec_ctx = self;
                let anchor_x = p.cells[0].coordinate.row;
                let anchor_y = p.cells[0].coordinate.col;
                for cell in p.cells {
                    let cell_id = ctx.fetch_cell_id(
                        &sheet_id,
                        cell.coordinate.row - anchor_x + p.start_row,
                        cell.coordinate.col - anchor_y + p.start_col,
                    )?;
                    // Paste / fill lands on whatever the target rectangle
                    // covers, which may include a block's computed column.
                    // Skip those cells rather than refusing the whole
                    // operation — the rest of the paste is legitimate.
                    if is_templated_cell(ctx, sheet_id, &cell_id) {
                        continue;
                    }
                    let cell_value = match cell.value {
                        crate::Value::Str(s) => {
                            CellValue::from_string(s, &mut |t| -> TextId { ctx.fetch_text_id(t) })
                        }
                        crate::Value::Bool(b) => CellValue::Boolean(b),
                        crate::Value::Number(n) => CellValue::Number(n),
                        crate::Value::Error(e) => {
                            CellValue::Error(logisheets_base::Error::from_string(e))
                        }
                        crate::Value::Empty => CellValue::Blank,
                    };
                    let new_id = ctx.insert_style(cell.style.clone())?;
                    if let Some(c) = exec_ctx.container.get_cell_mut(sheet_id, &cell_id) {
                        c.style = new_id;
                        c.value = cell_value;
                    } else {
                        exec_ctx.container.add_cell(
                            sheet_id,
                            cell_id,
                            Cell {
                                value: cell_value,
                                style: new_id,
                            },
                        );
                    }
                }
                Ok((exec_ctx, true))
            }
            EditPayload::CellInput(p) => {
                if p.content.starts_with("=") {
                    // Formula
                    return Ok((self, false));
                }
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let cell_value =
                    CellValue::from_string(p.content, &mut |t| -> TextId { ctx.fetch_text_id(t) });
                let cell_id = ctx.fetch_cell_id(&sheet_id, p.row, p.col)?;
                // A templated block cell belongs to its field's formula.
                // `BlockInput` already drops writes here; `CellInput` is
                // the path a person typing into the grid takes, so it has
                // to drop them too — otherwise a stray keystroke replaces
                // the computed value and the formula executor tears the
                // row's formula out behind it.
                if is_templated_cell(ctx, sheet_id, &cell_id) {
                    return Ok((self, false));
                }
                self.container.update_value(sheet_id, cell_id, cell_value);
                self.value_changed.push((sheet_id, cell_id));
                Ok((self, true))
            }
            EditPayload::EphemeralCellInput(p) => {
                if p.content.starts_with("=") {
                    // Formula
                    return Ok((self, false));
                }
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let cell_id = CellId::EphemeralCell(p.id);
                let cell_value =
                    CellValue::from_string(p.content, &mut |t| -> TextId { ctx.fetch_text_id(t) });
                self.container.update_value(sheet_id, cell_id, cell_value);
                self.value_changed.push((sheet_id, cell_id));
                Ok((self, true))
            }
            EditPayload::EphemeralCellRemove(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let cell_id = CellId::EphemeralCell(p.id);
                self.container.remove_cell(sheet_id, &cell_id);
                self.value_changed.push((sheet_id, cell_id));
                Ok((self, true))
            }
            EditPayload::CellClear(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let cell_id = ctx.fetch_cell_id(&sheet_id, p.row, p.col)?;
                // Clearing a templated cell would blank a value the schema
                // is about to recompute anyway — and removing the cell drops
                // the formula with it. Leave it alone.
                if is_templated_cell(ctx, sheet_id, &cell_id) {
                    return Ok((self, false));
                }
                self.container.remove_cell(sheet_id, &cell_id);
                self.value_changed.push((sheet_id, cell_id));
                Ok((self, true))
            }
            EditPayload::SetColWidth(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let col_id = ctx.fetch_col_id(&sheet_id, p.col)?;
                let info = self.container.get_col_info_mut(sheet_id, col_id);
                info.custom_width = true;
                info.width = Some(p.width);
                Ok((self, true))
            }
            EditPayload::SetRowHeight(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let row_id = ctx.fetch_row_id(&sheet_id, p.row)?;
                let info = self.container.get_row_info_mut(sheet_id, row_id);
                info.custom_height = true;
                info.ht = Some(p.height);
                Ok((self, true))
            }
            EditPayload::DeleteSheet(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                self.container.data.remove(&sheet_id);
                Ok((self, true))
            }
            EditPayload::DeleteCols(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let bids =
                    ctx.get_affected_blockplace(sheet_id, p.start, p.count as usize, false)?;

                let mut deleted_cells = Vec::<CellId>::new();
                for block_id in bids.into_iter() {
                    let (row_cnt, col_cnt) = ctx.get_block_size(sheet_id, block_id)?;
                    let master = ctx.get_master_cell(sheet_id, block_id)?;
                    let (master_row, master_col) =
                        ctx.fetch_normal_cell_index(&sheet_id, &master)?;
                    let start_row = master_row;
                    let end_row = master_row + row_cnt as usize - 1;
                    let start_col = master_col + col_cnt;
                    let end_col = start_col + p.count as usize - 1;
                    cross_product_usize(start_row, end_row, start_col, end_col)
                        .into_iter()
                        .for_each(|(r, c)| {
                            if let Ok(cid) = ctx.fetch_cell_id(&sheet_id, r, c) {
                                deleted_cells.push(cid)
                            }
                        });
                }

                self.get_norm_cell_ids_by_line(ctx, &sheet_id, p.start, p.count, false)
                    .into_iter()
                    .for_each(|c| deleted_cells.push(CellId::NormalCell(c)));

                let container = self.container.delete_cells(sheet_id, &deleted_cells);
                let mut cells_removed = self.cells_removed;
                deleted_cells.into_iter().for_each(|c| {
                    cells_removed.push((sheet_id, c));
                });
                Ok((
                    Self {
                        container,
                        cells_removed,
                        value_changed: self.value_changed,
                    },
                    true,
                ))
            }
            EditPayload::DeleteRows(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let bids =
                    ctx.get_affected_blockplace(sheet_id, p.start, p.count as usize, true)?;

                let mut deleted_cells = Vec::<CellId>::new();
                for block_id in bids.into_iter() {
                    let (row_cnt, col_cnt) = ctx.get_block_size(sheet_id, block_id)?;
                    let master = ctx.get_master_cell(sheet_id, block_id)?;
                    let (master_row, master_col) =
                        ctx.fetch_normal_cell_index(&sheet_id, &master)?;
                    let start_row = master_row + row_cnt;
                    let end_row = start_row + p.count as usize - 1;
                    let start_col = master_col;
                    let end_col = master_col + col_cnt as usize - 1;
                    cross_product_usize(start_row, end_row, start_col, end_col)
                        .into_iter()
                        .for_each(|(r, c)| {
                            if let Ok(cid) = ctx.fetch_cell_id(&sheet_id, r, c) {
                                deleted_cells.push(cid)
                            }
                        });
                }

                self.get_norm_cell_ids_by_line(ctx, &sheet_id, p.start, p.count, true)
                    .into_iter()
                    .for_each(|c| deleted_cells.push(CellId::NormalCell(c)));

                let container = self.container.delete_cells(sheet_id, &deleted_cells);

                let mut cells_removed = self.cells_removed;
                deleted_cells.into_iter().for_each(|c| {
                    cells_removed.push((sheet_id, c));
                });
                Ok((
                    Self {
                        container,
                        cells_removed,
                        value_changed: self.value_changed,
                    },
                    true,
                ))
            }
            EditPayload::InsertColsInBlock(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let (row_cnt, col_cnt) = ctx.get_block_size(sheet_id, p.block_id)?;
                let master = ctx.get_master_cell(sheet_id, p.block_id)?;
                let (master_row, master_col) = ctx.fetch_normal_cell_index(&sheet_id, &master)?;
                let start_row = master_row + row_cnt;
                let end_row = start_row + p.cnt - 1;
                let start_col = master_col;
                let end_col = master_col + col_cnt - 1;
                let cells = cross_product_usize(start_row, end_row, start_col, end_col)
                    .into_iter()
                    .map(|(r, c)| ctx.fetch_cell_id(&sheet_id, r, c))
                    .filter_map(|c| c.ok())
                    .collect::<Vec<_>>();
                let container = self.container.delete_cells(sheet_id, &cells);
                let mut cells_removed = self.cells_removed;
                cells.into_iter().for_each(|c| {
                    cells_removed.push((sheet_id, c));
                });
                Ok((
                    Self {
                        container,
                        cells_removed,
                        value_changed: self.value_changed,
                    },
                    true,
                ))
            }
            EditPayload::DeleteColsInBlock(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let (row_cnt, _) = ctx.get_block_size(sheet_id, p.block_id)?;
                let master = ctx.get_master_cell(sheet_id, p.block_id)?;
                let (master_row, master_col) = ctx.fetch_normal_cell_index(&sheet_id, &master)?;
                let start_row = master_row;
                let end_row = start_row + row_cnt - 1;
                let start_col = master_col + p.start;
                let end_col = start_col + p.cnt - 1;
                let cells = cross_product_usize(start_row, end_row, start_col, end_col)
                    .into_iter()
                    .map(|(r, c)| ctx.fetch_cell_id(&sheet_id, r, c))
                    .filter_map(|c| c.ok())
                    .collect::<Vec<_>>();
                let container = self.container.delete_cells(sheet_id, &cells);
                let mut cells_removed = self.cells_removed;
                cells.into_iter().for_each(|c| {
                    cells_removed.push((sheet_id, c));
                });
                Ok((
                    Self {
                        container,
                        cells_removed,
                        value_changed: self.value_changed,
                    },
                    true,
                ))
            }
            EditPayload::InsertRowsInBlock(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let (row_cnt, col_cnt) = ctx.get_block_size(sheet_id, p.block_id)?;
                let master = ctx.get_master_cell(sheet_id, p.block_id)?;
                let (master_row, master_col) = ctx.fetch_normal_cell_index(&sheet_id, &master)?;
                let start_row = master_row + row_cnt;
                let end_row = start_row + p.cnt - 1;
                let start_col = master_col;
                let end_col = master_col + col_cnt - 1;
                let cells = cross_product_usize(start_row, end_row, start_col, end_col)
                    .into_iter()
                    .map(|(r, c)| ctx.fetch_cell_id(&sheet_id, r, c))
                    .filter_map(|c| c.ok())
                    .collect::<Vec<_>>();
                let container = self.container.delete_cells(sheet_id, &cells);
                let mut cells_removed = self.cells_removed;
                cells.into_iter().for_each(|c| {
                    cells_removed.push((sheet_id, c));
                });
                Ok((
                    Self {
                        container,
                        cells_removed,
                        value_changed: self.value_changed,
                    },
                    true,
                ))
            }
            EditPayload::DeleteRowsInBlock(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let (_, col_cnt) = ctx.get_block_size(sheet_id, p.block_id)?;
                let master = ctx.get_master_cell(sheet_id, p.block_id)?;
                let (master_row, master_col) = ctx.fetch_normal_cell_index(&sheet_id, &master)?;
                let start_row = master_row + p.start;
                let end_row = start_row + p.cnt - 1;
                let start_col = master_col;
                let end_col = start_col + col_cnt - 1;
                let cells = cross_product_usize(start_row, end_row, start_col, end_col)
                    .into_iter()
                    .map(|(r, c)| ctx.fetch_cell_id(&sheet_id, r, c))
                    .filter_map(|c| c.ok())
                    .collect::<Vec<_>>();
                let container = self.container.delete_cells(sheet_id, &cells);
                let mut cells_removed = self.cells_removed;
                cells.into_iter().for_each(|c| {
                    cells_removed.push((sheet_id, c));
                });
                Ok((
                    Self {
                        container,
                        cells_removed,
                        value_changed: self.value_changed,
                    },
                    true,
                ))
            }
            EditPayload::BlockStyleUpdate(payload) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(payload.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let cell_id = CellId::BlockCell(ctx.get_block_cell_id(
                    sheet_id,
                    payload.block_id,
                    payload.row,
                    payload.col,
                )?);
                if let Some(c) = self.container.get_cell_mut(sheet_id, &cell_id) {
                    let new_id = ctx.get_new_style_id(c.style, payload.style_update)?;
                    c.style = new_id;
                } else {
                    let new_id = ctx.get_new_style_id(0, payload.style_update)?;
                    self.container.add_cell(
                        sheet_id,
                        cell_id,
                        Cell {
                            value: CellValue::Blank,
                            style: new_id,
                        },
                    );
                }
                Ok((self, true))
            }
            EditPayload::CellStyleUpdate(style_update) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(style_update.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let cell_id = ctx.fetch_cell_id(&sheet_id, style_update.row, style_update.col)?;
                if let Some(c) = self.container.get_cell_mut(sheet_id, &cell_id) {
                    let new_id = ctx.get_new_style_id(c.style, style_update.ty)?;
                    c.style = new_id;
                } else {
                    let new_id = ctx.get_new_style_id(0, style_update.ty)?;
                    self.container.add_cell(
                        sheet_id,
                        cell_id,
                        Cell {
                            value: CellValue::Blank,
                            style: new_id,
                        },
                    );
                }
                Ok((self, true))
            }
            EditPayload::LineStyleUpdate(s) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(s.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let mut exec_ctx = self;
                for i in s.from..=s.to {
                    if s.row {
                        let row_id = ctx.fetch_row_id(&sheet_id, i)?;
                        let row = exec_ctx.container.get_row_info_mut(sheet_id, row_id);
                        let new_id = ctx.get_new_style_id(row.style, s.ty.clone())?;
                        row.style = new_id;
                        //
                        // In ooxml, the style of the cell has the following properties:
                        // 1. The style of the cell itself.
                        // 2. The style of the row.
                        // 3. The style of the column.
                        //
                        // When users modify the row or column, we should set the style of the cell to make sure
                        // the latest style is applied to the cell.
                        let cells = exec_ctx
                            .container
                            .get_to_be_modified_cells_by_row(sheet_id, row_id);
                        for c in cells {
                            let (r, c) = ctx.fetch_normal_cell_index(&sheet_id, &c)?;
                            let p = EditPayload::CellStyleUpdate(CellStyleUpdate {
                                sheet_idx: s.sheet_idx as usize,
                                row: r,
                                col: c,
                                ty: s.ty.clone(),
                            });
                            (exec_ctx, _) = exec_ctx.execute(ctx, p)?;
                        }
                    } else {
                        let col_id = ctx.fetch_col_id(&sheet_id, i)?;
                        let col = exec_ctx.container.get_col_info_mut(sheet_id, col_id);
                        let new_id = ctx.get_new_style_id(col.style, s.ty.clone())?;
                        col.style = new_id;
                        let cells = exec_ctx
                            .container
                            .get_to_be_modified_cells_by_col(sheet_id, col_id);
                        for c in cells {
                            let (r, c) = ctx.fetch_normal_cell_index(&sheet_id, &c)?;
                            let p = EditPayload::CellStyleUpdate(CellStyleUpdate {
                                sheet_idx: s.sheet_idx as usize,
                                row: r,
                                col: c,
                                ty: s.ty.clone(),
                            });
                            (exec_ctx, _) = exec_ctx.execute(ctx, p)?;
                        }
                    }
                }
                Ok((exec_ctx, true))
            }
            EditPayload::BlockLineStyleUpdate(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let block_id = p.block_id;
                let from = p.from;
                let to = p.to;
                let ty = p.ty;
                let row = p.row;
                let mut exec_ctx = self;
                let block_line_info_manager = &mut exec_ctx
                    .container
                    .get_sheet_container_mut(sheet_id)
                    .block_line_info_manager;
                for i in from..=to {
                    let id = if row {
                        ctx.get_block_cell_id(sheet_id, block_id, i, 0)?.row
                    } else {
                        ctx.get_block_cell_id(sheet_id, block_id, 0, i)?.col
                    };
                    let old_style = if row {
                        block_line_info_manager
                            .get_row_info(block_id, id)
                            .map(|info| info.style)
                            .flatten()
                            .unwrap_or(0)
                    } else {
                        block_line_info_manager
                            .get_col_info(block_id, id)
                            .map(|info| info.style)
                            .flatten()
                            .unwrap_or(0)
                    };
                    let new_style = ctx.get_new_style_id(old_style, ty.clone())?;
                    let new_style = if new_style == 0 {
                        None
                    } else {
                        Some(new_style)
                    };
                    if row {
                        block_line_info_manager.update_row_info_style(block_id, id, new_style);
                    } else {
                        block_line_info_manager.update_col_info_style(block_id, id, new_style);
                    }
                }
                Ok((exec_ctx, true))
            }
            EditPayload::BlockLineNameFieldUpdate(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let block_id = p.block_id;
                let line = p.line;
                let mut exec_ctx = self;
                let block_line_info_manager = &mut exec_ctx
                    .container
                    .get_sheet_container_mut(sheet_id)
                    .block_line_info_manager;

                let id = if p.row {
                    ctx.get_block_cell_id(sheet_id, block_id, line, 0)?.row
                } else {
                    ctx.get_block_cell_id(sheet_id, block_id, 0, line)?.col
                };

                if p.row {
                    block_line_info_manager.update_row_info_name(block_id, id, p.name);
                    block_line_info_manager.update_row_info_field_id(block_id, id, p.field_id);
                    block_line_info_manager.update_row_info_diy_render(block_id, id, p.diy_render);
                } else {
                    block_line_info_manager.update_col_info_name(block_id, id, p.name);
                    block_line_info_manager.update_col_info_field_id(block_id, id, p.field_id);
                    block_line_info_manager.update_col_info_diy_render(block_id, id, p.diy_render);
                }

                Ok((exec_ctx, true))
            }
            EditPayload::CellFormatBrush(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.src_sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let cell_id = ctx.fetch_cell_id(&sheet_id, p.src_row, p.src_col)?;
                let cell = self.container.get_cell(sheet_id, &cell_id);
                let id = if let Some(c) = cell { c.style } else { 0 };
                for r in p.dst_row_start..=p.dst_row_end {
                    for c in p.dst_col_start..=p.dst_col_end {
                        let cell_id = ctx.fetch_cell_id(&sheet_id, r, c)?;
                        let cell = self.container.get_cell_mut(sheet_id, &cell_id);
                        if let Some(c) = cell {
                            c.style = id;
                        } else {
                            self.container.add_cell(
                                sheet_id,
                                cell_id,
                                Cell {
                                    value: CellValue::Blank,
                                    style: id,
                                },
                            );
                        }
                    }
                }
                Ok((self, true))
            }
            EditPayload::LineFormatBrush(p) => {
                let sheet_id = ctx
                    .fetch_sheet_id_by_index(p.src_sheet_idx)
                    .map_err(|l| BasicError::SheetIdxExceed(l))?;
                let cell_id = ctx.fetch_cell_id(&sheet_id, p.src_row, p.src_col)?;
                let cell = self.container.get_cell(sheet_id, &cell_id);
                let cell_id = if let Some(c) = cell { c.style } else { 0 };
                for l in p.from..=p.to {
                    if p.row {
                        let row_id = ctx.fetch_row_id(&sheet_id, l)?;
                        let row = self.container.get_row_info_mut(sheet_id, row_id);
                        row.style = cell_id;
                    } else {
                        let col_id = ctx.fetch_col_id(&sheet_id, l)?;
                        let col = self.container.get_col_info_mut(sheet_id, col_id);
                        col.style = cell_id;
                    }
                }
                Ok((self, true))
            }
            _ => Ok((self, false)),
        }
    }

    fn get_norm_cell_ids_by_line<C: ContainerExecCtx>(
        &self,
        ctx: &C,
        sheet_id: &SheetId,
        idx: usize,
        cnt: usize,
        is_row: bool,
    ) -> Vec<NormalCellId> {
        let Some(sheet_container) = self.container.data.get(sheet_id) else {
            return Vec::new();
        };
        let mut result = Vec::<NormalCellId>::new();
        sheet_container.cells.iter().for_each(|(cid, _)| match cid {
            CellId::NormalCell(nc) => {
                let cidx = ctx.fetch_cell_index(&sheet_id, cid);
                if let Ok((r, c)) = cidx {
                    if is_row && r >= idx && r <= idx + cnt - 1 {
                        result.push(nc.clone())
                    } else if !is_row && c >= idx && c <= idx + cnt - 1 {
                        result.push(nc.clone())
                    }
                }
            }
            CellId::BlockCell(_) => {}
            CellId::EphemeralCell(_) => {}
        });
        result
    }
}