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
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
//! What a sheet holds besides cells - notes, links, tables, drawings, rules,
//! pivots - and the names the workbook defines.

use super::Book;
use super::convert::{count, list, object, opt_count, opt_str, ranges_to_js};
#[cfg(feature = "write")]
use super::js;
use super::style::run_font_to_js;
#[cfg(feature = "write")]
use crate::coordinate::{CellRef, Col, Range};
use crate::model::chart::{
    ChartColor, ColorTransform, Fill, GradientPath, LineFormat, ShapeFormat,
};
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
impl Book {
    /// The notes on a sheet, in address order.
    #[wasm_bindgen(unchecked_return_type = "SheetComment[]")]
    pub fn comments(&self, sheet: usize) -> Result<JsValue, JsError> {
        Ok(list(&self.sheet_of(sheet)?.comments, |(at, comment)| {
            object(&[
                ("address", JsValue::from_str(&at.to_string())),
                ("author", JsValue::from_str(&comment.author)),
                ("text", JsValue::from_str(&comment.plain_text())),
            ])
        }))
    }

    /// The hyperlinks of a sheet. `external` tells a URL from a jump inside
    /// the workbook.
    #[wasm_bindgen(unchecked_return_type = "SheetHyperlink[]")]
    pub fn hyperlinks(&self, sheet: usize) -> Result<JsValue, JsError> {
        use crate::model::LinkTarget;
        Ok(list(&self.sheet_of(sheet)?.hyperlinks, |link| {
            let (target, external) = match &link.target {
                LinkTarget::Inside(to) => (to, false),
                LinkTarget::Outside(to) => (to, true),
            };
            object(&[
                ("range", JsValue::from_str(&link.range.to_string())),
                ("target", JsValue::from_str(target)),
                ("external", JsValue::from_bool(external)),
                ("display", opt_str(link.display.as_deref())),
                ("tooltip", opt_str(link.tooltip.as_deref())),
            ])
        }))
    }

    /// The tables of a sheet: what a structured reference like `Sales[Amount]`
    /// names.
    #[wasm_bindgen(unchecked_return_type = "SheetTable[]")]
    pub fn tables(&self, sheet: usize) -> Result<JsValue, JsError> {
        Ok(list(&self.sheet_of(sheet)?.tables, |table| {
            object(&[
                ("name", JsValue::from_str(&table.name)),
                ("displayName", JsValue::from_str(&table.display_name)),
                ("range", JsValue::from_str(&table.range.to_string())),
                ("headerRowCount", opt_count(table.header_row_count)),
                ("totalsRowCount", opt_count(table.totals_row_count)),
                (
                    "columns",
                    list(&table.columns, |column| JsValue::from_str(&column.name)),
                ),
            ])
        }))
    }

    /// The charts on a sheet. `kinds` names the plots drawn in each -
    /// `barChart`, `lineChart` - and a combination chart has more than one.
    #[wasm_bindgen(unchecked_return_type = "SheetChart[]")]
    pub fn charts(&self, sheet: usize) -> Result<JsValue, JsError> {
        Ok(list(&self.sheet_of(sheet)?.charts, |chart| {
            let title = chart
                .title
                .as_ref()
                .and_then(|t| t.text.as_ref())
                .and_then(crate::model::chart::ChartText::shown);
            object(&[
                ("name", JsValue::from_str(&chart.name)),
                ("title", opt_str(title)),
                (
                    "kinds",
                    list(&chart.plots, |plot| JsValue::from_str(plot.kind.element())),
                ),
                (
                    "seriesCount",
                    count(chart.plots.iter().map(|p| p.series.len()).sum()),
                ),
                ("anchor", anchor_to_js(&chart.anchor)),
                ("format", self.format_to_js(chart.format.as_ref())),
                ("plotFormat", self.format_to_js(chart.plot_format.as_ref())),
            ])
        }))
    }

    /// The pictures on a sheet, without their bytes: `imageData` fetches those
    /// for the one that is wanted.
    #[wasm_bindgen(unchecked_return_type = "SheetImage[]")]
    pub fn images(&self, sheet: usize) -> Result<JsValue, JsError> {
        Ok(list(&self.sheet_of(sheet)?.images, |image| {
            object(&[
                ("name", JsValue::from_str(&image.name)),
                ("description", JsValue::from_str(&image.description)),
                ("format", JsValue::from_str(image.format.extension())),
                ("byteLength", count(image.data.len())),
                ("anchor", anchor_to_js(&image.anchor)),
            ])
        }))
    }

    /// The bytes of one picture, by its position in `images`.
    #[wasm_bindgen(js_name = imageData)]
    pub fn image_data(&self, sheet: usize, index: usize) -> Result<Vec<u8>, JsError> {
        self.sheet_of(sheet)?
            .images
            .get(index)
            .map(|image| image.data.clone())
            .ok_or_else(|| JsError::new("no such image"))
    }

    /// The drawn shapes of a sheet, text and all, with the look Excel shows:
    /// fill, outline and font are the shape's own with its style filling in
    /// the rest, colours resolved through the workbook theme.
    #[wasm_bindgen(unchecked_return_type = "SheetShape[]")]
    pub fn shapes(&self, sheet: usize) -> Result<JsValue, JsError> {
        Ok(list(&self.sheet_of(sheet)?.shapes, |shape| {
            object(&[
                ("name", JsValue::from_str(&shape.name)),
                ("description", JsValue::from_str(&shape.description)),
                ("geometry", opt_str(shape.geometry.as_deref())),
                ("text", JsValue::from_str(&shape.text)),
                ("anchor", anchor_to_js(&shape.anchor)),
                (
                    "rotation",
                    JsValue::from_f64(f64::from(shape.rotation) / 60_000.0),
                ),
                ("flipH", JsValue::from_bool(shape.flip_h)),
                ("flipV", JsValue::from_bool(shape.flip_v)),
                ("fill", self.fill_to_js(&shape.effective_fill())),
                ("line", self.line_to_js(&shape.effective_line())),
                ("font", run_font_to_js(&shape.effective_font())),
            ])
        }))
    }

    /// The names the workbook defines: what `=Total` and `Print_Area` stand
    /// for. `sheet` is set on a name local to one sheet.
    #[wasm_bindgen(js_name = definedNames, unchecked_return_type = "WorkbookName[]")]
    #[must_use]
    pub fn defined_names(&self) -> JsValue {
        list(&self.workbook.defined_names, |name| {
            object(&[
                ("name", JsValue::from_str(&name.name)),
                ("formula", JsValue::from_str(&name.formula)),
                ("sheet", name.sheet.map_or(JsValue::NULL, count)),
                ("hidden", JsValue::from_bool(name.hidden)),
            ])
        })
    }

    /// The rules limiting what cells accept: the dropdown lists, the ranges,
    /// the dates.
    #[wasm_bindgen(js_name = dataValidations, unchecked_return_type = "SheetValidation[]")]
    pub fn data_validations(&self, sheet: usize) -> Result<JsValue, JsError> {
        Ok(list(&self.sheet_of(sheet)?.data_validations, |rule| {
            object(&[
                ("sqref", ranges_to_js(&rule.sqref)),
                ("type", JsValue::from_str(rule.kind.as_str())),
                ("operator", JsValue::from_str(rule.operator.as_str())),
                ("formula1", JsValue::from_str(&rule.formula1)),
                ("formula2", JsValue::from_str(&rule.formula2)),
                ("allowBlank", JsValue::from_bool(rule.allow_blank)),
                ("showDropDown", JsValue::from_bool(!rule.hide_drop_down)),
            ])
        }))
    }

    /// The conditional formatting of a sheet, block by block. The formatting
    /// each rule applies is not modelled here - it lives in the workbook's
    /// differential styles - but what the rule tests is.
    #[wasm_bindgen(
        js_name = conditionalFormats,
        unchecked_return_type = "SheetConditionalFormat[]"
    )]
    pub fn conditional_formats(&self, sheet: usize) -> Result<JsValue, JsError> {
        Ok(list(&self.sheet_of(sheet)?.conditional_formats, |block| {
            let rules = list(&block.rules, |rule| {
                object(&[
                    ("type", JsValue::from_str(rule.kind.as_str())),
                    ("priority", JsValue::from_f64(f64::from(rule.priority))),
                    (
                        "operator",
                        opt_str(rule.operator.map(crate::model::CfOperator::as_str)),
                    ),
                    ("formulas", list(&rule.formulas, JsValue::from)),
                    ("text", opt_str(rule.text.as_deref())),
                ])
            });
            object(&[("sqref", ranges_to_js(&block.sqref)), ("rules", rules)])
        }))
    }

    /// The autofilter over a sheet, or `undefined` when it has none. What the
    /// filter hides is a property of each row - see `rowHidden`.
    #[wasm_bindgen(js_name = autoFilter, unchecked_return_type = "SheetAutoFilter | undefined")]
    pub fn auto_filter(&self, sheet: usize) -> Result<JsValue, JsError> {
        use crate::model::autofilter::ColumnFilter;
        let Some(filter) = &self.sheet_of(sheet)?.auto_filter else {
            return Ok(JsValue::UNDEFINED);
        };
        let columns = list(&filter.columns, |column| {
            let kind = match &column.filter {
                Some(ColumnFilter::Values { .. }) => "values",
                Some(ColumnFilter::Custom { .. }) => "custom",
                Some(ColumnFilter::Dynamic { .. }) => "dynamic",
                Some(ColumnFilter::Top10 { .. }) => "top10",
                Some(ColumnFilter::Color { .. }) => "color",
                Some(ColumnFilter::Icon { .. }) => "icon",
                None => "none",
            };
            object(&[
                ("colId", JsValue::from_f64(f64::from(column.col_id))),
                ("kind", JsValue::from_str(kind)),
            ])
        });
        Ok(object(&[
            ("range", JsValue::from_str(&filter.range.to_string())),
            ("columns", columns),
        ]))
    }

    /// The pivot reports laid out on a sheet. The numbers they show are cells
    /// like any others; this says where a report sits and how wide its axes
    /// are.
    #[wasm_bindgen(js_name = pivotTables, unchecked_return_type = "SheetPivotTable[]")]
    pub fn pivot_tables(&self, sheet: usize) -> Result<JsValue, JsError> {
        Ok(list(&self.sheet_of(sheet)?.pivot_tables, |pivot| {
            object(&[
                ("name", JsValue::from_str(&pivot.name)),
                (
                    "location",
                    opt_str(pivot.location.map(|r| r.to_string()).as_deref()),
                ),
                ("cacheId", JsValue::from_f64(f64::from(pivot.cache_id))),
                ("rowFields", count(pivot.row_fields.len())),
                ("columnFields", count(pivot.column_fields.len())),
                ("valueFields", count(pivot.data_fields.len())),
            ])
        }))
    }

    /// The array formulas of a sheet, as the areas they cover: `["B2:B4"]`.
    /// The formula itself is on the top left cell of each.
    #[wasm_bindgen(js_name = arrayFormulas)]
    pub fn array_formulas(&self, sheet: usize) -> Result<Vec<String>, JsError> {
        Ok(self
            .sheet_of(sheet)?
            .array_formulas
            .iter()
            .map(ToString::to_string)
            .collect())
    }

    /// The other workbooks this one reads, in the order `[1]Sheet1!A1` counts
    /// them. A path is `undefined` where the file does not name one.
    #[wasm_bindgen(js_name = externalBooks)]
    #[must_use]
    pub fn external_books(&self) -> Vec<JsValue> {
        self.workbook
            .external
            .iter()
            .map(|book| opt_str(book.path.as_deref()))
            .collect()
    }
}

#[cfg(feature = "write")]
#[wasm_bindgen]
impl Book {
    /// Puts a note on a cell, replacing any note already there.
    #[wasm_bindgen(js_name = setComment)]
    pub fn set_comment(
        &mut self,
        sheet: usize,
        address: &str,
        author: &str,
        text: &str,
    ) -> Result<(), JsError> {
        let at = CellRef::parse(address).map_err(js)?;
        let comment = crate::model::Comment {
            author: author.to_owned(),
            text: vec![crate::model::TextRun {
                text: text.to_owned(),
                font: None,
            }],
            ..crate::model::Comment::default()
        };
        self.sheet_mut(sheet)?.comments.insert(at, comment);
        Ok(())
    }

    /// Takes a note off a cell. Answers whether there was one.
    #[wasm_bindgen(js_name = removeComment)]
    pub fn remove_comment(&mut self, sheet: usize, address: &str) -> Result<bool, JsError> {
        let at = CellRef::parse(address).map_err(js)?;
        Ok(self.sheet_mut(sheet)?.comments.remove(&at).is_some())
    }

    /// Puts a link over a cell or a block of them.
    ///
    /// `target` is a URL or a file path unless `inside` is true, and then it
    /// is a place in this workbook: `'Sheet 2'!A1`.
    #[wasm_bindgen(js_name = setHyperlink)]
    pub fn set_hyperlink(
        &mut self,
        sheet: usize,
        range: &str,
        target: &str,
        inside: Option<bool>,
        display: Option<String>,
        tooltip: Option<String>,
    ) -> Result<(), JsError> {
        use crate::model::{Hyperlink, LinkTarget};
        let area = Range::parse(range).map_err(js)?;
        let target = if inside.unwrap_or(false) {
            LinkTarget::Inside(target.to_owned())
        } else {
            LinkTarget::Outside(target.to_owned())
        };
        let links = &mut self.sheet_mut(sheet)?.hyperlinks;
        links.retain(|link| link.range != area);
        links.push(Hyperlink {
            range: area,
            target,
            display,
            tooltip,
        });
        Ok(())
    }

    /// Takes the link off a range. Answers whether there was one.
    #[wasm_bindgen(js_name = removeHyperlink)]
    pub fn remove_hyperlink(&mut self, sheet: usize, range: &str) -> Result<bool, JsError> {
        let area = Range::parse(range).map_err(js)?;
        let links = &mut self.sheet_mut(sheet)?.hyperlinks;
        let before = links.len();
        links.retain(|link| link.range != area);
        Ok(links.len() != before)
    }

    /// Draws a table over a range, the thing `Sales[Amount]` names.
    ///
    /// The first row of the range is the header unless `headerRow` says
    /// otherwise, and the column names are read from it. The name must be
    /// unique in the workbook, as Excel requires.
    #[wasm_bindgen(js_name = addTable)]
    pub fn add_table(
        &mut self,
        sheet: usize,
        name: &str,
        range: &str,
        header_row: Option<bool>,
    ) -> Result<(), JsError> {
        use crate::model::table::{Table, TableColumn, TableStyle};
        let area = Range::parse(range).map_err(js)?;
        let taken = self
            .workbook
            .sheets()
            .iter()
            .flat_map(|ws| &ws.tables)
            .any(|t| t.display_name.eq_ignore_ascii_case(name));
        if taken {
            return Err(JsError::new(
                "a table of that name is already in the workbook",
            ));
        }
        let header = header_row.unwrap_or(true);
        let ws = self.sheet_mut(sheet)?;
        let columns = (area.start.col.index()..=area.end.col.index())
            .zip(1..)
            .map(|(col, id)| {
                let named = Col::new(col)
                    .filter(|_| header)
                    .and_then(|col| ws.get(CellRef::new(col, area.start.row)))
                    .and_then(|cell| cell.value.plain_text())
                    .filter(|text| !text.is_empty());
                TableColumn {
                    id,
                    name: named.unwrap_or_else(|| format!("Column{id}")),
                    totals_row_function: None,
                    totals_row_label: None,
                    calculated_formula: None,
                }
            })
            .collect();
        let id = u32::try_from(ws.tables.len() + 1).unwrap_or(u32::MAX);
        ws.tables.push(Table {
            id,
            name: name.to_owned(),
            display_name: name.to_owned(),
            range: area,
            header_row_count: Some(u32::from(header)),
            totals_row_count: None,
            auto_filter: header.then(|| crate::model::AutoFilter::new(area)),
            sort_state: None,
            columns,
            style: Some(TableStyle::default()),
            extensions: None,
        });
        Ok(())
    }

    /// Filters a table by one of its columns, named by its header or
    /// numbered from 1, and hides the data rows the table's criteria reject,
    /// as Excel does. `null` takes the column's criterion off.
    ///
    /// ```js
    /// book.setTableFilter("Sales", "Region", { values: ["South", "West"] });
    /// book.setTableFilter("Sales", "Amount", { custom: [{ op: ">", value: 100 }] });
    /// book.setTableFilter("Sales", 3, { top: 5 });          // or { bottom: 10, percent: true }
    /// ```
    ///
    /// `values` keeps a row whose cell shows one of them, `blank: true` the
    /// empty ones too; `custom` takes one or two comparisons (`=`, `<>`, `>`,
    /// `>=`, `<`, `<=`; `*` and `?` in `=` and `<>`), joined by `or` unless
    /// `and` is set. Criteria on several columns all have to hold.
    #[wasm_bindgen(js_name = setTableFilter)]
    pub fn set_table_filter(
        &mut self,
        name: &str,
        #[wasm_bindgen(unchecked_param_type = "string | number")] column: &JsValue,
        #[wasm_bindgen(unchecked_param_type = "TableFilter | null")] criteria: &JsValue,
    ) -> Result<(), JsError> {
        let columns = self
            .workbook
            .sheets()
            .iter()
            .flat_map(|ws| &ws.tables)
            .find(|t| {
                t.display_name.eq_ignore_ascii_case(name) || t.name.eq_ignore_ascii_case(name)
            })
            .map(|t| t.columns.iter().map(|c| c.name.clone()).collect::<Vec<_>>())
            .ok_or_else(|| JsError::new(&format!("no table called {name}")))?;
        let offset = if let Some(header) = column.as_string() {
            columns
                .iter()
                .position(|c| c.to_lowercase() == header.to_lowercase())
                .ok_or_else(|| JsError::new(&format!("table {name} has no column {header:?}")))?
        } else {
            column
                .as_f64()
                .filter(|n| n.fract() == 0.0 && *n >= 1.0 && *n <= 16_384.0)
                .map(|n| {
                    #[expect(
                        clippy::cast_possible_truncation,
                        clippy::cast_sign_loss,
                        reason = "a whole column number checked just above"
                    )]
                    let n = n as usize;
                    n - 1
                })
                .ok_or_else(|| JsError::new("a column is a header or a number from 1"))?
        };
        let filter = if criteria.is_null() || criteria.is_undefined() {
            None
        } else {
            Some(table_filter_of(criteria)?)
        };
        let offset = u32::try_from(offset).map_err(|_| JsError::new("no such column"))?;
        crate::edit::filter_table(&mut self.workbook, name, offset, filter).map_err(js)
    }

    /// Removes a table by name. Answers whether there was one.
    #[wasm_bindgen(js_name = removeTable)]
    pub fn remove_table(&mut self, sheet: usize, name: &str) -> Result<bool, JsError> {
        let tables = &mut self.sheet_mut(sheet)?.tables;
        let before = tables.len();
        tables.retain(|table| !table.display_name.eq_ignore_ascii_case(name));
        Ok(tables.len() != before)
    }

    /// Defines a name, replacing one of the same name. `formula` is what it
    /// stands for - `Sheet1!$A$1:$A$9` or a constant - and `sheet` makes the
    /// name local to that sheet instead of the workbook.
    #[wasm_bindgen(js_name = setDefinedName)]
    pub fn set_defined_name(
        &mut self,
        name: &str,
        formula: &str,
        sheet: Option<usize>,
    ) -> Result<(), JsError> {
        if name.is_empty() {
            return Err(JsError::new("a defined name is not empty"));
        }
        if let Some(index) = sheet {
            self.sheet_of(index)?;
        }
        self.remove_defined_name(name, sheet);
        self.workbook.defined_names.push(crate::model::DefinedName {
            name: name.to_owned(),
            sheet,
            formula: formula.to_owned(),
            hidden: false,
        });
        self.forget_dependencies();
        Ok(())
    }

    /// Removes a defined name. Answers whether there was one.
    #[wasm_bindgen(js_name = removeDefinedName)]
    pub fn remove_defined_name(&mut self, name: &str, sheet: Option<usize>) -> bool {
        let names = &mut self.workbook.defined_names;
        let before = names.len();
        names.retain(|existing| !(existing.name == name && existing.sheet == sheet));
        let removed = names.len() != before;
        if removed {
            self.forget_dependencies();
        }
        removed
    }
}

/// Where a drawing object sits, as `ObjectAnchor`. An absolute anchor is at a
/// point on the sheet rather than at a cell, so it names no row or column.
fn anchor_to_js(anchor: &crate::model::chart::Anchor) -> JsValue {
    use crate::model::chart::Anchor;
    let at = match anchor {
        Anchor::TwoCell { from, .. } | Anchor::OneCell { from, .. } => Some(from),
        Anchor::Absolute { .. } => None,
    };
    let kind = match anchor {
        Anchor::TwoCell { .. } => "twoCell",
        Anchor::OneCell { .. } => "oneCell",
        Anchor::Absolute { .. } => "absolute",
    };
    object(&[
        ("kind", JsValue::from_str(kind)),
        ("row", opt_count(at.map(|m| m.row.one_based()))),
        ("column", opt_count(at.map(|m| m.col.one_based()))),
    ])
}

/// The look of drawing objects in JS terms. A `DrawingML` colour is resolved
/// to `#AARRGGBB` through the workbook theme, since outside the file a theme
/// colour with its transforms means nothing; `null` for one no theme defines.
impl Book {
    fn chart_color_to_js(&self, color: &ChartColor) -> JsValue {
        color
            .resolve(self.workbook.theme.as_deref())
            .map_or(JsValue::NULL, |rgb| {
                // The opacity, the one transform `resolve` leaves alone.
                let alpha = color.transforms.iter().rev().find_map(|t| match t {
                    ColorTransform::Alpha(a) => {
                        Some((a.clamp(&0, &100_000) * 255 + 50_000) / 100_000)
                    }
                    _ => None,
                });
                JsValue::from_str(&format!("#{:02X}{rgb:06X}", alpha.unwrap_or(0xFF)))
            })
    }

    fn opt_color(&self, color: Option<&ChartColor>) -> JsValue {
        color.map_or(JsValue::NULL, |c| self.chart_color_to_js(c))
    }

    /// `{ type, ... }`: `none`, `solid` with `color`, `gradient` with `stops`
    /// (`position` in percent), `angle` in degrees and `path`, `pattern` with
    /// `preset`, `foreground` and `background`, or `other` for a picture.
    fn fill_to_js(&self, fill: &Fill) -> JsValue {
        let kind = |name: &str| ("type", JsValue::from_str(name));
        match fill {
            Fill::None => object(&[kind("none")]),
            Fill::Solid(color) => {
                object(&[kind("solid"), ("color", self.chart_color_to_js(color))])
            }
            Fill::Gradient { stops, angle, path } => object(&[
                kind("gradient"),
                (
                    "stops",
                    list(stops, |stop| {
                        object(&[
                            (
                                "position",
                                JsValue::from_f64(f64::from(stop.position) / 1000.0),
                            ),
                            ("color", self.chart_color_to_js(&stop.color)),
                        ])
                    }),
                ),
                (
                    "angle",
                    angle.map_or(JsValue::NULL, |a| {
                        JsValue::from_f64(f64::from(a) / 60_000.0)
                    }),
                ),
                ("path", opt_str(path.map(GradientPath::as_str))),
            ]),
            Fill::Pattern {
                preset,
                foreground,
                background,
            } => object(&[
                kind("pattern"),
                ("preset", opt_str(preset.as_deref())),
                ("foreground", self.opt_color(foreground.as_ref())),
                ("background", self.opt_color(background.as_ref())),
            ]),
            Fill::Other => object(&[kind("other")]),
        }
    }

    /// `{ fill, width }`, `width` in points; `null` where the file is silent.
    fn line_to_js(&self, line: &LineFormat) -> JsValue {
        object(&[
            (
                "fill",
                line.fill
                    .as_ref()
                    .map_or(JsValue::NULL, |f| self.fill_to_js(f)),
            ),
            (
                "width",
                line.width.map_or(JsValue::NULL, |w| {
                    JsValue::from_f64(f64::from(w) / 12_700.0)
                }),
            ),
        ])
    }

    /// `{ fill, line }` as the element states them, or `null` for an area
    /// that leaves its look to the chart style.
    fn format_to_js(&self, format: Option<&ShapeFormat>) -> JsValue {
        format.map_or(JsValue::NULL, |format| {
            object(&[
                (
                    "fill",
                    format
                        .fill
                        .as_ref()
                        .map_or(JsValue::NULL, |f| self.fill_to_js(f)),
                ),
                (
                    "line",
                    format
                        .line
                        .as_ref()
                        .map_or(JsValue::NULL, |l| self.line_to_js(l)),
                ),
            ])
        })
    }
}

/// Reads the criteria of `setTableFilter`.
#[cfg(feature = "write")]
fn table_filter_of(criteria: &JsValue) -> Result<crate::model::autofilter::ColumnFilter, JsError> {
    use super::convert::{array, field};
    use crate::model::autofilter::{ColumnFilter, CustomFilter, FilterOperator};
    // A number is written the way JS prints it, which is how a General cell
    // shows it.
    let spelled = |v: &JsValue| {
        v.as_string()
            .or_else(|| v.as_f64().map(|n| n.to_string()))
            .ok_or_else(|| JsError::new("a filter value is a string or a number"))
    };
    let flag = |key: &str| field(criteria, key).is_some_and(|v| v.is_truthy());
    if let Some(values) = field(criteria, "values") {
        return Ok(ColumnFilter::Values {
            blank: flag("blank"),
            values: array(&values, "values")?
                .iter()
                .map(|v| spelled(&v))
                .collect::<Result<_, _>>()?,
            date_groups: Vec::new(),
        });
    }
    if let Some(rules) = field(criteria, "custom") {
        let rules = array(&rules, "custom")?
            .iter()
            .map(|rule| {
                let op = field(&rule, "op")
                    .and_then(|o| o.as_string())
                    .unwrap_or_else(|| "=".into());
                let operator = match op.as_str() {
                    "=" => FilterOperator::Equal,
                    "<>" | "!=" => FilterOperator::NotEqual,
                    ">" => FilterOperator::GreaterThan,
                    ">=" => FilterOperator::GreaterThanOrEqual,
                    "<" => FilterOperator::LessThan,
                    "<=" => FilterOperator::LessThanOrEqual,
                    other => {
                        return Err(JsError::new(&format!(
                            "a comparison is =, <>, >, >=, < or <=, not {other:?}"
                        )));
                    }
                };
                let value = field(&rule, "value")
                    .ok_or_else(|| JsError::new("a comparison has a value"))?;
                Ok(CustomFilter {
                    operator,
                    value: spelled(&value)?,
                })
            })
            .collect::<Result<Vec<_>, JsError>>()?;
        if rules.is_empty() || rules.len() > 2 {
            return Err(JsError::new("custom takes one or two comparisons"));
        }
        return Ok(ColumnFilter::Custom {
            and: flag("and"),
            rules,
        });
    }
    for (key, top) in [("top", true), ("bottom", false)] {
        if let Some(count) = field(criteria, key) {
            let n = count
                .as_f64()
                .filter(|n| *n > 0.0 && n.is_finite())
                .ok_or_else(|| JsError::new(&format!("{key} is a positive number")))?;
            return Ok(ColumnFilter::Top10 {
                value: Some(n.to_string()),
                percent: flag("percent"),
                top,
                filter_value: None,
            });
        }
    }
    Err(JsError::new(
        "a filter is { values }, { custom }, { top } or { bottom }",
    ))
}