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
use crate::CellInfo;
use crate::block_manager::schema_manager::field_type::FieldTypeParts;

use super::style::Style;
use gents_derives::TS;
use logisheets_base::{BlockId, SheetId};

use crate::block_manager::schema_manager::schema::RenderId;

#[derive(Debug, Clone, TS)]
/// An offset from the sheet's top-left corner, in Excel's native units, which
/// DIFFER per axis: `y` sums row heights in points, `x` sums column widths in
/// character-width units. Neither is pixels; hosts convert each axis
/// separately (the engine UI uses `ptToPx` / `widthToPx`).
#[ts(file_name = "cell_position.ts", rename_all = "camelCase")]
pub struct CellPosition {
    pub x: f64,
    pub y: f64,
}

#[derive(Debug, Clone, TS)]
/// A 0-based grid position. Note the axis naming: `x` is the COLUMN and `y`
/// is the ROW.
#[ts(file_name = "cell_coordinate.ts", rename_all = "camelCase")]
pub struct CellCoordinate {
    pub x: usize,
    pub y: usize,
}

/// One exported block row: the field values in schema (column) order. Wrapping
/// the row in a struct keeps the exported matrix as `BlockDataRow[]` rather
/// than a nested `Value[][]`, which the TS binding generator can't render.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "block_data_row.ts", rename_all = "camelCase")]
pub struct BlockDataRow {
    pub cells: Vec<crate::Value>,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "cell_coordinate_with_sheet.ts", rename_all = "camelCase")]
pub struct CellCoordinateWithSheet {
    pub sheet_idx: usize,
    pub coordinate: CellCoordinate,
}

#[derive(Debug, Clone, TS)]
/// A shadow cell's value and the rectangle of the cell it shadows
/// ([`CellPosition`] units).
#[ts(file_name = "shadow_cell_info.ts", rename_all = "camelCase")]
pub struct ShadowCellInfo {
    pub start_position: CellPosition,
    pub end_position: CellPosition,
    pub value: Value,
}

#[derive(Debug, Clone, Default, TS)]
/// Everything needed to paint a rectangle of the sheet. Hidden rows and
/// columns are left out of `rows`/`cols`; `merge_cells` holds merges that
/// intersect the window; `blocks` the blocks any included cell belongs to.
#[ts(file_name = "display_window.ts", rename_all = "camelCase")]
pub struct DisplayWindow {
    pub cells: Vec<CellInfo>,
    pub rows: Vec<RowInfo>,
    pub cols: Vec<ColInfo>,
    pub comments: Vec<Comment>,
    pub merge_cells: Vec<MergeCell>,
    pub blocks: Vec<BlockDisplayInfo>,
}

#[derive(Debug, Clone, TS)]
/// A block with its on-sheet rectangle ([`CellPosition`] units; `end` is the
/// far corner of its bottom-right cell).
#[ts(file_name = "block_display_info.ts", rename_all = "camelCase")]
pub struct BlockDisplayInfo {
    pub info: BlockInfo,
    pub start_position: CellPosition,
    pub end_position: CellPosition,
}

#[derive(Debug, Clone, TS)]
#[ts(
    file_name = "display_window_with_start_point.ts",
    rename_all = "camelCase"
)]
pub struct DisplayWindowWithStartPoint {
    pub window: DisplayWindow,
    pub start_x: f64,
    pub start_y: f64,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "sheet_names.ts", rename_all = "camelCase")]
pub struct SheetNames {
    pub names: Vec<String>,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "sheet_info.ts", rename_all = "camelCase")]
pub struct SheetInfo {
    pub name: String,
    pub id: SheetId,
    pub hidden: bool,
    /// ARGB hex as stored (see `SetSheetColor`); `""` when unset.
    pub tab_color: String,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "sheet_blocks.ts", rename_all = "camelCase")]
pub struct SheetBlocks {
    pub sheet_idx: usize,
    pub blocks: Vec<BlockInfo>,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "block_info.ts", rename_all = "camelCase")]
pub struct BlockInfo {
    pub sheet_idx: usize,
    pub sheet_id: SheetId,
    pub block_id: BlockId,
    /// 0-based sheet row of the block's top-left cell.
    pub row_start: usize,
    pub row_cnt: usize,
    /// 0-based sheet column of the block's top-left cell.
    pub col_start: usize,
    pub col_cnt: usize,
    pub schema: Option<BlockSchema>,
    pub field_renders: Vec<FieldRenderEntry>,
    pub cells: Vec<BlockCellInfo>,
    /// What the block is for, in prose — empty when nobody said. The schema
    /// describes the shape of the records; this is the only thing that says
    /// what they mean, which is what an AI reading the sheet needs.
    pub description: String,
    /// The craft that created the block, empty for one the user made.
    pub owner: String,
    /// The block's default write policy.
    pub modify_policy: crate::edit_action::ModifyPolicy,
    /// Per-operation overrides of it. Do not read these apart to decide
    /// whether an edit is allowed — ask `Workbook::may_modify_block`, so
    /// every host answers the question the same way.
    pub permissions: crate::edit_action::BlockPermissions,
    /// Which block this one ANALYSES, when it is an analysis block — a total
    /// row, a set of statistics, later a pivot. `None` for an ordinary block.
    ///
    /// Reported in both directions on purpose. An agent reading the sheet has
    /// to be able to tell a table from its analysis: the rows of an analysis
    /// block are its own records, not the source's, and summing them alongside
    /// the source would double-count. See `design/block-analysis.md`.
    pub analyzes: Option<BlockId>,
    /// The blocks that analyse THIS one. Empty for a block nobody summarises.
    pub analyzed_by: Vec<BlockId>,
    /// When this analysis block is a PIVOT, the recipe it derives from.
    /// `None` for a total row and for an ordinary block.
    ///
    /// Reported because a pivot's SHAPE is data, so a reader has to know it is
    /// looking at one: a stale pivot's numbers are each correct while a whole
    /// group is simply absent, which is the one way a block can mislead
    /// without being wrong. See `design/block-pivot.md` §8.
    pub pivot: Option<crate::block_manager::schema_manager::field_type::PivotSpecParts>,
}

/// A range that is linked to a backing block: the *source* range (the cells the
/// user references, e.g. `A1:A10`) resolved to sheet coordinates, plus the block
/// id it redirects to. The app draws an outer border around the source range.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "link_info.ts", rename_all = "camelCase")]
pub struct LinkInfo {
    pub sheet_idx: usize,
    pub block_id: BlockId,
    pub start_row: usize,
    pub start_col: usize,
    pub end_row: usize,
    pub end_col: usize,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "block_schema.ts", rename_all = "camelCase")]
pub struct BlockSchema {
    pub name: String,
    pub schema_type: BlockSchemaType,
    pub keys: Vec<BlockSchemaKeyEntry>,
    pub fields: Vec<BlockSchemaFieldEntry>,
    pub random_entries: Vec<BlockSchemaRandomEntry>,
    /// Block-relative index of the line holding field NAMES rather than a
    /// record, when the schema declares one.
    ///
    /// An INDEX rather than the line id the schema stores, because a host
    /// counts lines from the block's corner and has no business knowing line
    /// ids. Absent for the blocks that have no header line, which is most.
    pub header_idx: Option<usize>,
    /// Block-relative index of the KEY line, on the same axis `fields` are
    /// numbered on: the key COLUMN of a row schema, the key ROW of a column
    /// schema.
    ///
    /// Comparable with [`BlockSchemaFieldEntry::idx`], and deliberately NOT
    /// with [`BlockSchemaKeyEntry::idx`], which counts along the RECORD axis —
    /// see `api::worksheet::key_index` for what conflating the two cost.
    /// `None` only for a random schema, which has no key axis.
    pub key_idx: Option<usize>,
    /// Field groups whose values must not repeat in COMBINATION — the block's
    /// own rule, as opposed to the per-field ones on each entry.
    pub unique_together: Vec<crate::edit_action::UniqueTogetherGroup>,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "block_schema_type.ts", rename_all = "camelCase")]
pub enum BlockSchemaType {
    Row,
    Col,
    Random,
}

#[derive(Debug, Clone, Default, TS)]
#[ts(file_name = "block_schema_key_entry.ts", rename_all = "camelCase")]
pub struct BlockSchemaKeyEntry {
    pub key: String,
    pub idx: usize,
}

#[derive(Debug, Clone, Default, TS)]
#[ts(file_name = "block_schema_field_entry.ts", rename_all = "camelCase")]
pub struct BlockSchemaFieldEntry {
    pub field: String,
    pub idx: usize,
    pub render_id: RenderId,
    /// Raw value-formula template (e.g. `=#FIELD("qty")*#FIELD("price")`)
    /// or `None` for free-form fields. Engine-managed: writing a value
    /// to a templated cell is rejected.
    pub value_formula: Option<String>,
    /// Raw validation-formula template. Engine installs a
    /// `ShadowKind::Validation` shadow per row at bind / insert time;
    /// host UI reads the shadow to render warning markers.
    pub validation_formula: Option<String>,
    /// Raw editability-formula template. Engine installs a
    /// `ShadowKind::UserEditable` shadow per row at bind / insert time;
    /// host permission layer reads the shadow to gate writes.
    pub editability_formula: Option<String>,
    /// The field's declaration — what it is, what it is for, and the two
    /// non-formula constraints. Absent means nobody said: a block bound before
    /// the declaration existed, or converted from plain cells.
    ///
    /// This is the half that used to live only in the host, keyed by
    /// `render_id` and persisted as opaque JSON, so no headless host could read
    /// it and `describe_block` could not report a type in any host. See
    /// `design/block-field-semantics.md`.
    pub field_type: Option<FieldTypeParts>,
    pub description: Option<String>,
    pub required: bool,
    pub unique: bool,
    pub default_value: Option<String>,
    /// Who may write to this field's cells: `inherit` | `ownerOnly` |
    /// `anyone`. A declaration for the host to decide with — the engine does
    /// not know who is writing. Always reported, so a reader never has to
    /// guess what an absent value meant.
    pub write_policy: String,
    /// When the block analyses another one: how this field aggregates it —
    /// `SUM` | `COUNT` | `AVERAGE` | `MIN` | `MAX`, over `agg_field` of the
    /// analysed block. Both absent for an ordinary field, which is what the
    /// label column of a total row is.
    ///
    /// Reported so a reader can see WHAT the number is rather than only that
    /// it is a number — and so an agent knows not to write to it.
    pub agg_func: Option<String>,
    pub agg_field: Option<String>,
    /// When the block is a PIVOT and this column is hand-declared: the column
    /// dimension value it filters on (`*` = every value, a row total), and
    /// optionally its own measure and function. All absent for the derived
    /// columns of a plain cross-tab.
    pub pivot_col_value: Option<String>,
    pub pivot_measure: Option<String>,
    pub pivot_func: Option<String>,
}

impl BlockSchemaFieldEntry {
    /// Project one schema field for a reader. Four call sites in
    /// `api/worksheet.rs` built this by hand and differed only in how they
    /// found `idx`; going through one constructor is what keeps a newly-added
    /// declaration field from reaching two of them and not the other two.
    pub fn from_entry<F>(
        name: &str,
        idx: usize,
        entry: &crate::block_manager::schema_manager::schema::FieldEntry<F>,
    ) -> Self {
        let parts = entry.field_type.to_parts();
        Self {
            field: name.to_string(),
            idx,
            render_id: entry.render_id.clone(),
            value_formula: entry.value_formula.clone(),
            validation_formula: entry.validation_formula.clone(),
            editability_formula: entry.editability_formula.clone(),
            field_type: parts.kind.is_some().then_some(parts),
            description: entry.description.clone(),
            required: entry.required,
            unique: entry.unique,
            default_value: entry.default_value.clone(),
            write_policy: entry.write_policy.as_str().to_string(),
            agg_func: entry
                .aggregate
                .as_ref()
                .map(|a| a.func.as_str().to_string()),
            agg_field: entry.aggregate.as_ref().map(|a| a.source_field.clone()),
            pivot_col_value: entry.pivot_column.as_ref().map(|c| c.col_value_str()),
            pivot_measure: entry.pivot_column.as_ref().and_then(|c| c.measure.clone()),
            pivot_func: entry
                .pivot_column
                .as_ref()
                .and_then(|c| c.func.map(|f| f.as_str().to_string())),
        }
    }
}

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

#[derive(Debug, Clone, Default, TS)]
#[ts(file_name = "field_render_entry.ts", rename_all = "camelCase")]
pub struct FieldRenderEntry {
    pub render_id: RenderId,
    pub style: Option<Style>,
    pub diy_render: bool,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "block_cell_info.ts", rename_all = "camelCase")]
pub struct BlockCellInfo {
    pub value: Value,
    // None means that no shadow cell has been created
    pub shadow_value: Option<Value>,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "display_window_request.ts", rename_all = "camelCase")]
pub struct DisplayWindowRequest {
    pub sheet_idx: usize,
    pub height: f64,
    pub width: f64,
    pub start_x: f64,
    pub start_y: f64,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "sheet_merge_cells.ts", rename_all = "camelCase")]
pub struct SheetMergeCells {
    pub sheet_idx: usize,
    pub merge_cells: Vec<MergeCell>,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "sheet_comments.ts", rename_all = "camelCase")]
pub struct SheetComments {
    pub sheet_idx: usize,
    pub comments: Vec<Comment>,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "merge_cell.ts", rename_all = "camelCase")]
pub struct MergeCell {
    pub start_row: usize,
    pub start_col: usize,
    pub end_row: usize,
    pub end_col: usize,
}

/// An image placed in a cell. `data` is the base64-encoded image bytes and
/// `format` is the bare file extension (e.g. `png`). Used by the frontend to
/// render the image on the canvas at the cell's position.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "cell_image_info.ts", rename_all = "camelCase")]
pub struct CellImageInfo {
    pub row: usize,
    pub col: usize,
    pub id: String,
    pub format: String,
    pub data: String,
}

/// One data series of a chart, resolved for rendering. `values` holds the
/// cached numeric values (gaps are `null`); the frontend re-reads live values
/// from the source range and only falls back to these.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "chart_series_info.ts", rename_all = "camelCase")]
pub struct ChartSeriesInfo {
    pub name: Option<String>,
    pub values: Vec<Option<f64>>,
    /// Resolved fill color as an RGB/ARGB hex (no `#`), or `None` to use the
    /// renderer's default palette. Scheme colors are resolved against the theme.
    pub color: Option<String>,
    /// `values` rendered with the label number format — the exact strings a
    /// data label should show. The renderer cannot do this itself: Excel
    /// number formats are evaluated by the core, not the host.
    pub formatted_values: Vec<Option<String>>,
    /// Bubble sizes, live from `size_ref` — a bubble chart's third dimension.
    /// Empty for every other chart kind.
    pub sizes: Vec<Option<f64>>,
    /// The bubble-size source range, e.g. `Sheet1!$D$2:$D$6`.
    pub size_ref: Option<String>,
    /// The kind this series is drawn as when it differs from the chart's own —
    /// what makes a combo chart. `None` means it follows `chart_type`.
    pub series_type: Option<String>,
    /// The series' source range, e.g. `Sheet1!$B$2:$E$2`. This is what an
    /// editor shows and rewrites when the user re-points the series.
    pub val_ref: Option<String>,
    /// Excel number-format code for this series' values, taken from the source
    /// cells (Excel's "linked to source"), falling back to the format the
    /// producer cached. `None` means render the raw number.
    pub num_fmt: Option<String>,
}

/// An axis' scale as it will be drawn. All-`None`/false is a fully automatic
/// axis, which is what most charts have.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "chart_axis_scale_info.ts", rename_all = "camelCase")]
pub struct ChartAxisScaleInfo {
    pub min: Option<f64>,
    pub max: Option<f64>,
    pub log_base: Option<f64>,
    pub reversed: bool,
    pub major_unit: Option<f64>,
    pub minor_unit: Option<f64>,
}

/// How a pie-of-pie / bar-of-pie divides its series between the two plots.
/// Empty for every other chart kind.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "chart_of_pie_split_info.ts", rename_all = "camelCase")]
pub struct ChartOfPieSplitInfo {
    /// `auto | cust | percent | pos | val`.
    pub by: Option<String>,
    /// Read according to `by`: a count of trailing points, a value threshold,
    /// or a percentage.
    pub pos: Option<f64>,
    /// The second plot's size as a percentage of the first.
    pub second_size: Option<f64>,
}

/// What a chart draws next to each data point. All-false means no labels.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "chart_data_labels_info.ts", rename_all = "camelCase")]
pub struct ChartDataLabelsInfo {
    pub show_value: bool,
    pub show_category: bool,
    pub show_series: bool,
    pub show_percent: bool,
    pub show_legend_key: bool,
    /// `ctr|inEnd|outEnd|inBase|bestFit`, or `None` for the renderer's default.
    pub position: Option<String>,
    /// Number-format code for the label's value; overrides the series format.
    pub num_fmt: Option<String>,
}

/// A chart anchored on a sheet, resolved for rendering. The anchor is its
/// from/to cell positions plus EMU offsets into those cells; `chart_type` is
/// one of `col|bar|line|area|pie|doughnut|scatter|radar|bubble|stock|ofPie|
/// barOfPie|surface|surface3d`; `legend_pos` (if any) is `top|bottom|left|right`.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "chart_info.ts", rename_all = "camelCase")]
pub struct ChartInfo {
    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,
    /// Set when the chart is anchored by a size rather than a second cell
    /// (`oneCellAnchor`): the frame's width and height in EMUs. `to_*` then
    /// repeats the `from` cell and carries no extent, so a host that wants to
    /// draw the frame should use these when they are present.
    pub ext_cx: Option<i64>,
    pub ext_cy: Option<i64>,
    pub chart_type: String,
    pub stacked: bool,
    pub title: Option<String>,
    pub legend_pos: Option<String>,
    /// Category labels, read live from `cat_ref` and formatted the way the
    /// source cells display (so dates read as dates), falling back to the
    /// labels cached in the file.
    pub categories: Vec<String>,
    /// The category (X) source range, e.g. `Sheet1!$A$2:$A$5`.
    pub cat_ref: Option<String>,
    pub series: Vec<ChartSeriesInfo>,
    pub cat_axis_title: Option<String>,
    pub val_axis_title: Option<String>,
    pub data_labels: ChartDataLabelsInfo,
    pub of_pie_split: ChartOfPieSplitInfo,
    pub val_axis_scale: ChartAxisScaleInfo,
    pub cat_axis_scale: ChartAxisScaleInfo,
    /// Number-format code for the value axis, live from the first series'
    /// source cells when the chart does not set one itself.
    pub val_axis_num_fmt: Option<String>,
    /// Set when the chart plots a block rather than fixed ranges. The refs
    /// above are then derived from the block as it is right now, so a host
    /// showing a chart's source should say which block it follows rather than
    /// present the range as something the user typed.
    pub block_source: Option<ChartBlockSourceInfo>,
}

/// The block a chart follows: its id, the field labelling the categories, and
/// the fields plotted as series.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "chart_block_source_info.ts", rename_all = "camelCase")]
pub struct ChartBlockSourceInfo {
    pub block_id: usize,
    pub category_field: Option<String>,
    pub value_fields: Vec<String>,
}

/// A person referenced by a comment (author or mention). Enterprise builds
/// populate `user_id` + `provider_id` from their directory; the `src` app
/// leaves them `None` and only sets `display_name`.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "comment_person.ts", rename_all = "camelCase")]
pub struct CommentPerson {
    pub display_name: String,
    pub user_id: Option<String>,
    pub provider_id: Option<String>,
}

/// A resolved `@mention` span within a note's content.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "comment_mention_info.ts", rename_all = "camelCase")]
pub struct CommentMentionInfo {
    pub start: usize,
    pub len: usize,
    pub person: CommentPerson,
}

/// A single note in a comment thread (root or reply).
#[derive(Debug, Clone, TS)]
#[ts(file_name = "comment_note.ts", rename_all = "camelCase")]
pub struct CommentNote {
    pub id: String,
    pub author: CommentPerson,
    pub dt: String,
    pub content: String,
    pub parent_id: Option<String>,
    pub mentions: Vec<CommentMentionInfo>,
    pub resolved: bool,
}

/// A comment thread anchored at a cell. `notes` is ordered (root first, then
/// replies).
#[derive(Debug, Clone, TS)]
#[ts(file_name = "comment.ts", rename_all = "camelCase")]
pub struct Comment {
    pub row: usize,
    pub col: usize,
    pub notes: Vec<CommentNote>,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "sheet_row_info.ts", rename_all = "camelCase")]
pub struct SheetRowInfo {
    pub sheet_idx: usize,
    pub info: Vec<RowInfo>,
    pub default_height: f64,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "row_info.ts", rename_all = "camelCase")]
pub struct RowInfo {
    /// 0-based row index.
    pub idx: usize,
    /// Points.
    pub height: f64,
    pub hidden: bool,
}

impl RowInfo {
    /// Uses the global default height (15pt), not the sheet's own default.
    pub fn default(idx: usize) -> RowInfo {
        Self {
            idx,
            height: get_default_row_height(),
            hidden: false,
        }
    }
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "sheet_col_info.ts", rename_all = "camelCase")]
pub struct SheetColInfo {
    pub sheet_idx: usize,
    pub info: Vec<ColInfo>,
    pub default_width: f64,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "col_info.ts", rename_all = "camelCase")]
pub struct ColInfo {
    /// 0-based column index.
    pub idx: usize,
    /// Excel character-width units, not pixels.
    pub width: f64,
    pub hidden: bool,
}

impl ColInfo {
    /// Uses the global default width (8.43), not the sheet's own default.
    pub fn default(idx: usize) -> Self {
        Self {
            idx,
            width: get_default_col_width(),
            hidden: false,
        }
    }
}

/// Excel's default row height, in points.
pub fn get_default_row_height() -> f64 {
    15.
}

/// Excel's default column width, in character-width units.
pub fn get_default_col_width() -> f64 {
    8.43
}

#[derive(Debug, Clone, Default, TS)]
#[ts(file_name = "value.ts", tag = "type")]
pub enum Value {
    Str(String),
    Bool(bool),
    Number(f64),
    Error(String),
    #[default]
    Empty,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "cell_formula_value.ts", rename_all = "camelCase")]
pub struct CellFormulaValue {
    pub row: usize,
    pub col: usize,
    pub formula: String,
    pub value: Value,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "sheet_values.ts", rename_all = "camelCase")]
pub struct SheetValues {
    pub sheet_idx: usize,
    pub values: Vec<CellFormulaValue>,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "cell_style.ts", rename_all = "camelCase")]
pub struct CellStyle {
    pub row: usize,
    pub col: usize,
    pub style: Style,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "sheet_styles.ts", rename_all = "camelCase")]
pub struct SheetStyles {
    pub sheet_idx: usize,
    pub styles: Vec<CellStyle>,
}

/// One cell that changed inside the active temp branch. `old_value` is
/// what's in the committed branch (the `fork_status` snapshot taken when
/// temp mode began); `new_value` is what the cell holds right now in the
/// live temp branch. Position is the *current* (post-temp) sheet row/col
/// — block inserts may shift earlier rows downward, so even cells that
/// didn't have a direct write may surface here with shifted positions.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "temp_cell_change.ts", rename_all = "camelCase")]
pub struct TempCellChange {
    pub sheet_idx: usize,
    pub row: usize,
    pub col: usize,
    pub old_value: Value,
    pub new_value: Value,
}

/// Diff between the active temp branch and the committed branch.
/// Returned by `Workbook::get_temp_status_changes`; empty when no temp
/// branch is currently active.
#[derive(Debug, Clone, Default, TS)]
#[ts(file_name = "temp_status_diff.ts", rename_all = "camelCase")]
pub struct TempStatusDiff {
    pub cells: Vec<TempCellChange>,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "block_field.ts", rename_all = "camelCase")]
pub struct BlockField {
    pub sheet_id: SheetId,
    pub block_id: BlockId,
    pub field_id: String,
}