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 {
#[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))
}
#[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))
}
#[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)?)
}
#[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)?)
}
#[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)?)
}
#[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),
),
])
}))
}
}
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 {
#[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)
}
#[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 {
#[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)
}
#[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)
}
#[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)
}
#[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)
}
#[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())]))
}
#[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))
}
#[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() {
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)
}
#[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(())
}
}
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)
}),
}
}
fn border_to_js(border: &Border) -> JsValue {
object(&[
("style", JsValue::from_str(border.style.as_str())),
("color", color_to_js(&border.color)),
])
}
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)),
),
]),
),
])
}
#[cfg(feature = "write")]
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::*;
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> {
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(())
}
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 })
}
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)
}
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"));
}
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"))
}
fn flag(patch: &JsValue, key: &str, to: &mut bool) {
if let Some(value) = field(patch, key) {
*to = value.is_truthy();
}
}
fn text(value: &JsValue, what: &str) -> Result<String, JsError> {
value
.as_string()
.ok_or_else(|| JsError::new(&format!("{what} is a string")))
}
fn number(value: &JsValue, what: &str) -> Result<f64, JsError> {
value
.as_f64()
.ok_or_else(|| JsError::new(&format!("{what} is a number")))
}
}