use super::convert::{
area_at, array, at_index, cell_to_js, js_to_cell, object, offset, row_at, rows_of,
};
use super::{Book, js};
use crate::coordinate::{CellRef, Col, Range};
use crate::model::CellValue;
use crate::style::Style;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
impl Book {
#[wasm_bindgen(unchecked_return_type = "CellValue")]
pub fn get(&self, sheet: usize, address: &str) -> Result<JsValue, JsError> {
self.value_at(sheet, CellRef::parse(address).map_err(js)?)
}
#[wasm_bindgen(js_name = getAt, unchecked_return_type = "CellValue")]
pub fn get_at(&self, sheet: usize, row: u32, column: u32) -> Result<JsValue, JsError> {
self.value_at(sheet, at_index(row, column)?)
}
pub fn set(
&mut self,
sheet: usize,
address: &str,
#[wasm_bindgen(unchecked_param_type = "CellValue")] value: &JsValue,
) -> Result<(), JsError> {
let at = CellRef::parse(address).map_err(js)?;
self.store(sheet, vec![(at, js_to_cell(value)?)])
}
#[wasm_bindgen(js_name = setAt)]
pub fn set_at(
&mut self,
sheet: usize,
row: u32,
column: u32,
#[wasm_bindgen(unchecked_param_type = "CellValue")] value: &JsValue,
) -> Result<(), JsError> {
let at = at_index(row, column)?;
self.store(sheet, vec![(at, js_to_cell(value)?)])
}
pub fn clear(&mut self, sheet: usize, address: &str) -> Result<(), JsError> {
self.erase(sheet, CellRef::parse(address).map_err(js)?)
}
#[wasm_bindgen(js_name = clearAt)]
pub fn clear_at(&mut self, sheet: usize, row: u32, column: u32) -> Result<(), JsError> {
self.erase(sheet, at_index(row, column)?)
}
#[wasm_bindgen(js_name = getFormula)]
#[must_use]
pub fn get_formula(&self, sheet: usize, address: &str) -> Option<String> {
self.formula_of(sheet, CellRef::parse(address).ok()?)
}
#[wasm_bindgen(js_name = getFormulaAt)]
#[must_use]
pub fn get_formula_at(&self, sheet: usize, row: u32, column: u32) -> Option<String> {
self.formula_of(sheet, at_index(row, column).ok()?)
}
#[wasm_bindgen(js_name = getFormatted)]
pub fn get_formatted(&self, sheet: usize, address: &str) -> Result<String, JsError> {
self.formatted(sheet, CellRef::parse(address).map_err(js)?)
}
#[wasm_bindgen(js_name = getFormattedAt)]
pub fn get_formatted_at(&self, sheet: usize, row: u32, column: u32) -> Result<String, JsError> {
self.formatted(sheet, at_index(row, column)?)
}
#[wasm_bindgen(js_name = cellBold)]
pub fn cell_bold(&self, sheet: usize, address: &str) -> Result<bool, JsError> {
let at = CellRef::parse(address).map_err(js)?;
Ok(self.style_at(sheet, at)?.is_some_and(|s| s.font.bold))
}
#[wasm_bindgen(js_name = cellBoldAt)]
pub fn cell_bold_at(&self, sheet: usize, row: u32, column: u32) -> Result<bool, JsError> {
let at = at_index(row, column)?;
Ok(self.style_at(sheet, at)?.is_some_and(|s| s.font.bold))
}
#[wasm_bindgen(js_name = cellIndent)]
pub fn cell_indent(&self, sheet: usize, address: &str) -> Result<u32, JsError> {
let at = CellRef::parse(address).map_err(js)?;
Ok(self.style_at(sheet, at)?.map_or(0, |s| s.alignment.indent))
}
#[wasm_bindgen(js_name = cellIndentAt)]
pub fn cell_indent_at(&self, sheet: usize, row: u32, column: u32) -> Result<u32, JsError> {
let at = at_index(row, column)?;
Ok(self.style_at(sheet, at)?.map_or(0, |s| s.alignment.indent))
}
#[wasm_bindgen(js_name = getRowAt, unchecked_return_type = "SheetRow")]
pub fn get_row_at(
&self,
sheet: usize,
row: u32,
formatted: Option<bool>,
) -> Result<JsValue, JsError> {
Ok(row_object(
self.sheet_of(sheet)?,
&self.workbook.styles,
self.workbook.epoch,
row_at(row)?,
formatted.unwrap_or(true),
))
}
#[wasm_bindgen(js_name = forEachRow)]
#[expect(
clippy::needless_pass_by_value,
reason = "an optional string crosses the wasm boundary owned"
)]
pub fn for_each_row(
bytes: &[u8],
name: Option<String>,
sheet: usize,
callback: &js_sys::Function,
formatted: Option<bool>,
) -> Result<Self, JsError> {
let wanted = formatted.unwrap_or(true);
let failed: std::cell::RefCell<Option<JsValue>> = std::cell::RefCell::new(None);
let sink = |batch: &crate::progress::RowBatch<'_>| {
if failed.borrow().is_some() {
return;
}
let data = row_object(batch.sheet, batch.styles, batch.epoch, batch.row, wanted);
let row = JsValue::from(batch.row.index() + 1);
if let Err(e) = callback.call2(&JsValue::NULL, &row, &data) {
*failed.borrow_mut() = Some(e);
}
};
let options = crate::progress::Options::new().streaming(sheet, &sink);
let book = crate::reader::read_bytes_limited_with(
bytes,
name.as_deref(),
crate::reader::xlsx::MAX_UNCOMPRESSED_SIZE,
&options,
)
.map_err(js)?;
if let Some(e) = failed.into_inner() {
return Err(JsError::new(
&e.as_string()
.or_else(|| js_sys::Error::from(e).message().as_string())
.unwrap_or_else(|| "row callback failed".into()),
));
}
Ok(Self::wrap(book))
}
#[wasm_bindgen(js_name = getRange, unchecked_return_type = "CellGrid")]
pub fn get_range(&self, sheet: usize, range: &str) -> Result<JsValue, JsError> {
self.grid(sheet, Range::parse(range).map_err(js)?)
}
#[wasm_bindgen(js_name = getRangeAt, unchecked_return_type = "CellGrid")]
pub fn get_range_at(
&self,
sheet: usize,
row: u32,
column: u32,
rows: u32,
columns: u32,
) -> Result<JsValue, JsError> {
self.grid(sheet, area_at(row, column, rows, columns)?)
}
#[wasm_bindgen(js_name = setRange)]
pub fn set_range(
&mut self,
sheet: usize,
at: &str,
#[wasm_bindgen(unchecked_param_type = "CellGrid")] values: &JsValue,
) -> Result<(), JsError> {
self.write_grid(sheet, CellRef::parse(at).map_err(js)?, values)
}
#[wasm_bindgen(js_name = setRangeAt)]
pub fn set_range_at(
&mut self,
sheet: usize,
row: u32,
column: u32,
#[wasm_bindgen(unchecked_param_type = "CellGrid")] values: &JsValue,
) -> Result<(), JsError> {
self.write_grid(sheet, at_index(row, column)?, values)
}
}
impl Book {
fn value_at(&self, sheet: usize, at: CellRef) -> Result<JsValue, JsError> {
Ok(self
.sheet_of(sheet)?
.get(at)
.map_or(JsValue::NULL, |cell| cell_to_js(&cell.value)))
}
fn formula_of(&self, sheet: usize, at: CellRef) -> Option<String> {
match &self.workbook.sheet(sheet)?.get(at)?.value {
CellValue::Formula { formula, .. } => Some(formula.clone()),
_ => None,
}
}
fn formatted(&self, sheet: usize, at: CellRef) -> Result<String, JsError> {
self.sheet_of(sheet)?;
Ok(self.workbook.formatted(sheet, at))
}
pub(super) fn style_at(&self, sheet: usize, at: CellRef) -> Result<Option<&Style>, JsError> {
Ok(self
.sheet_of(sheet)?
.get(at)
.and_then(|cell| self.workbook.styles.get(cell.style)))
}
fn grid(&self, sheet: usize, area: Range) -> Result<JsValue, JsError> {
let ws = self.sheet_of(sheet)?;
let rows = js_sys::Array::new();
for line in rows_of(area) {
let cells: js_sys::Array = line
.map(|at| {
ws.get(at)
.map_or(JsValue::NULL, |cell| cell_to_js(&cell.value))
})
.collect();
rows.push(&cells);
}
Ok(rows.into())
}
fn write_grid(
&mut self,
sheet: usize,
start: CellRef,
values: &JsValue,
) -> Result<(), JsError> {
self.sheet_of(sheet)?;
let mut writes = Vec::new();
for (r, row) in array(values, "values")?.iter().enumerate() {
for (c, value) in array(&row, "every row")?.iter().enumerate() {
writes.push((offset(start, r, c)?, js_to_cell(&value)?));
}
}
self.store(sheet, writes)
}
fn store(&mut self, sheet: usize, writes: Vec<(CellRef, CellValue)>) -> Result<(), JsError> {
let ws = self.sheet_mut(sheet)?;
let is_formula =
|value: Option<&CellValue>| matches!(value, Some(CellValue::Formula { .. }));
let mut formulas = Vec::new();
for (at, value) in writes {
if is_formula(Some(&value)) || is_formula(ws.get(at).map(|c| &c.value)) {
formulas.push(at);
}
ws.set(at, value);
}
self.note(sheet, &formulas);
Ok(())
}
fn erase(&mut self, sheet: usize, at: CellRef) -> Result<(), JsError> {
self.sheet_mut(sheet)?.remove(at);
self.note(sheet, &[at]);
Ok(())
}
}
fn row_object(
ws: &crate::model::Worksheet,
styles: &crate::style::StyleTable,
epoch: crate::shared::date::Epoch,
at: crate::coordinate::Row,
wanted: bool,
) -> JsValue {
let width = ws
.row_cells(at)
.last()
.map_or(0, |(col, _)| col.index() + 1);
let values = js_sys::Array::new();
let shown = js_sys::Array::new();
let mut bold = Vec::with_capacity(width as usize);
let mut indent = Vec::with_capacity(width as usize);
for cell_at in (0..width)
.filter_map(Col::new)
.map(|col| CellRef::new(col, at))
{
let cell = ws.get(cell_at);
values.push(&cell.map_or(JsValue::NULL, |cell| cell_to_js(&cell.value)));
let style = cell.and_then(|cell| styles.get(cell.style));
if wanted {
let code = style.map_or(crate::style::format::GENERAL, |s| s.number_format.code());
let text = cell.map_or_else(String::new, |cell| cell.value.display(code, epoch));
shown.push(&JsValue::from_str(&text));
}
bold.push(u8::from(style.is_some_and(|s| s.font.bold)));
indent.push(style.map_or(0, |s| s.alignment.indent));
}
object(&[
("values", values.into()),
(
"formatted",
if wanted { shown.into() } else { JsValue::NULL },
),
("bold", js_sys::Uint8Array::from(&bold[..]).into()),
("indent", js_sys::Uint32Array::from(&indent[..]).into()),
(
"hidden",
JsValue::from_bool(ws.rows.get(&at).is_some_and(|props| props.hidden)),
),
])
}