logisheets-rs 1.16.1

The Rust API for LogiSheets — a spreadsheet engine that reads, edits, and writes .xlsx
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
use crate::{
    ActionEffect, AppData, BasicError, BlockDataRow, BlockField, BlockId, BlockSortOrder,
    CellCoordinateWithSheet, CellInfo, ColId, DisplayWindow, EditAction, Error, ErrorMessage,
    FormulaDisplayInfo, PayloadsAction, PivotExcelNote, PivotPlan, PivotSpecParts, RowId, RowInfo,
    SaveFileResult, ShadowCellInfo, SheetCellId, SheetId, SheetInfo, TempStatusDiff, Workbook,
    lex_and_fmt, lex_success,
};

use super::{Manager, Transaction};

// ============================================================================
// Transport-agnostic workbook logic. Each function is a thin, serialization-free
// wrapper over `Workbook`, returning typed values (`Result<T, ErrorMessage>` for
// fallible calls, `T` otherwise). It receives `&Manager` / `&mut Manager` from
// whichever transport drives it (browser WASM `handle`, or a native Tauri
// command) so both share one implementation; serialization happens at the edge.
// ============================================================================

/// Open an empty workbook and return the book id every later call needs.
pub fn new_workbook(mgr: &mut Manager) -> usize {
    mgr.new_workbook()
}

/// Parse `buf` as .xlsx into the workbook slot `id`, replacing what was there
/// and resetting its pending payloads. On a parse error the slot is untouched.
/// `id` need not exist yet; a transport normally mints it with [`new_workbook`]
/// first.
pub fn read_file(
    mgr: &mut Manager,
    id: usize,
    name: String,
    buf: &[u8],
) -> Result<(), ErrorMessage> {
    let wb = Workbook::from_file(buf, name).map_err(ErrorMessage::from)?;
    mgr.replace_workbook(id, wb);
    Ok(())
}

/// Serialize workbook `id` to .xlsx bytes.
///
/// `app_data` replaces the workbook's whole app-data list with one entry named
/// `logisheets` before writing, and stays set after the call. With
/// `resolve_block_refs`, block formulas are written as A1 references so another
/// spreadsheet can recalculate them.
pub fn save_file(
    mgr: &mut Manager,
    id: usize,
    app_data: String,
    resolve_block_refs: bool,
) -> Result<SaveFileResult, ErrorMessage> {
    let ctrl = mgr.workbook_mut(id)?;
    ctrl.set_app_data(vec![AppData {
        name: "logisheets".to_string(),
        data: app_data,
    }]);
    let format = if resolve_block_refs {
        logisheets_controller::FormulaFormat::Coordinates
    } else {
        logisheets_controller::FormulaFormat::Named
    };
    let data = ctrl.save_with_format(format).map_err(ErrorMessage::from)?;
    Ok(SaveFileResult { data })
}

pub fn get_app_data(mgr: &Manager, id: usize) -> Result<Vec<AppData>, ErrorMessage> {
    Ok(mgr.workbook(id)?.get_app_data())
}

/// Drop workbook `id`. Releasing an unknown id is a no-op; later calls on it fail.
pub fn release(mgr: &mut Manager, id: usize) {
    mgr.remove(id)
}

pub fn undo(mgr: &mut Manager, id: usize) -> Result<bool, ErrorMessage> {
    Ok(mgr.workbook_mut(id)?.undo())
}

pub fn redo(mgr: &mut Manager, id: usize) -> Result<bool, ErrorMessage> {
    Ok(mgr.workbook_mut(id)?.redo())
}

pub fn clean_history(mgr: &mut Manager, id: usize) -> Result<(), ErrorMessage> {
    mgr.workbook_mut(id)?.clear_history();
    Ok(())
}

pub fn commit_temp_status(mgr: &mut Manager, id: usize) -> Result<(), ErrorMessage> {
    mgr.workbook_mut(id)?.commit_temp_status();
    Ok(())
}

pub fn clean_temp_status(mgr: &mut Manager, id: usize) -> Result<(), ErrorMessage> {
    mgr.workbook_mut(id)?.clean_temp_status();
    Ok(())
}

pub fn is_in_temp_mode(mgr: &Manager, id: usize) -> Result<bool, ErrorMessage> {
    Ok(mgr.workbook(id)?.is_in_temp_mode())
}

/// A no-op kept for old callers: the temp branch opens on the first `temp` transaction.
pub fn toggle_status(mgr: &mut Manager, id: usize, use_temp: bool) -> Result<(), ErrorMessage> {
    mgr.workbook_mut(id)?.toggle_status(use_temp);
    Ok(())
}

pub fn batch_get_cell_info_by_id(
    mgr: &mut Manager,
    id: usize,
    ids: Vec<SheetCellId>,
) -> Result<Vec<CellInfo>, ErrorMessage> {
    let wb = mgr.workbook_mut(id)?;
    wb.batch_get_cell_info_by_id(ids)
        .map_err(ErrorMessage::from)
}

pub fn batch_get_cell_coordinate_with_sheet_by_id(
    mgr: &mut Manager,
    id: usize,
    ids: Vec<SheetCellId>,
) -> Result<Vec<CellCoordinateWithSheet>, ErrorMessage> {
    let wb = mgr.workbook_mut(id)?;
    wb.batch_get_cell_coordinate_with_sheet_by_id(ids)
        .map_err(ErrorMessage::from)
}

pub fn get_sheet_name_by_idx(
    mgr: &mut Manager,
    id: usize,
    idx: usize,
) -> Result<String, ErrorMessage> {
    let wb = mgr.workbook_mut(id)?;
    wb.get_sheet_name_by_idx(idx).map_err(ErrorMessage::from)
}

pub fn get_sheet_count(mgr: &Manager, id: usize) -> Result<usize, ErrorMessage> {
    Ok(mgr.workbook(id)?.get_sheet_count())
}

pub fn get_version(mgr: &Manager, id: usize) -> Result<u32, ErrorMessage> {
    Ok(mgr.workbook(id)?.get_version())
}

pub fn get_all_sheet_info(mgr: &Manager, id: usize) -> Result<Vec<SheetInfo>, ErrorMessage> {
    Ok(mgr.workbook(id)?.get_all_sheet_info())
}

pub fn get_formula_function_names(mgr: &Manager, id: usize) -> Result<Vec<String>, ErrorMessage> {
    Ok(mgr.workbook(id)?.get_formula_function_names())
}

pub fn get_row_info(
    mgr: &Manager,
    id: usize,
    sheet_idx: usize,
    row_idx: usize,
) -> Result<RowInfo, ErrorMessage> {
    let wb = mgr.workbook(id)?;
    let ws = wb.get_sheet_by_idx(sheet_idx).map_err(ErrorMessage::from)?;
    Ok(ws
        .get_row_info(row_idx)
        .unwrap_or(RowInfo::default(row_idx)))
}

pub fn check_formula(mgr: &Manager, id: usize, f: String) -> Result<bool, ErrorMessage> {
    Ok(mgr.workbook(id)?.check_formula(f))
}

/// Evaluate `f` for its truth value. Goes through a normal (non-temp) write of
/// an ephemeral cell, so it bumps the version and discards any open temp
/// branch.
pub fn calc_condition(
    mgr: &mut Manager,
    id: usize,
    sheet_idx: usize,
    f: String,
) -> Result<bool, ErrorMessage> {
    let wb = mgr.workbook_mut(id)?;
    wb.calc_condition(sheet_idx, f).map_err(ErrorMessage::from)
}

pub fn get_cell_id_by_block_ref(
    mgr: &Manager,
    id: usize,
    ref_name: String,
    key: String,
    field: String,
) -> Result<SheetCellId, ErrorMessage> {
    let wb = mgr.workbook(id)?;
    wb.get_cell_id_by_block_ref(&ref_name, &key, &field)
        .map_err(ErrorMessage::from)
}

pub fn export_block_data(
    mgr: &Manager,
    id: usize,
    ref_name: String,
    key_filter: Option<Vec<String>>,
    field_filter: Option<Vec<String>>,
) -> Result<Vec<BlockDataRow>, ErrorMessage> {
    let wb = mgr.workbook(id)?;
    wb.export_block_data(&ref_name, key_filter, field_filter)
        .map_err(ErrorMessage::from)
}

pub fn get_temp_status_changes(mgr: &Manager, id: usize) -> Result<TempStatusDiff, ErrorMessage> {
    let wb = mgr.workbook(id)?;
    wb.get_temp_status_changes().map_err(ErrorMessage::from)
}

pub fn check_bind_block(
    mgr: &mut Manager,
    id: usize,
    sheet_idx: usize,
    block_id: usize,
    row_count: usize,
    col_count: usize,
) -> Result<bool, ErrorMessage> {
    Ok(mgr
        .workbook_mut(id)?
        .check_bind_block(sheet_idx, block_id, row_count, col_count)
        .is_ok())
}

pub fn get_available_block_id(
    mgr: &mut Manager,
    id: usize,
    sheet_idx: usize,
) -> Result<BlockId, ErrorMessage> {
    let wb = mgr.workbook_mut(id)?;
    wb.get_available_block_id(sheet_idx)
        .map_err(ErrorMessage::from)
}

pub fn get_sheet_id(
    mgr: &mut Manager,
    id: usize,
    sheet_idx: usize,
) -> Result<SheetId, ErrorMessage> {
    let wb = mgr.workbook_mut(id)?;
    wb.get_worksheet_id(sheet_idx).map_err(ErrorMessage::from)
}

pub fn get_sheet_idx(mgr: &Manager, id: usize, sheet_id: SheetId) -> Result<usize, ErrorMessage> {
    let wb = mgr.workbook(id)?;
    wb.get_sheet_idx_by_id(sheet_id).map_err(ErrorMessage::from)
}

pub fn get_block_values(
    mgr: &Manager,
    id: usize,
    sheet_id: SheetId,
    block_id: BlockId,
    row_ids: Vec<RowId>,
    col_ids: Vec<ColId>,
) -> Result<Vec<String>, ErrorMessage> {
    let wb = mgr.workbook(id)?;
    wb.get_block_values(sheet_id, block_id, &row_ids, &col_ids)
        .map_err(ErrorMessage::from)
}

pub fn get_block_sort_order(
    mgr: &Manager,
    id: usize,
    sheet_idx: usize,
    block_id: BlockId,
    field: String,
    asc: bool,
) -> Result<BlockSortOrder, ErrorMessage> {
    let wb = mgr.workbook(id)?;
    wb.get_block_sort_order(sheet_idx, block_id, &field, asc)
        .map_err(ErrorMessage::from)
}

/// The shape a pivot block should have, and whether it currently has it.
///
/// Read-only, like [`get_block_sort_order`]: it computes, the caller applies.
/// The caller sends the reshape as ONE transaction in the order
/// `design/block-pivot.md` §6 pins — grow, write the keys, bind, shrink —
/// because `#KEY` is captured when the bind materializes each row.
pub fn pivot_plan(
    mgr: &Manager,
    id: usize,
    sheet_idx: usize,
    block_id: BlockId,
) -> Result<PivotPlan, ErrorMessage> {
    let wb = mgr.workbook(id)?;
    wb.pivot_plan(sheet_idx, block_id)
        .map_err(ErrorMessage::from)
}

/// Why a pivot could not be saved as a real Excel pivot table, or `None`.
///
/// Asked BEFORE building, so a recipe can be chosen knowing whether it will
/// survive the trip — rather than discovering after a save that the file
/// degraded to a grid of numbers Excel cannot recompute.
pub fn pivot_excel_note(
    mgr: &Manager,
    id: usize,
    sheet_idx: usize,
    block_id: BlockId,
) -> Result<PivotExcelNote, ErrorMessage> {
    let wb = mgr.workbook(id)?;
    wb.pivot_excel_note(sheet_idx, block_id)
        .map_err(ErrorMessage::from)
}

/// The shape a pivot over `source_block` WOULD have for a recipe no block
/// carries yet — so a host can create a pivot at its right size in ONE
/// transaction, and therefore one undo.
pub fn pivot_plan_for(
    mgr: &Manager,
    id: usize,
    sheet_idx: usize,
    source_block: BlockId,
    spec: PivotSpecParts,
) -> Result<PivotPlan, ErrorMessage> {
    let wb = mgr.workbook(id)?;
    wb.pivot_plan_for(sheet_idx, source_block, &spec)
        .map_err(ErrorMessage::from)
}

/// Whether `actor` may perform `op` on this block — see
/// [`MayModifyBlockParams`]. Read-only: it decides nothing, it only answers,
/// and the host is what actually refuses the edit.
///
/// [`MayModifyBlockParams`]: crate::rpc::message::MayModifyBlockParams
pub fn may_modify_block(
    mgr: &Manager,
    id: usize,
    sheet_idx: usize,
    block_id: BlockId,
    op: crate::BlockOp,
    actor: crate::BlockActor,
) -> Result<bool, ErrorMessage> {
    let wb = mgr.workbook(id)?;
    wb.may_modify_block(sheet_idx, block_id, op, &actor)
        .map_err(ErrorMessage::from)
}

/// Whether writing `proposed` into this cell would break its field's
/// validation rule — see [`CheckFieldValidationParams`].
///
/// The companion to [`may_modify_block`] for `BlockOp::OverrideValidation`:
/// that answers "may this actor write a violating value", this answers
/// "would this value be a violating one". Neither writes anything.
///
/// [`CheckFieldValidationParams`]: crate::rpc::message::CheckFieldValidationParams
pub fn check_field_validation(
    mgr: &mut Manager,
    id: usize,
    sheet_idx: usize,
    row: usize,
    col: usize,
    proposed: String,
) -> Result<logisheets_controller::FieldValidationVerdict, ErrorMessage> {
    let wb = mgr.workbook_mut(id)?;
    wb.check_field_validation(sheet_idx, row, col, proposed)
        .map_err(ErrorMessage::from)
}

/// A block's governance metadata, without its cells. See
/// [`GetBlockModifyInfoParams`].
///
/// [`GetBlockModifyInfoParams`]: crate::rpc::message::GetBlockModifyInfoParams
pub fn get_block_modify_info(
    mgr: &Manager,
    id: usize,
    sheet_idx: usize,
    block_id: BlockId,
) -> Result<crate::BlockModifyInfo, ErrorMessage> {
    let wb = mgr.workbook(id)?;
    wb.get_block_modify_info(sheet_idx, block_id)
        .map_err(ErrorMessage::from)
}

pub fn get_block_row_id(
    mgr: &mut Manager,
    id: usize,
    sheet_id: SheetId,
    block_id: BlockId,
    row_idx: usize,
) -> Result<RowId, ErrorMessage> {
    let wb = mgr.workbook_mut(id)?;
    let ws = wb.get_sheet_by_id(sheet_id).map_err(ErrorMessage::from)?;
    ws.get_block_row_id(block_id, row_idx)
        .map_err(ErrorMessage::from)
}

pub fn get_block_col_id(
    mgr: &mut Manager,
    id: usize,
    sheet_id: SheetId,
    block_id: BlockId,
    col_idx: usize,
) -> Result<ColId, ErrorMessage> {
    let wb = mgr.workbook_mut(id)?;
    let ws = wb.get_sheet_by_id(sheet_id).map_err(ErrorMessage::from)?;
    ws.get_block_col_id(block_id, col_idx)
        .map_err(ErrorMessage::from)
}

pub fn get_display_window_for_block(
    mgr: &mut Manager,
    id: usize,
    sheet_id: SheetId,
    block_id: BlockId,
) -> Result<DisplayWindow, ErrorMessage> {
    let wb = mgr.workbook_mut(id)?;
    let ws = wb.get_sheet_by_id(sheet_id).map_err(ErrorMessage::from)?;
    ws.get_display_window_for_block(block_id)
        .map_err(ErrorMessage::from)
}

pub fn get_shadow_cell_id(
    mgr: &mut Manager,
    id: usize,
    sheet_idx: usize,
    row_idx: usize,
    col_idx: usize,
    kind: crate::ShadowKind,
) -> Result<SheetCellId, ErrorMessage> {
    let wb = mgr.workbook_mut(id)?;
    wb.get_shadow_cell_id(sheet_idx, row_idx, col_idx, kind)
        .map_err(ErrorMessage::from)
}

pub fn get_shadow_cell_ids(
    mgr: &mut Manager,
    id: usize,
    sheet_idx: usize,
    row_idx: Vec<usize>,
    col_idx: Vec<usize>,
    kind: crate::ShadowKind,
) -> Result<Vec<SheetCellId>, ErrorMessage> {
    let wb = mgr.workbook_mut(id)?;
    wb.get_shawdow_cell_ids(sheet_idx, row_idx, col_idx, kind)
        .map_err(ErrorMessage::from)
}

pub fn get_shadow_info_by_id(
    mgr: &mut Manager,
    id: usize,
    shadow_id: u64,
) -> Result<ShadowCellInfo, ErrorMessage> {
    let wb = mgr.workbook_mut(id)?;
    wb.get_shadow_info_by_id(shadow_id)
        .map_err(ErrorMessage::from)
}

pub fn get_cell_id(
    mgr: &mut Manager,
    id: usize,
    sheet_idx: usize,
    row_idx: usize,
    col_idx: usize,
) -> Result<SheetCellId, ErrorMessage> {
    let wb = mgr.workbook_mut(id)?;
    let sheet_id = wb.get_worksheet_id(sheet_idx).map_err(ErrorMessage::from)?;
    let ws = wb.get_sheet_by_id(sheet_id).map_err(ErrorMessage::from)?;
    let cell_id = ws
        .get_cell_id(row_idx, col_idx)
        .map_err(ErrorMessage::from)?;
    Ok(SheetCellId { sheet_id, cell_id })
}

pub fn get_all_block_fields(mgr: &mut Manager, id: usize) -> Result<Vec<BlockField>, ErrorMessage> {
    let wb = mgr.workbook_mut(id)?;
    wb.get_all_block_fields().map_err(ErrorMessage::from)
}

/// Which [`BlockOp`](logisheets_controller::edit_action::BlockOp) each payload
/// counts as, keyed by wire type name.
///
/// Static, so fetch once and cache. It lives here because the engine defines
/// the operations: every host that enforces a policy needs the mapping, and
/// each keeping its own table is how the same payload comes to be governed
/// differently in different hosts.
pub fn get_block_op_for_payloads(
    mgr: &Manager,
    id: usize,
) -> Result<Vec<crate::BlockOpForPayload>, ErrorMessage> {
    let wb = mgr.workbook(id)?;
    Ok(wb.get_block_op_for_payloads())
}

/// What a block declares for each operation, beyond whether a given actor is
/// allowed. `stated` is the difference between a block that says "anyone may"
/// and one that says nothing — a host needs it to know whether its own owner
/// check still applies.
pub fn get_block_op_policies(
    mgr: &Manager,
    id: usize,
    sheet_idx: usize,
    block_id: BlockId,
) -> Result<Vec<crate::BlockOpPolicy>, ErrorMessage> {
    let wb = mgr.workbook(id)?;
    wb.get_block_op_policies(sheet_idx, block_id)
        .map_err(ErrorMessage::from)
}

/// The workbook's enum sets — the option lists `enum` / `multiSelect` fields
/// draw from.
///
/// A field's declaration names a set by id and does not carry it, so without
/// this a host can read the declaration and still not know what is allowed —
/// which is the state every headless host was in while the sets lived in the
/// browser's AppData blob.
pub fn get_enum_sets(mgr: &Manager, id: usize) -> Result<Vec<crate::EnumSetInfo>, ErrorMessage> {
    let wb = mgr.workbook(id)?;
    Ok(wb.get_enum_sets())
}

/// The workbook's defined names, each with its definition sheet-qualified.
pub fn get_defined_names(
    mgr: &Manager,
    id: usize,
) -> Result<Vec<crate::DefinedNameInfo>, ErrorMessage> {
    let wb = mgr.workbook(id)?;
    Ok(wb.get_defined_names())
}

/// Every duplicated block row key in the workbook.
///
/// The companion to the engine's write-path refusal: that stops a caller from
/// creating a collision, this finds the ones a file arrived with. Nothing else
/// surfaces them — `BLOCKREF` resolves a repeated key to its first match and
/// says nothing — so a caller has to ask.
pub fn duplicate_block_keys(
    mgr: &Manager,
    id: usize,
) -> Result<Vec<crate::DuplicateBlockKey>, ErrorMessage> {
    let wb = mgr.workbook(id)?;
    Ok(wb.duplicate_block_keys())
}

/// Apply a [`Transaction`], on the temp branch when `transaction.temp`.
///
/// `Err` only when `id` names no workbook. An engine rejection is an `Ok` whose
/// `ActionEffect::status` is `Err`, with nothing applied; see
/// `HandleTransactionParams`.
pub fn handle_transaction(
    mgr: &mut Manager,
    id: usize,
    transaction: Transaction,
) -> Result<ActionEffect, ErrorMessage> {
    // Process all payloads at once
    let payloads_action = PayloadsAction {
        payloads: transaction.payloads,
        undoable: transaction.undoable,
        init: false,
    };

    let wb = mgr.workbook_mut(id)?;
    Ok(if transaction.temp {
        wb.handle_action_in_temp_status(payloads_action)
    } else {
        wb.handle_action(EditAction::Payloads(payloads_action))
    })
}

// ---- Formula helpers (no workbook state) ----------------------------------

/// Whether `f` (after trimming) is `=` followed by something that lexes as a
/// formula. Anything without the leading `=` is `false`.
pub fn formula_check(f: &str) -> bool {
    f.trim().strip_prefix('=').is_some_and(lex_success)
}

/// Tokenize a formula for syntax highlighting; errors when it does not lex.
pub fn get_display_units_of_formula(f: &str) -> Result<FormulaDisplayInfo, ErrorMessage> {
    lex_and_fmt(f)
        .ok_or_else(|| ErrorMessage::from(Error::from(BasicError::InvalidFormula(f.to_string()))))
}