excelerate 0.15.0

Read, write and recalculate spreadsheets: xlsx, xls, ods, csv, html, and a 518-function formula engine
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
//! Cell styles: read as `CellStyle` objects, written as partial patches laid
//! over what a cell already has.

use super::convert::{area_at, at_index, object, rows_of};
#[cfg(feature = "write")]
use super::convert::{array, field, offset};
use super::{Book, js};
use crate::coordinate::{CellRef, Range};
use crate::style::{Border, Color, Style, StyleId};
use std::collections::HashMap;
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
impl Book {
    /// How a cell is painted: number format, font, fill, borders and text
    /// placement, as the file states them.
    ///
    /// A cell the file says nothing about answers with Excel's defaults, which
    /// is what Excel itself shows for it.
    #[wasm_bindgen(js_name = cellStyle, unchecked_return_type = "CellStyle")]
    pub fn cell_style(&self, sheet: usize, address: &str) -> Result<JsValue, JsError> {
        let at = CellRef::parse(address).map_err(js)?;
        Ok(self
            .style_at(sheet, at)?
            .map_or_else(|| style_to_js(&Style::default()), style_to_js))
    }

    /// The same by 1-based row and column.
    #[wasm_bindgen(js_name = cellStyleAt, unchecked_return_type = "CellStyle")]
    pub fn cell_style_at(&self, sheet: usize, row: u32, column: u32) -> Result<JsValue, JsError> {
        let at = at_index(row, column)?;
        Ok(self
            .style_at(sheet, at)?
            .map_or_else(|| style_to_js(&Style::default()), style_to_js))
    }

    /// The styles of a rectangle in one call: each distinct style once, and a
    /// grid of indexes into them. `cellStyle` per cell costs a crossing and a
    /// whole style object per cell; a formatted table of ten thousand cells
    /// usually has a dozen styles.
    #[wasm_bindgen(js_name = getRangeStyles, unchecked_return_type = "RangeStyles")]
    pub fn get_range_styles(&self, sheet: usize, range: &str) -> Result<JsValue, JsError> {
        self.styles_of(sheet, Range::parse(range).map_err(js)?)
    }

    /// The same by numbers, as `getRangeAt` takes them.
    #[wasm_bindgen(js_name = getRangeStylesAt, unchecked_return_type = "RangeStyles")]
    pub fn get_range_styles_at(
        &self,
        sheet: usize,
        row: u32,
        column: u32,
        rows: u32,
        columns: u32,
    ) -> Result<JsValue, JsError> {
        self.styles_of(sheet, area_at(row, column, rows, columns)?)
    }

    /// The runs of a cell's formatted text: `{ text, font }` each, `font`
    /// naming only what the run changes about the cell's font, or `null` for
    /// a run in the cell's own. `null` for a cell without formatted text.
    #[wasm_bindgen(js_name = getRichText, unchecked_return_type = "TextRun[] | null")]
    pub fn get_rich_text(&self, sheet: usize, address: &str) -> Result<JsValue, JsError> {
        self.rich_at(sheet, CellRef::parse(address).map_err(js)?)
    }

    /// The same by 1-based row and column.
    #[wasm_bindgen(js_name = getRichTextAt, unchecked_return_type = "TextRun[] | null")]
    pub fn get_rich_text_at(
        &self,
        sheet: usize,
        row: u32,
        column: u32,
    ) -> Result<JsValue, JsError> {
        self.rich_at(sheet, at_index(row, column)?)
    }
}

impl Book {
    fn rich_at(&self, sheet: usize, at: CellRef) -> Result<JsValue, JsError> {
        use crate::model::CellValue;
        let value = self.sheet_of(sheet)?.get(at).map(|cell| &cell.value);
        let runs = match value {
            Some(CellValue::RichText(runs)) => runs,
            Some(CellValue::Formula {
                cached: Some(cached),
                ..
            }) => match cached.as_ref() {
                CellValue::RichText(runs) => runs,
                _ => return Ok(JsValue::NULL),
            },
            _ => return Ok(JsValue::NULL),
        };
        Ok(super::convert::list(runs, |run| {
            object(&[
                ("text", JsValue::from_str(&run.text)),
                (
                    "font",
                    run.font.as_ref().map_or(JsValue::NULL, run_font_to_js),
                ),
            ])
        }))
    }
}

/// What a run changes about the font, only the parts it names.
pub(super) fn run_font_to_js(font: &crate::style::DiffFont) -> JsValue {
    let mut fields: Vec<(&str, JsValue)> = Vec::new();
    if let Some(name) = &font.name {
        fields.push(("name", JsValue::from_str(name)));
    }
    if let Some(size) = font.size {
        fields.push(("size", JsValue::from_f64(f64::from(size) / 100.0)));
    }
    for (key, flag) in [
        ("bold", font.bold),
        ("italic", font.italic),
        ("strike", font.strike),
    ] {
        if let Some(on) = flag {
            fields.push((key, JsValue::from_bool(on)));
        }
    }
    if let Some(underline) = font.underline {
        fields.push(("underline", JsValue::from_str(underline.as_str())));
    }
    if let Some(color) = &font.color {
        fields.push(("color", color_to_js(color)));
    }
    if let Some(script) = font.script {
        fields.push((
            "script",
            JsValue::from_str(match script {
                crate::style::Script::Superscript => "superscript",
                crate::style::Script::Subscript => "subscript",
                crate::style::Script::Baseline => "baseline",
            }),
        ));
    }
    object(&fields)
}

#[cfg(feature = "write")]
#[wasm_bindgen]
impl Book {
    /// Writes formatted text: runs as `getRichText` returns them, each with
    /// its own text and the part of the font it changes (`font` may be left
    /// out or `null` for the cell's own).
    #[wasm_bindgen(js_name = setRichText)]
    pub fn set_rich_text(
        &mut self,
        sheet: usize,
        address: &str,
        #[wasm_bindgen(unchecked_param_type = "TextRun[]")] runs: &JsValue,
    ) -> Result<(), JsError> {
        let at = CellRef::parse(address).map_err(js)?;
        self.write_rich(sheet, at, runs)
    }

    /// The same by 1-based row and column.
    #[wasm_bindgen(js_name = setRichTextAt)]
    pub fn set_rich_text_at(
        &mut self,
        sheet: usize,
        row: u32,
        column: u32,
        #[wasm_bindgen(unchecked_param_type = "TextRun[]")] runs: &JsValue,
    ) -> Result<(), JsError> {
        self.write_rich(sheet, at_index(row, column)?, runs)
    }
}

#[cfg(feature = "write")]
impl Book {
    fn write_rich(&mut self, sheet: usize, at: CellRef, runs: &JsValue) -> Result<(), JsError> {
        let runs = array(runs, "runs")?
            .iter()
            .map(|run| patch::text_run(&run))
            .collect::<Result<Vec<_>, _>>()?;
        let ws = self.sheet_mut(sheet)?;
        let was_formula = matches!(
            ws.get(at).map(|c| &c.value),
            Some(crate::model::CellValue::Formula { .. })
        );
        ws.set(at, crate::model::CellValue::RichText(runs));
        if was_formula {
            self.note(sheet, &[at]);
        }
        Ok(())
    }
}

#[cfg(feature = "write")]
#[wasm_bindgen]
impl Book {
    /// Paints a cell: a number format, a font, a fill, borders, alignment, or
    /// any part of those.
    ///
    /// The patch is laid over the style the cell has, so a field left out
    /// keeps what was there - `{ font: { bold: true } }` does not reset the
    /// number format. Equal styles share one entry in the workbook's table,
    /// so painting a column costs one style, not one per cell.
    ///
    /// ```js
    /// book.setCellStyle(0, "B2", {
    ///   numberFormat: "#,##0.00",
    ///   font: { bold: true, color: "#FF1F4E79" },
    ///   fill: { pattern: "solid", foreground: "#FFFFE699" },
    ///   alignment: { horizontal: "right" },
    /// });
    /// ```
    #[wasm_bindgen(js_name = setCellStyle)]
    pub fn set_cell_style(
        &mut self,
        sheet: usize,
        address: &str,
        #[wasm_bindgen(unchecked_param_type = "CellStylePatch")] patch: &JsValue,
    ) -> Result<(), JsError> {
        let at = CellRef::parse(address).map_err(js)?;
        self.paint(sheet, Range::new(at, at), patch)
    }

    /// The same by 1-based row and column.
    #[wasm_bindgen(js_name = setCellStyleAt)]
    pub fn set_cell_style_at(
        &mut self,
        sheet: usize,
        row: u32,
        column: u32,
        #[wasm_bindgen(unchecked_param_type = "CellStylePatch")] patch: &JsValue,
    ) -> Result<(), JsError> {
        let at = at_index(row, column)?;
        self.paint(sheet, Range::new(at, at), patch)
    }

    /// The same over a rectangle: `setRangeStyle(0, "A1:D1", { font: { bold:
    /// true } })`. Cells the range covers but the sheet has no value for are
    /// created empty, which is what carries the style.
    #[wasm_bindgen(js_name = setRangeStyle)]
    pub fn set_range_style(
        &mut self,
        sheet: usize,
        range: &str,
        #[wasm_bindgen(unchecked_param_type = "CellStylePatch")] patch: &JsValue,
    ) -> Result<(), JsError> {
        self.paint(sheet, Range::parse(range).map_err(js)?, patch)
    }

    /// Paints a rectangle cell by cell in one call, `at` its top-left corner:
    /// `grid` points into `styles`, each a patch as `setCellStyle` takes it,
    /// and `null` or `-1` leaves its cell alone. The output of
    /// `getRangeStyles` goes back in unchanged, so a block's formatting can be
    /// read, edited in JS and written back - or copied somewhere else.
    #[wasm_bindgen(js_name = setRangeStyles)]
    pub fn set_range_styles(
        &mut self,
        sheet: usize,
        at: &str,
        #[wasm_bindgen(unchecked_param_type = "RangeStylesPatch")] styles: &JsValue,
    ) -> Result<(), JsError> {
        self.paint_grid(sheet, CellRef::parse(at).map_err(js)?, styles)
    }

    /// The same with the corner given as 1-based row and column.
    #[wasm_bindgen(js_name = setRangeStylesAt)]
    pub fn set_range_styles_at(
        &mut self,
        sheet: usize,
        row: u32,
        column: u32,
        #[wasm_bindgen(unchecked_param_type = "RangeStylesPatch")] styles: &JsValue,
    ) -> Result<(), JsError> {
        self.paint_grid(sheet, at_index(row, column)?, styles)
    }
}

impl Book {
    fn styles_of(&self, sheet: usize, area: Range) -> Result<JsValue, JsError> {
        let ws = self.sheet_of(sheet)?;
        let default = Style::default();
        let mut index: HashMap<StyleId, u32> = HashMap::new();
        let styles = js_sys::Array::new();
        let grid = js_sys::Array::new();
        for line in rows_of(area) {
            let row: js_sys::Array = line
                .map(|at| {
                    let id = ws.get(at).map(|cell| cell.style).unwrap_or_default();
                    let pick = *index.entry(id).or_insert_with(|| {
                        styles.push(&style_to_js(
                            self.workbook.styles.get(id).unwrap_or(&default),
                        )) - 1
                    });
                    JsValue::from(pick)
                })
                .collect();
            grid.push(&row);
        }
        Ok(object(&[("styles", styles.into()), ("grid", grid.into())]))
    }

    /// Lays one patch over every cell of an area.
    #[cfg(feature = "write")]
    fn paint(&mut self, sheet: usize, area: Range, patch: &JsValue) -> Result<(), JsError> {
        let cells = rows_of(area).flatten().map(|at| (at, 0)).collect();
        self.restyle(sheet, cells, std::slice::from_ref(patch))
    }

    /// Reads a `RangeStylesPatch` into the cells it paints.
    #[cfg(feature = "write")]
    fn paint_grid(&mut self, sheet: usize, start: CellRef, input: &JsValue) -> Result<(), JsError> {
        let patches: Vec<JsValue> = array(&field(input, "styles").unwrap_or_default(), "`styles`")?
            .iter()
            .collect();
        let grid = array(&field(input, "grid").unwrap_or_default(), "`grid`")?;
        let mut cells = Vec::new();
        for (r, line) in grid.iter().enumerate() {
            for (c, pick) in array(&line, "every row of `grid`")?.iter().enumerate() {
                // `null` and `-1` leave the cell alone.
                let Some(pick) = pick.as_f64().filter(|p| *p >= 0.0) else {
                    continue;
                };
                #[expect(
                    clippy::cast_possible_truncation,
                    clippy::cast_sign_loss,
                    reason = "an index into `styles`, checked against its length below"
                )]
                cells.push((offset(start, r, c)?, pick as usize));
            }
        }
        self.restyle(sheet, cells, &patches)
    }

    /// Gives each cell the style it has with `patches[pick]` laid over it.
    ///
    /// Every style is worked out before any is written, so a bad patch
    /// halfway through leaves the sheet as it was, and each distinct (old
    /// style, patch) pair is interned once.
    #[cfg(feature = "write")]
    fn restyle(
        &mut self,
        sheet: usize,
        cells: Vec<(CellRef, usize)>,
        patches: &[JsValue],
    ) -> Result<(), JsError> {
        let ws = self.sheet_of(sheet)?;
        let old: Vec<StyleId> = cells
            .iter()
            .map(|(at, _)| ws.get(*at).map(|cell| cell.style).unwrap_or_default())
            .collect();
        let mut seen: HashMap<(StyleId, usize), StyleId> = HashMap::new();
        let mut ids = Vec::with_capacity(cells.len());
        for (&(_, pick), old) in cells.iter().zip(old) {
            let id = if let Some(&id) = seen.get(&(old, pick)) {
                id
            } else {
                let patch = patches
                    .get(pick)
                    .ok_or_else(|| JsError::new(&format!("no style {pick} in `styles`")))?;
                if !patch.is_object() {
                    return Err(JsError::new("a style patch is an object"));
                }
                let mut style = self.workbook.styles.get(old).cloned().unwrap_or_default();
                patch::apply(&mut style, patch)?;
                let id = self.workbook.styles.intern(style);
                seen.insert((old, pick), id);
                id
            };
            ids.push(id);
        }
        let ws = self.sheet_mut(sheet)?;
        for ((at, _), id) in cells.into_iter().zip(ids) {
            ws.entry(at).style = id;
        }
        Ok(())
    }
}

/// A colour as JS sees it: the text a reader can act on, or `null` where the
/// file left the choice open.
fn color_to_js(color: &Color) -> JsValue {
    match color {
        Color::Auto => JsValue::NULL,
        Color::Argb(argb) => JsValue::from_str(&format!("#{argb:08X}")),
        Color::Indexed(i) => JsValue::from_str(&format!("indexed:{i}")),
        Color::Theme { id, tint } => JsValue::from_str(&if *tint == 0 {
            format!("theme:{id}")
        } else {
            format!("theme:{id}@{}", f64::from(*tint) / 1_000_000.0)
        }),
    }
}

/// One border side as `{ style, color }`.
fn border_to_js(border: &Border) -> JsValue {
    object(&[
        ("style", JsValue::from_str(border.style.as_str())),
        ("color", color_to_js(&border.color)),
    ])
}

/// The whole style of a cell, shaped as the `CellStyle` declaration says.
fn style_to_js(style: &Style) -> JsValue {
    let (font, fill, borders, alignment) =
        (&style.font, &style.fill, &style.borders, &style.alignment);
    let optional = |text: Option<&str>| text.map_or(JsValue::NULL, JsValue::from_str);
    object(&[
        (
            "numberFormat",
            JsValue::from_str(style.number_format.code()),
        ),
        (
            "font",
            object(&[
                ("name", JsValue::from_str(&font.name)),
                ("size", JsValue::from_f64(f64::from(font.size) / 100.0)),
                ("bold", JsValue::from_bool(font.bold)),
                ("italic", JsValue::from_bool(font.italic)),
                ("underline", JsValue::from_str(font.underline.as_str())),
                ("strike", JsValue::from_bool(font.strike)),
                ("color", color_to_js(&font.color)),
            ]),
        ),
        (
            "fill",
            object(&[
                ("pattern", JsValue::from_str(fill.pattern.as_str())),
                ("foreground", color_to_js(&fill.foreground)),
                ("background", color_to_js(&fill.background)),
            ]),
        ),
        (
            "borders",
            object(&[
                ("left", border_to_js(&borders.left)),
                ("right", border_to_js(&borders.right)),
                ("top", border_to_js(&borders.top)),
                ("bottom", border_to_js(&borders.bottom)),
            ]),
        ),
        (
            "alignment",
            object(&[
                ("horizontal", optional(alignment.horizontal.as_str())),
                ("vertical", optional(alignment.vertical.as_str())),
                ("wrapText", JsValue::from_bool(alignment.wrap_text)),
                ("shrinkToFit", JsValue::from_bool(alignment.shrink_to_fit)),
                ("indent", JsValue::from_f64(f64::from(alignment.indent))),
                (
                    "textRotation",
                    JsValue::from_f64(f64::from(alignment.text_rotation)),
                ),
            ]),
        ),
    ])
}

/// Reading a `CellStylePatch`: every field is optional, and one left out
/// keeps what the cell had.
#[cfg(feature = "write")]
pub(super) mod patch {
    use super::super::convert::field;
    use crate::style::{
        Alignment, BorderStyle, Borders, Color, Fill, Font, HorizontalAlign, NumberFormat, Pattern,
        Style, Underline, VerticalAlign,
    };
    use wasm_bindgen::prelude::*;

    /// Lays a patch over a style.
    pub(super) fn apply(style: &mut Style, patch: &JsValue) -> Result<(), JsError> {
        if let Some(code) = field(patch, "numberFormat") {
            let code = text(&code, "a number format")?;
            style.number_format = if code == crate::style::format::GENERAL {
                NumberFormat::General
            } else {
                NumberFormat::Custom(code)
            };
        }
        if let Some(patch) = field(patch, "font") {
            font(&mut style.font, &patch)?;
        }
        if let Some(patch) = field(patch, "fill") {
            fill(&mut style.fill, &patch)?;
        }
        if let Some(patch) = field(patch, "borders") {
            borders(&mut style.borders, &patch)?;
        }
        if let Some(patch) = field(patch, "alignment") {
            alignment(&mut style.alignment, &patch)?;
        }
        Ok(())
    }

    fn font(font: &mut Font, patch: &JsValue) -> Result<(), JsError> {
        if let Some(name) = field(patch, "name") {
            font.name = text(&name, "a font name")?;
        }
        if let Some(size) = field(patch, "size") {
            #[expect(
                clippy::cast_possible_truncation,
                clippy::cast_sign_loss,
                reason = "a font size in hundredths of a point is a small positive number"
            )]
            {
                font.size = (number(&size, "a font size")? * 100.0).round() as u32;
            }
        }
        flag(patch, "bold", &mut font.bold);
        flag(patch, "italic", &mut font.italic);
        flag(patch, "strike", &mut font.strike);
        if let Some(underline) = field(patch, "underline") {
            font.underline = Underline::parse(&text(&underline, "an underline")?);
        }
        if let Some(color) = field(patch, "color") {
            font.color = color_from_js(&color)?;
        }
        Ok(())
    }

    fn fill(fill: &mut Fill, patch: &JsValue) -> Result<(), JsError> {
        if let Some(pattern) = field(patch, "pattern") {
            fill.pattern = Pattern::parse(&text(&pattern, "a fill pattern")?);
        }
        if let Some(color) = field(patch, "foreground") {
            fill.foreground = color_from_js(&color)?;
        }
        if let Some(color) = field(patch, "background") {
            fill.background = color_from_js(&color)?;
        }
        Ok(())
    }

    fn borders(borders: &mut Borders, patch: &JsValue) -> Result<(), JsError> {
        for (key, side) in [
            ("left", &mut borders.left),
            ("right", &mut borders.right),
            ("top", &mut borders.top),
            ("bottom", &mut borders.bottom),
        ] {
            let Some(patch) = field(patch, key) else {
                continue;
            };
            if let Some(kind) = field(&patch, "style") {
                side.style = BorderStyle::parse(&text(&kind, "a border style")?);
            }
            if let Some(color) = field(&patch, "color") {
                side.color = color_from_js(&color)?;
            }
        }
        Ok(())
    }

    fn alignment(alignment: &mut Alignment, patch: &JsValue) -> Result<(), JsError> {
        // `null` gives the placement back to the default.
        if let Some(horizontal) = field(patch, "horizontal") {
            alignment.horizontal = horizontal
                .as_string()
                .map_or(HorizontalAlign::General, |h| HorizontalAlign::parse(&h));
        }
        if let Some(vertical) = field(patch, "vertical") {
            alignment.vertical = vertical
                .as_string()
                .map_or(VerticalAlign::Bottom, |v| VerticalAlign::parse(&v));
        }
        flag(patch, "wrapText", &mut alignment.wrap_text);
        flag(patch, "shrinkToFit", &mut alignment.shrink_to_fit);
        #[expect(
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss,
            reason = "indent steps and a rotation in degrees are small positive numbers"
        )]
        {
            if let Some(indent) = field(patch, "indent") {
                alignment.indent = number(&indent, "an indent")? as u32;
            }
            if let Some(rotation) = field(patch, "textRotation") {
                alignment.text_rotation = number(&rotation, "a text rotation")? as u32;
            }
        }
        Ok(())
    }

    /// One run as `setRichText` takes it: `{ text, font? }`.
    pub(super) fn text_run(value: &JsValue) -> Result<crate::model::TextRun, JsError> {
        let text = field(value, "text")
            .ok_or_else(|| JsError::new("a run has text"))
            .and_then(|t| text(&t, "a run's text"))?;
        let font = match field(value, "font") {
            Some(patch) if !patch.is_null() => Some(run_font(&patch)?),
            _ => None,
        };
        Ok(crate::model::TextRun { text, font })
    }

    /// The part of a font a run changes: only the fields the object names.
    pub(in crate::wasm) fn run_font(patch: &JsValue) -> Result<crate::style::DiffFont, JsError> {
        use crate::style::{DiffFont, Script};
        let mut font = DiffFont::default();
        if let Some(name) = field(patch, "name") {
            font.name = Some(text(&name, "a font name")?);
        }
        if let Some(size) = field(patch, "size") {
            let points = number(&size, "a font size")?;
            if !(points > 0.0 && points < 4096.0) {
                return Err(JsError::new("a font size is between 0 and 4096 points"));
            }
            #[expect(
                clippy::cast_possible_truncation,
                clippy::cast_sign_loss,
                reason = "bounded to a positive number of points above"
            )]
            {
                font.size = Some((points * 100.0).round() as u32);
            }
        }
        for (key, slot) in [
            ("bold", &mut font.bold),
            ("italic", &mut font.italic),
            ("strike", &mut font.strike),
        ] {
            if let Some(value) = field(patch, key) {
                *slot = Some(value.is_truthy());
            }
        }
        if let Some(underline) = field(patch, "underline") {
            font.underline = Some(Underline::parse(&text(&underline, "an underline")?));
        }
        if let Some(color) = field(patch, "color") {
            font.color = Some(color_from_js(&color)?);
        }
        if let Some(script) = field(patch, "script") {
            font.script = Some(match text(&script, "a script")?.as_str() {
                "superscript" => Script::Superscript,
                "subscript" => Script::Subscript,
                _ => Script::Baseline,
            });
        }
        Ok(font)
    }

    /// A colour as the JS side spells it: `#AARRGGBB` (or `#RRGGBB`),
    /// `indexed:N`, `theme:N` with an optional `@tint`, or `null` for the one
    /// the file leaves open.
    fn color_from_js(value: &JsValue) -> Result<Color, JsError> {
        if value.is_null() {
            return Ok(Color::Auto);
        }
        let text = value
            .as_string()
            .ok_or_else(|| JsError::new("a colour is a string or null"))?;
        if let Some(index) = text.strip_prefix("indexed:") {
            return index
                .parse()
                .map(Color::Indexed)
                .map_err(|_| JsError::new("indexed:N takes a number"));
        }
        if let Some(rest) = text.strip_prefix("theme:") {
            let (id, tint) = match rest.split_once('@') {
                Some((id, tint)) => {
                    let tint: f64 = tint
                        .parse()
                        .map_err(|_| JsError::new("a theme tint is a number between -1 and 1"))?;
                    #[expect(
                        clippy::cast_possible_truncation,
                        reason = "a tint is between -1 and 1, and the file stores it in millionths"
                    )]
                    (id, (tint * 1_000_000.0).round() as i32)
                }
                None => (rest, 0),
            };
            return id
                .parse()
                .map(|id| Color::Theme { id, tint })
                .map_err(|_| JsError::new("theme:N takes a number"));
        }
        // Written as `#AARRGGBB`, which is how `cellStyle` reads it back; the
        // file itself stores the eight digits alone, so both forms are taken.
        Color::from_argb_str(text.strip_prefix('#').unwrap_or(&text))
            .ok_or_else(|| JsError::new("a colour is #AARRGGBB, indexed:N, theme:N or null"))
    }

    /// Sets a flag the patch names, by JS truthiness.
    fn flag(patch: &JsValue, key: &str, to: &mut bool) {
        if let Some(value) = field(patch, key) {
            *to = value.is_truthy();
        }
    }

    /// A string a patch states, rejected if it is not one.
    pub(in crate::wasm) fn text(value: &JsValue, what: &str) -> Result<String, JsError> {
        value
            .as_string()
            .ok_or_else(|| JsError::new(&format!("{what} is a string")))
    }

    /// A number a patch states, rejected if it is not one.
    pub(in crate::wasm) fn number(value: &JsValue, what: &str) -> Result<f64, JsError> {
        value
            .as_f64()
            .ok_or_else(|| JsError::new(&format!("{what} is a number")))
    }
}