Compare commits

..

1 Commits

Author SHA1 Message Date
varuntumbe
e7858f7aa9 adding merge cell logic processing
formatting commit

addressing testcase failures

adding one more scenario to case

adding one more scenario to case

Adding update and unmerge functions for merge cell handling

adding one more case to testcase

adding testcases to base code

adding testcase for import/export

adding documentation to some of the PUB function

fixing warnings and test warnings

adding merge cell part cell update restriction to public sytle set fns

addressing reviwers comment : Changed Mergedcell structure and its side effercts

reverting it back to non pub.

renaming update_merge_cells to just merge_cells in model

renaming *unmerge_merged_cell* to *unmerge_cells*

addressing other reviewer's comment + cosmetica naming adjustments

cosmetic changes
2024-11-29 23:13:10 +01:00
107 changed files with 1774 additions and 4449 deletions

View File

@@ -1,7 +1,10 @@
name: Coverage
on:
workflow_dispatch:
pull_request:
push:
branches:
- main
jobs:
coverage:
@@ -17,9 +20,8 @@ jobs:
- name: Generate code coverage
run: cargo llvm-cov --all-features --workspace --exclude pyroncalc --exclude wasm --lcov --output-path lcov.info
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v5
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
uses: codecov/codecov-action@v3
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: lcov.info
fail_ci_if_error: true

View File

@@ -12,7 +12,6 @@
- Fixed several issues with pasting content
- Fixed several issues with borders
- Fixed bug where columns and rows could be resized to negative width and height, respectively
## [0.2.0] - 2024-11-06 (The HN release)

View File

@@ -10,7 +10,6 @@ format:
.PHONY: tests
tests: lint
cargo test
make remove-artifacts
# Regretabbly we need to build the wasm twice, once for the nodejs tests
# and a second one for the vitest.

View File

@@ -2,7 +2,6 @@ use std::cmp::Ordering;
use crate::expressions::{token::Error, types::CellReferenceIndex};
#[derive(Clone)]
pub struct Range {
pub left: CellReferenceIndex,
pub right: CellReferenceIndex,

View File

@@ -176,3 +176,18 @@ impl Cell {
}
}
}
// Implementing methods for MergedCells struct
impl MergedCells {
pub fn is_cell_part_of_merged_cells(&self, row: i32, col: i32) -> bool {
// This is merge Mother cell so do not include this cell as part of Merged Cells
if row == self.0 && col == self.1 {
return false;
}
let result: bool = (row >= self.0 && row <= self.2) && (col >= self.1 && col <= self.3);
result
}
}

View File

@@ -6,7 +6,7 @@ pub(crate) const DEFAULT_COLUMN_WIDTH: f64 = 125.0;
pub(crate) const DEFAULT_ROW_HEIGHT: f64 = 28.0;
pub(crate) const COLUMN_WIDTH_FACTOR: f64 = 12.0;
pub(crate) const ROW_HEIGHT_FACTOR: f64 = 2.0;
pub(crate) const DEFAULT_WINDOW_HEIGHT: i64 = 600;
pub(crate) const DEFAULT_WINDOW_HEIGH: i64 = 600;
pub(crate) const DEFAULT_WINDOW_WIDTH: i64 = 800;
pub(crate) const LAST_COLUMN: i32 = 16_384;

View File

@@ -24,25 +24,6 @@ fn test_get_tokens() {
assert_eq!(l.end, 10);
}
#[test]
fn get_tokens_unicode() {
let formula = "'🇵🇭 Philippines'!A1";
let t = get_tokens(formula);
assert_eq!(t.len(), 1);
let expected = TokenType::Reference {
sheet: Some("🇵🇭 Philippines".to_string()),
row: 1,
column: 1,
absolute_column: false,
absolute_row: false,
};
let l = t.first().expect("expected token");
assert_eq!(l.token, expected);
assert_eq!(l.start, 0);
assert_eq!(l.end, 19);
}
#[test]
fn test_simple_tokens() {
assert_eq!(

View File

@@ -49,7 +49,15 @@ pub mod stringify;
pub mod walk;
#[cfg(test)]
mod tests;
mod test;
#[cfg(test)]
mod test_ranges;
#[cfg(test)]
mod test_move_formula;
#[cfg(test)]
mod test_tables;
pub(crate) fn parse_range(formula: &str) -> Result<(i32, i32, i32, i32), String> {
let mut lexer = lexer::Lexer::new(
@@ -164,9 +172,7 @@ pub enum Node {
args: Vec<Node>,
},
ArrayKind(Vec<Node>),
DefinedNameKind((String, Option<u32>)),
TableNameKind(String),
WrongVariableKind(String),
VariableKind(String),
CompareKind {
kind: OpCompare,
left: Box<Node>,
@@ -189,17 +195,12 @@ pub enum Node {
pub struct Parser {
lexer: lexer::Lexer,
worksheets: Vec<String>,
defined_names: Vec<(String, Option<u32>)>,
context: CellReferenceRC,
context: Option<CellReferenceRC>,
tables: HashMap<String, Table>,
}
impl Parser {
pub fn new(
worksheets: Vec<String>,
defined_names: Vec<(String, Option<u32>)>,
tables: HashMap<String, Table>,
) -> Parser {
pub fn new(worksheets: Vec<String>, tables: HashMap<String, Table>) -> Parser {
let lexer = lexer::Lexer::new(
"",
lexer::LexerMode::A1,
@@ -208,16 +209,10 @@ impl Parser {
#[allow(clippy::expect_used)]
get_language("en").expect(""),
);
let context = CellReferenceRC {
sheet: worksheets.first().map_or("", |v| v).to_string(),
column: 1,
row: 1,
};
Parser {
lexer,
worksheets,
defined_names,
context,
context: None,
tables,
}
}
@@ -225,18 +220,13 @@ impl Parser {
self.lexer.set_lexer_mode(mode)
}
pub fn set_worksheets_and_names(
&mut self,
worksheets: Vec<String>,
defined_names: Vec<(String, Option<u32>)>,
) {
pub fn set_worksheets(&mut self, worksheets: Vec<String>) {
self.worksheets = worksheets;
self.defined_names = defined_names;
}
pub fn parse(&mut self, formula: &str, context: &CellReferenceRC) -> Node {
pub fn parse(&mut self, formula: &str, context: &Option<CellReferenceRC>) -> Node {
self.lexer.set_formula(formula);
self.context = context.clone();
self.context.clone_from(context);
self.parse_expr()
}
@@ -250,24 +240,6 @@ impl Parser {
None
}
// Returns:
// * None: If there is no defined name by that name
// * Some(Some(index)): If there is a defined name local to that sheet
// * Some(None): If there is a global defined name
fn get_defined_name(&self, name: &str, sheet: u32) -> Option<Option<u32>> {
for (df_name, df_scope) in &self.defined_names {
if name.to_lowercase() == df_name.to_lowercase() && df_scope == &Some(sheet) {
return Some(*df_scope);
}
}
for (df_name, df_scope) in &self.defined_names {
if name.to_lowercase() == df_name.to_lowercase() && df_scope.is_none() {
return Some(None);
}
}
None
}
fn parse_expr(&mut self) -> Node {
let mut t = self.parse_concat();
if let Node::ParseErrorKind { .. } = t {
@@ -482,7 +454,16 @@ impl Parser {
absolute_column,
absolute_row,
} => {
let context = &self.context;
let context = match &self.context {
Some(c) => c,
None => {
return Node::ParseErrorKind {
formula: self.lexer.get_formula(),
position: self.lexer.get_position() as usize,
message: "Expected context for the reference".to_string(),
}
}
};
let sheet_index = match &sheet {
Some(name) => self.get_sheet_index_by_name(name),
None => self.get_sheet_index_by_name(&context.sheet),
@@ -517,7 +498,16 @@ impl Parser {
}
}
TokenType::Range { sheet, left, right } => {
let context = &self.context;
let context = match &self.context {
Some(c) => c,
None => {
return Node::ParseErrorKind {
formula: self.lexer.get_formula(),
position: self.lexer.get_position() as usize,
message: "Expected context for the reference".to_string(),
}
}
};
let sheet_index = match &sheet {
Some(name) => self.get_sheet_index_by_name(name),
None => self.get_sheet_index_by_name(&context.sheet),
@@ -532,6 +522,20 @@ impl Parser {
let mut absolute_row1 = left.absolute_row;
let mut absolute_row2 = right.absolute_row;
if self.lexer.is_a1_mode() {
if !left.absolute_row {
row1 -= context.row
};
if !left.absolute_column {
column1 -= context.column
};
if !right.absolute_row {
row2 -= context.row
};
if !right.absolute_column {
column2 -= context.column
};
}
if row1 > row2 {
(row2, row1) = (row1, row2);
(absolute_row2, absolute_row1) = (absolute_row1, absolute_row2);
@@ -540,22 +544,6 @@ impl Parser {
(column2, column1) = (column1, column2);
(absolute_column2, absolute_column1) = (absolute_column1, absolute_column2);
}
if self.lexer.is_a1_mode() {
if !absolute_row1 {
row1 -= context.row
};
if !absolute_column1 {
column1 -= context.column
};
if !absolute_row2 {
row2 -= context.row
};
if !absolute_column2 {
column2 -= context.column
};
}
match sheet_index {
Some(index) => Node::RangeKind {
sheet_name: sheet,
@@ -603,33 +591,11 @@ impl Parser {
kind: function_kind,
args,
};
}
return Node::InvalidFunctionKind { name, args };
}
let context = &self.context;
let context_sheet_index = match self.get_sheet_index_by_name(&context.sheet) {
Some(i) => i,
None => {
return Node::ParseErrorKind {
formula: self.lexer.get_formula(),
position: 0,
message: "sheet not found".to_string(),
};
}
};
// Could be a defined name or a table
if let Some(scope) = self.get_defined_name(&name, context_sheet_index) {
return Node::DefinedNameKind((name, scope));
}
let name_lower = name.to_lowercase();
for table_name in self.tables.keys() {
if table_name.to_lowercase() == name_lower {
return Node::TableNameKind(name);
} else {
return Node::InvalidFunctionKind { name, args };
}
}
Node::WrongVariableKind(name)
Node::VariableKind(name)
}
TokenType::Error(kind) => Node::ErrorKind(kind),
TokenType::Illegal(error) => Node::ParseErrorKind {
@@ -701,177 +667,187 @@ impl Parser {
// We will try to convert to a normal reference
// table_name[column_name] => cell1:cell2
// table_name[[#This Row], [column_name]:[column_name]] => cell1:cell2
let context = &self.context;
let context_sheet_index = match self.get_sheet_index_by_name(&context.sheet) {
Some(i) => i,
None => {
return Node::ParseErrorKind {
formula: self.lexer.get_formula(),
position: 0,
message: "sheet not found".to_string(),
};
}
};
// table-name => table
let table = match self.tables.get(&table_name) {
Some(t) => t,
None => {
let message = format!(
"Table not found: '{table_name}' at '{}!{}{}'",
context.sheet,
number_to_column(context.column)
.unwrap_or(format!("{}", context.column)),
context.row
);
return Node::ParseErrorKind {
formula: self.lexer.get_formula(),
position: 0,
message,
};
}
};
let table_sheet_index = match self.get_sheet_index_by_name(&table.sheet_name) {
Some(i) => i,
None => {
return Node::ParseErrorKind {
formula: self.lexer.get_formula(),
position: 0,
message: "sheet not found".to_string(),
};
}
};
let sheet_name = if table_sheet_index == context_sheet_index {
None
} else {
Some(table.sheet_name.clone())
};
// context must be with tables.reference
#[allow(clippy::expect_used)]
let (column_start, mut row_start, column_end, mut row_end) =
parse_range(&table.reference).expect("Failed parsing range");
let totals_row_count = table.totals_row_count as i32;
let header_row_count = table.header_row_count as i32;
row_end -= totals_row_count;
match specifier {
Some(token::TableSpecifier::ThisRow) => {
row_start = context.row;
row_end = context.row;
}
Some(token::TableSpecifier::Totals) => {
if totals_row_count != 0 {
row_start = row_end + 1;
row_end = row_start;
} else {
// Table1[#Totals] is #REF! if Table1 does not have totals
return Node::ErrorKind(token::Error::REF);
}
}
Some(token::TableSpecifier::Headers) => {
row_end = row_start;
}
Some(token::TableSpecifier::Data) => {
row_start += header_row_count;
}
Some(token::TableSpecifier::All) => {
if totals_row_count != 0 {
row_end += 1;
}
}
None => {
// skip the headers
row_start += header_row_count;
}
}
match table_reference {
None => Node::RangeKind {
sheet_name,
sheet_index: table_sheet_index,
absolute_row1: true,
absolute_column1: true,
row1: row_start,
column1: column_start,
absolute_row2: true,
absolute_column2: true,
row2: row_end,
column2: column_end,
},
Some(TableReference::ColumnReference(s)) => {
let column_index = match get_table_column_by_name(&s, table) {
Some(s) => s + column_start,
None => {
return Node::ParseErrorKind {
formula: self.lexer.get_formula(),
position: self.lexer.get_position() as usize,
message: format!("Expecting column: {s} in table {table_name}"),
};
}
};
if row_start == row_end {
return Node::ReferenceKind {
sheet_name,
sheet_index: table_sheet_index,
absolute_row: true,
absolute_column: true,
row: row_start,
column: column_index,
if let Some(context) = &self.context {
let context_sheet_index = match self.get_sheet_index_by_name(&context.sheet) {
Some(i) => i,
None => {
return Node::ParseErrorKind {
formula: self.lexer.get_formula(),
position: 0,
message: "sheet not found".to_string(),
};
}
Node::RangeKind {
sheet_name,
sheet_index: table_sheet_index,
absolute_row1: true,
absolute_column1: true,
row1: row_start,
column1: column_index,
absolute_row2: true,
absolute_column2: true,
row2: row_end,
column2: column_index,
};
// table-name => table
let table = match self.tables.get(&table_name) {
Some(t) => t,
None => {
let message = format!(
"Table not found: '{table_name}' at '{}!{}{}'",
context.sheet,
number_to_column(context.column)
.unwrap_or(format!("{}", context.column)),
context.row
);
return Node::ParseErrorKind {
formula: self.lexer.get_formula(),
position: 0,
message,
};
}
}
Some(TableReference::RangeReference((left, right))) => {
let left_column_index = match get_table_column_by_name(&left, table) {
Some(f) => f + column_start,
None => {
return Node::ParseErrorKind {
formula: self.lexer.get_formula(),
position: self.lexer.get_position() as usize,
message: format!(
"Expecting column: {left} in table {table_name}"
),
};
}
};
};
let table_sheet_index = match self.get_sheet_index_by_name(&table.sheet_name) {
Some(i) => i,
None => {
return Node::ParseErrorKind {
formula: self.lexer.get_formula(),
position: 0,
message: "sheet not found".to_string(),
};
}
};
let right_column_index = match get_table_column_by_name(&right, table) {
Some(f) => f + column_start,
None => {
return Node::ParseErrorKind {
formula: self.lexer.get_formula(),
position: self.lexer.get_position() as usize,
message: format!(
"Expecting column: {right} in table {table_name}"
),
};
let sheet_name = if table_sheet_index == context_sheet_index {
None
} else {
Some(table.sheet_name.clone())
};
// context must be with tables.reference
#[allow(clippy::expect_used)]
let (column_start, mut row_start, column_end, mut row_end) =
parse_range(&table.reference).expect("Failed parsing range");
let totals_row_count = table.totals_row_count as i32;
let header_row_count = table.header_row_count as i32;
row_end -= totals_row_count;
match specifier {
Some(token::TableSpecifier::ThisRow) => {
row_start = context.row;
row_end = context.row;
}
Some(token::TableSpecifier::Totals) => {
if totals_row_count != 0 {
row_start = row_end + 1;
row_end = row_start;
} else {
// Table1[#Totals] is #REF! if Table1 does not have totals
return Node::ErrorKind(token::Error::REF);
}
};
Node::RangeKind {
sheet_name,
sheet_index: table_sheet_index,
absolute_row1: true,
absolute_column1: true,
row1: row_start,
column1: left_column_index,
absolute_row2: true,
absolute_column2: true,
row2: row_end,
column2: right_column_index,
}
Some(token::TableSpecifier::Headers) => {
row_end = row_start;
}
Some(token::TableSpecifier::Data) => {
row_start += header_row_count;
}
Some(token::TableSpecifier::All) => {
if totals_row_count != 0 {
row_end += 1;
}
}
None => {
// skip the headers
row_start += header_row_count;
}
}
match table_reference {
None => {
return Node::RangeKind {
sheet_name,
sheet_index: table_sheet_index,
absolute_row1: true,
absolute_column1: true,
row1: row_start,
column1: column_start,
absolute_row2: true,
absolute_column2: true,
row2: row_end,
column2: column_end,
};
}
Some(TableReference::ColumnReference(s)) => {
let column_index = match get_table_column_by_name(&s, table) {
Some(s) => s + column_start,
None => {
return Node::ParseErrorKind {
formula: self.lexer.get_formula(),
position: self.lexer.get_position() as usize,
message: format!(
"Expecting column: {s} in table {table_name}"
),
};
}
};
if row_start == row_end {
return Node::ReferenceKind {
sheet_name,
sheet_index: table_sheet_index,
absolute_row: true,
absolute_column: true,
row: row_start,
column: column_index,
};
}
return Node::RangeKind {
sheet_name,
sheet_index: table_sheet_index,
absolute_row1: true,
absolute_column1: true,
row1: row_start,
column1: column_index,
absolute_row2: true,
absolute_column2: true,
row2: row_end,
column2: column_index,
};
}
Some(TableReference::RangeReference((left, right))) => {
let left_column_index = match get_table_column_by_name(&left, table) {
Some(f) => f + column_start,
None => {
return Node::ParseErrorKind {
formula: self.lexer.get_formula(),
position: self.lexer.get_position() as usize,
message: format!(
"Expecting column: {left} in table {table_name}"
),
};
}
};
let right_column_index = match get_table_column_by_name(&right, table) {
Some(f) => f + column_start,
None => {
return Node::ParseErrorKind {
formula: self.lexer.get_formula(),
position: self.lexer.get_position() as usize,
message: format!(
"Expecting column: {right} in table {table_name}"
),
};
}
};
return Node::RangeKind {
sheet_name,
sheet_index: table_sheet_index,
absolute_row1: true,
absolute_column1: true,
row1: row_start,
column1: left_column_index,
absolute_row2: true,
absolute_column2: true,
row2: row_end,
column2: right_column_index,
};
}
}
}
Node::ParseErrorKind {
formula: self.lexer.get_formula(),
position: 0,
message: "Structured references not supported in R1C1 mode".to_string(),
}
}
}

View File

@@ -375,9 +375,7 @@ fn to_string_moved(node: &Node, move_context: &MoveContext) -> String {
}
format!("{{{}}}", arguments)
}
DefinedNameKind((name, _)) => name.to_string(),
TableNameKind(name) => name.to_string(),
WrongVariableKind(name) => name.to_string(),
VariableKind(value) => value.to_string(),
CompareKind { kind, left, right } => format!(
"{}{}{}",
to_string_moved(left, move_context),

View File

@@ -456,69 +456,11 @@ fn stringify(
};
format!("{}{}{}", x, kind, y)
}
OpPowerKind { left, right } => {
let x = match **left {
BooleanKind(_)
| NumberKind(_)
| StringKind(_)
| ReferenceKind { .. }
| RangeKind { .. }
| WrongReferenceKind { .. }
| DefinedNameKind(_)
| TableNameKind(_)
| WrongVariableKind(_)
| WrongRangeKind { .. } => {
stringify(left, context, displace_data, use_original_name)
}
OpRangeKind { .. }
| OpConcatenateKind { .. }
| OpProductKind { .. }
| OpPowerKind { .. }
| FunctionKind { .. }
| InvalidFunctionKind { .. }
| ArrayKind(_)
| UnaryKind { .. }
| ErrorKind(_)
| ParseErrorKind { .. }
| OpSumKind { .. }
| CompareKind { .. }
| EmptyArgKind => format!(
"({})",
stringify(left, context, displace_data, use_original_name)
),
};
let y = match **right {
BooleanKind(_)
| NumberKind(_)
| StringKind(_)
| ReferenceKind { .. }
| RangeKind { .. }
| WrongReferenceKind { .. }
| DefinedNameKind(_)
| TableNameKind(_)
| WrongVariableKind(_)
| WrongRangeKind { .. } => {
stringify(right, context, displace_data, use_original_name)
}
OpRangeKind { .. }
| OpConcatenateKind { .. }
| OpProductKind { .. }
| OpPowerKind { .. }
| FunctionKind { .. }
| InvalidFunctionKind { .. }
| ArrayKind(_)
| UnaryKind { .. }
| ErrorKind(_)
| ParseErrorKind { .. }
| OpSumKind { .. }
| CompareKind { .. }
| EmptyArgKind => format!(
"({})",
stringify(right, context, displace_data, use_original_name)
),
};
format!("{}^{}", x, y)
}
OpPowerKind { left, right } => format!(
"{}^{}",
stringify(left, context, displace_data, use_original_name),
stringify(right, context, displace_data, use_original_name)
),
InvalidFunctionKind { name, args } => {
format_function(name, args, context, displace_data, use_original_name)
}
@@ -547,9 +489,7 @@ fn stringify(
}
format!("{{{}}}", arguments)
}
TableNameKind(value) => value.to_string(),
DefinedNameKind((name, _)) => name.to_string(),
WrongVariableKind(name) => name.to_string(),
VariableKind(value) => value.to_string(),
UnaryKind { kind, right } => match kind {
OpUnary::Minus => {
format!(
@@ -666,90 +606,7 @@ pub(crate) fn rename_sheet_in_node(node: &mut Node, sheet_index: u32, new_name:
Node::ErrorKind(_) => {}
Node::ParseErrorKind { .. } => {}
Node::ArrayKind(_) => {}
Node::DefinedNameKind(_) => {}
Node::TableNameKind(_) => {}
Node::WrongVariableKind(_) => {}
Node::VariableKind(_) => {}
Node::EmptyArgKind => {}
}
}
pub(crate) fn rename_defined_name_in_node(
node: &mut Node,
name: &str,
scope: Option<u32>,
new_name: &str,
) {
match node {
// Rename
Node::DefinedNameKind((n, s)) => {
if name.to_lowercase() == n.to_lowercase() && *s == scope {
*n = new_name.to_string();
}
}
// Go next level
Node::OpRangeKind { left, right } => {
rename_defined_name_in_node(left, name, scope, new_name);
rename_defined_name_in_node(right, name, scope, new_name);
}
Node::OpConcatenateKind { left, right } => {
rename_defined_name_in_node(left, name, scope, new_name);
rename_defined_name_in_node(right, name, scope, new_name);
}
Node::OpSumKind {
kind: _,
left,
right,
} => {
rename_defined_name_in_node(left, name, scope, new_name);
rename_defined_name_in_node(right, name, scope, new_name);
}
Node::OpProductKind {
kind: _,
left,
right,
} => {
rename_defined_name_in_node(left, name, scope, new_name);
rename_defined_name_in_node(right, name, scope, new_name);
}
Node::OpPowerKind { left, right } => {
rename_defined_name_in_node(left, name, scope, new_name);
rename_defined_name_in_node(right, name, scope, new_name);
}
Node::FunctionKind { kind: _, args } => {
for arg in args {
rename_defined_name_in_node(arg, name, scope, new_name);
}
}
Node::InvalidFunctionKind { name: _, args } => {
for arg in args {
rename_defined_name_in_node(arg, name, scope, new_name);
}
}
Node::CompareKind {
kind: _,
left,
right,
} => {
rename_defined_name_in_node(left, name, scope, new_name);
rename_defined_name_in_node(right, name, scope, new_name);
}
Node::UnaryKind { kind: _, right } => {
rename_defined_name_in_node(right, name, scope, new_name);
}
// Do nothing
Node::BooleanKind(_) => {}
Node::NumberKind(_) => {}
Node::StringKind(_) => {}
Node::ErrorKind(_) => {}
Node::ParseErrorKind { .. } => {}
Node::ArrayKind(_) => {}
Node::EmptyArgKind => {}
Node::ReferenceKind { .. } => {}
Node::RangeKind { .. } => {}
Node::WrongReferenceKind { .. } => {}
Node::WrongRangeKind { .. } => {}
Node::TableNameKind(_) => {}
Node::WrongVariableKind(_) => {}
}
}

View File

@@ -3,11 +3,17 @@
use std::collections::HashMap;
use crate::expressions::lexer::LexerMode;
use crate::expressions::parser::stringify::{
to_rc_format, to_string, to_string_displaced, DisplaceData,
use crate::expressions::parser::stringify::DisplaceData;
use super::super::types::CellReferenceRC;
use super::Parser;
use super::{
super::parser::{
stringify::{to_rc_format, to_string},
Node,
},
stringify::to_string_displaced,
};
use crate::expressions::parser::{Node, Parser};
use crate::expressions::types::CellReferenceRC;
struct Formula<'a> {
initial: &'a str,
@@ -17,7 +23,7 @@ struct Formula<'a> {
#[test]
fn test_parser_reference() {
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
@@ -25,14 +31,14 @@ fn test_parser_reference() {
row: 1,
column: 1,
};
let t = parser.parse("A2", &cell_reference);
let t = parser.parse("A2", &Some(cell_reference));
assert_eq!(to_rc_format(&t), "R[1]C[0]");
}
#[test]
fn test_parser_absolute_column() {
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
@@ -40,14 +46,14 @@ fn test_parser_absolute_column() {
row: 1,
column: 1,
};
let t = parser.parse("$A1", &cell_reference);
let t = parser.parse("$A1", &Some(cell_reference));
assert_eq!(to_rc_format(&t), "R[0]C1");
}
#[test]
fn test_parser_absolute_row_col() {
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
@@ -55,14 +61,14 @@ fn test_parser_absolute_row_col() {
row: 1,
column: 1,
};
let t = parser.parse("$C$5", &cell_reference);
let t = parser.parse("$C$5", &Some(cell_reference));
assert_eq!(to_rc_format(&t), "R5C3");
}
#[test]
fn test_parser_absolute_row_col_1() {
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
@@ -70,14 +76,14 @@ fn test_parser_absolute_row_col_1() {
row: 1,
column: 1,
};
let t = parser.parse("$A$1", &cell_reference);
let t = parser.parse("$A$1", &Some(cell_reference));
assert_eq!(to_rc_format(&t), "R1C1");
}
#[test]
fn test_parser_simple_formula() {
let worksheets = vec!["Sheet1".to_string(), "Sheet2".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
@@ -86,14 +92,14 @@ fn test_parser_simple_formula() {
column: 1,
};
let t = parser.parse("C3+Sheet2!D4", &cell_reference);
let t = parser.parse("C3+Sheet2!D4", &Some(cell_reference));
assert_eq!(to_rc_format(&t), "R[2]C[2]+Sheet2!R[3]C[3]");
}
#[test]
fn test_parser_boolean() {
let worksheets = vec!["Sheet1".to_string(), "Sheet2".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
@@ -102,14 +108,14 @@ fn test_parser_boolean() {
column: 1,
};
let t = parser.parse("true", &cell_reference);
let t = parser.parse("true", &Some(cell_reference));
assert_eq!(to_rc_format(&t), "TRUE");
}
#[test]
fn test_parser_bad_formula() {
let worksheets = vec!["Sheet1".to_string(), "Sheet2".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
@@ -117,7 +123,7 @@ fn test_parser_bad_formula() {
row: 1,
column: 1,
};
let t = parser.parse("#Value", &cell_reference);
let t = parser.parse("#Value", &Some(cell_reference));
match &t {
Node::ParseErrorKind {
formula,
@@ -138,7 +144,7 @@ fn test_parser_bad_formula() {
#[test]
fn test_parser_bad_formula_1() {
let worksheets = vec!["Sheet1".to_string(), "Sheet2".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
@@ -146,7 +152,7 @@ fn test_parser_bad_formula_1() {
row: 1,
column: 1,
};
let t = parser.parse("<5", &cell_reference);
let t = parser.parse("<5", &Some(cell_reference));
match &t {
Node::ParseErrorKind {
formula,
@@ -167,7 +173,7 @@ fn test_parser_bad_formula_1() {
#[test]
fn test_parser_bad_formula_2() {
let worksheets = vec!["Sheet1".to_string(), "Sheet2".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
@@ -175,7 +181,7 @@ fn test_parser_bad_formula_2() {
row: 1,
column: 1,
};
let t = parser.parse("*5", &cell_reference);
let t = parser.parse("*5", &Some(cell_reference));
match &t {
Node::ParseErrorKind {
formula,
@@ -196,7 +202,7 @@ fn test_parser_bad_formula_2() {
#[test]
fn test_parser_bad_formula_3() {
let worksheets = vec!["Sheet1".to_string(), "Sheet2".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
@@ -204,7 +210,7 @@ fn test_parser_bad_formula_3() {
row: 1,
column: 1,
};
let t = parser.parse("SUM(#VALVE!)", &cell_reference);
let t = parser.parse("SUM(#VALVE!)", &Some(cell_reference));
match &t {
Node::ParseErrorKind {
formula,
@@ -225,7 +231,7 @@ fn test_parser_bad_formula_3() {
#[test]
fn test_parser_formulas() {
let worksheets = vec!["Sheet1".to_string(), "Sheet2".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
let formulas = vec![
Formula {
@@ -259,11 +265,11 @@ fn test_parser_formulas() {
for formula in formulas {
let t = parser.parse(
formula.initial,
&CellReferenceRC {
&Some(CellReferenceRC {
sheet: "Sheet1".to_string(),
row: 1,
column: 1,
},
}),
);
assert_eq!(to_rc_format(&t), formula.expected);
assert_eq!(to_string(&t, &cell_reference), formula.initial);
@@ -273,7 +279,7 @@ fn test_parser_formulas() {
#[test]
fn test_parser_r1c1_formulas() {
let worksheets = vec!["Sheet1".to_string(), "Sheet2".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
parser.set_lexer_mode(LexerMode::R1C1);
let formulas = vec![
@@ -324,11 +330,11 @@ fn test_parser_r1c1_formulas() {
for formula in formulas {
let t = parser.parse(
formula.initial,
&CellReferenceRC {
&Some(CellReferenceRC {
sheet: "Sheet1".to_string(),
row: 1,
column: 1,
},
}),
);
assert_eq!(to_string(&t, &cell_reference), formula.expected);
assert_eq!(to_rc_format(&t), formula.initial);
@@ -338,7 +344,7 @@ fn test_parser_r1c1_formulas() {
#[test]
fn test_parser_quotes() {
let worksheets = vec!["Sheet1".to_string(), "Second Sheet".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
@@ -347,14 +353,14 @@ fn test_parser_quotes() {
column: 1,
};
let t = parser.parse("C3+'Second Sheet'!D4", &cell_reference);
let t = parser.parse("C3+'Second Sheet'!D4", &Some(cell_reference));
assert_eq!(to_rc_format(&t), "R[2]C[2]+'Second Sheet'!R[3]C[3]");
}
#[test]
fn test_parser_escape_quotes() {
let worksheets = vec!["Sheet1".to_string(), "Second '2' Sheet".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
@@ -363,14 +369,14 @@ fn test_parser_escape_quotes() {
column: 1,
};
let t = parser.parse("C3+'Second ''2'' Sheet'!D4", &cell_reference);
let t = parser.parse("C3+'Second ''2'' Sheet'!D4", &Some(cell_reference));
assert_eq!(to_rc_format(&t), "R[2]C[2]+'Second ''2'' Sheet'!R[3]C[3]");
}
#[test]
fn test_parser_parenthesis() {
let worksheets = vec!["Sheet1".to_string(), "Second2".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
@@ -379,14 +385,14 @@ fn test_parser_parenthesis() {
column: 1,
};
let t = parser.parse("(C3=\"Yes\")*5", &cell_reference);
let t = parser.parse("(C3=\"Yes\")*5", &Some(cell_reference));
assert_eq!(to_rc_format(&t), "(R[2]C[2]=\"Yes\")*5");
}
#[test]
fn test_parser_excel_xlfn() {
let worksheets = vec!["Sheet1".to_string(), "Second2".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
@@ -395,7 +401,7 @@ fn test_parser_excel_xlfn() {
column: 1,
};
let t = parser.parse("_xlfn.CONCAT(C3)", &cell_reference);
let t = parser.parse("_xlfn.CONCAT(C3)", &Some(cell_reference));
assert_eq!(to_rc_format(&t), "CONCAT(R[2]C[2])");
}
@@ -407,9 +413,9 @@ fn test_to_string_displaced() {
column: 1,
};
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
let node = parser.parse("C3", context);
let node = parser.parse("C3", &Some(context.clone()));
let displace_data = DisplaceData::Column {
sheet: 0,
column: 1,
@@ -427,9 +433,9 @@ fn test_to_string_displaced_full_ranges() {
column: 1,
};
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
let node = parser.parse("SUM(3:3)", context);
let node = parser.parse("SUM(3:3)", &Some(context.clone()));
let displace_data = DisplaceData::Column {
sheet: 0,
column: 1,
@@ -440,7 +446,7 @@ fn test_to_string_displaced_full_ranges() {
"SUM(3:3)".to_string()
);
let node = parser.parse("SUM(D:D)", context);
let node = parser.parse("SUM(D:D)", &Some(context.clone()));
let displace_data = DisplaceData::Row {
sheet: 0,
row: 3,
@@ -460,9 +466,9 @@ fn test_to_string_displaced_too_low() {
column: 1,
};
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
let node = parser.parse("C3", context);
let node = parser.parse("C3", &Some(context.clone()));
let displace_data = DisplaceData::Column {
sheet: 0,
column: 1,
@@ -480,9 +486,9 @@ fn test_to_string_displaced_too_high() {
column: 1,
};
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
let node = parser.parse("C3", context);
let node = parser.parse("C3", &Some(context.clone()));
let displace_data = DisplaceData::Column {
sheet: 0,
column: 1,

View File

@@ -1,8 +1,10 @@
use std::collections::HashMap;
use crate::expressions::parser::move_formula::{move_formula, MoveContext};
use crate::expressions::parser::Parser;
use crate::expressions::types::{Area, CellReferenceRC};
use crate::expressions::types::Area;
use super::super::types::CellReferenceRC;
use super::Parser;
#[test]
fn test_move_formula() {
@@ -15,7 +17,7 @@ fn test_move_formula() {
column,
};
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Area is C2:F6
let area = &Area {
@@ -27,7 +29,7 @@ fn test_move_formula() {
};
// formula AB31 will not change
let node = parser.parse("AB31", context);
let node = parser.parse("AB31", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -43,7 +45,7 @@ fn test_move_formula() {
assert_eq!(t, "AB31");
// formula $AB$31 will not change
let node = parser.parse("AB31", context);
let node = parser.parse("AB31", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -59,7 +61,7 @@ fn test_move_formula() {
assert_eq!(t, "AB31");
// but formula D5 will change to N15 (N = D + 10)
let node = parser.parse("D5", context);
let node = parser.parse("D5", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -75,7 +77,7 @@ fn test_move_formula() {
assert_eq!(t, "N15");
// Also formula $D$5 will change to N15 (N = D + 10)
let node = parser.parse("$D$5", context);
let node = parser.parse("$D$5", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -102,7 +104,7 @@ fn test_move_formula_context_offset() {
column,
};
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Area is C2:F6
let area = &Area {
@@ -113,7 +115,7 @@ fn test_move_formula_context_offset() {
height: 5,
};
let node = parser.parse("-X9+C2%", context);
let node = parser.parse("-X9+C2%", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -140,7 +142,7 @@ fn test_move_formula_area_limits() {
column,
};
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Area is C2:F6
let area = &Area {
@@ -152,7 +154,7 @@ fn test_move_formula_area_limits() {
};
// Outside of the area. Not moved
let node = parser.parse("B2+B3+C1+G6+H5", context);
let node = parser.parse("B2+B3+C1+G6+H5", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -168,7 +170,7 @@ fn test_move_formula_area_limits() {
assert_eq!(t, "B2+B3+C1+G6+H5");
// In the area. Moved
let node = parser.parse("C2+F4+F5+F6", context);
let node = parser.parse("C2+F4+F5+F6", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -195,7 +197,7 @@ fn test_move_formula_ranges() {
column,
};
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
let area = &Area {
sheet: 0,
@@ -205,7 +207,7 @@ fn test_move_formula_ranges() {
height: 5,
};
// Ranges inside the area are fully displaced (absolute or not)
let node = parser.parse("SUM(C2:F5)", context);
let node = parser.parse("SUM(C2:F5)", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -220,7 +222,7 @@ fn test_move_formula_ranges() {
);
assert_eq!(t, "SUM(M12:P15)");
let node = parser.parse("SUM($C$2:$F$5)", context);
let node = parser.parse("SUM($C$2:$F$5)", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -236,7 +238,7 @@ fn test_move_formula_ranges() {
assert_eq!(t, "SUM($M$12:$P$15)");
// Ranges completely outside of the area are not touched
let node = parser.parse("SUM(A1:B3)", context);
let node = parser.parse("SUM(A1:B3)", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -251,7 +253,7 @@ fn test_move_formula_ranges() {
);
assert_eq!(t, "SUM(A1:B3)");
let node = parser.parse("SUM($A$1:$B$3)", context);
let node = parser.parse("SUM($A$1:$B$3)", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -267,7 +269,7 @@ fn test_move_formula_ranges() {
assert_eq!(t, "SUM($A$1:$B$3)");
// Ranges that overlap with the area are also NOT displaced
let node = parser.parse("SUM(A1:F5)", context);
let node = parser.parse("SUM(A1:F5)", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -283,7 +285,7 @@ fn test_move_formula_ranges() {
assert_eq!(t, "SUM(A1:F5)");
// Ranges that contain the area are also NOT displaced
let node = parser.parse("SUM(A1:X50)", context);
let node = parser.parse("SUM(A1:X50)", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -318,10 +320,10 @@ fn test_move_formula_wrong_reference() {
height: 5,
};
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Wrong formulas will NOT be displaced
let node = parser.parse("Sheet3!AB31", context);
let node = parser.parse("Sheet3!AB31", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -335,7 +337,7 @@ fn test_move_formula_wrong_reference() {
},
);
assert_eq!(t, "Sheet3!AB31");
let node = parser.parse("Sheet3!$X$9", context);
let node = parser.parse("Sheet3!$X$9", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -350,7 +352,7 @@ fn test_move_formula_wrong_reference() {
);
assert_eq!(t, "Sheet3!$X$9");
let node = parser.parse("SUM(Sheet3!D2:D3)", context);
let node = parser.parse("SUM(Sheet3!D2:D3)", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -377,7 +379,7 @@ fn test_move_formula_misc() {
column,
};
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Area is C2:F6
let area = &Area {
@@ -387,7 +389,7 @@ fn test_move_formula_misc() {
width: 4,
height: 5,
};
let node = parser.parse("X9^C2-F4*H2", context);
let node = parser.parse("X9^C2-F4*H2", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -402,7 +404,7 @@ fn test_move_formula_misc() {
);
assert_eq!(t, "X9^M12-P14*H2");
let node = parser.parse("F5*(-D5)*SUM(A1, X9, $D$5)", context);
let node = parser.parse("F5*(-D5)*SUM(A1, X9, $D$5)", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -417,7 +419,7 @@ fn test_move_formula_misc() {
);
assert_eq!(t, "P15*(-N15)*SUM(A1,X9,$N$15)");
let node = parser.parse("IF(F5 < -D5, X9 & F5, FALSE)", context);
let node = parser.parse("IF(F5 < -D5, X9 & F5, FALSE)", &Some(context.clone()));
let t = move_formula(
&node,
&MoveContext {
@@ -445,7 +447,7 @@ fn test_move_formula_another_sheet() {
};
// we add two sheets and we cut/paste from Sheet1 to Sheet2
let worksheets = vec!["Sheet1".to_string(), "Sheet2".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Area is C2:F6
let area = &Area {
@@ -457,7 +459,10 @@ fn test_move_formula_another_sheet() {
};
// Formula AB31 and JJ3:JJ4 refers to original Sheet1!AB31 and Sheet1!JJ3:JJ4
let node = parser.parse("AB31*SUM(JJ3:JJ4)+SUM(Sheet2!C2:F6)*SUM(C2:F6)", context);
let node = parser.parse(
"AB31*SUM(JJ3:JJ4)+SUM(Sheet2!C2:F6)*SUM(C2:F6)",
&Some(context.clone()),
);
let t = move_formula(
&node,
&MoveContext {

View File

@@ -2,9 +2,9 @@ use std::collections::HashMap;
use crate::expressions::lexer::LexerMode;
use crate::expressions::parser::stringify::{to_rc_format, to_string};
use crate::expressions::parser::Parser;
use crate::expressions::types::CellReferenceRC;
use super::super::parser::stringify::{to_rc_format, to_string};
use super::super::types::CellReferenceRC;
use super::Parser;
struct Formula<'a> {
formula_a1: &'a str,
@@ -14,7 +14,7 @@ struct Formula<'a> {
#[test]
fn test_parser_formulas_with_full_ranges() {
let worksheets = vec!["Sheet1".to_string(), "Second Sheet".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
let formulas = vec![
Formula {
@@ -52,11 +52,11 @@ fn test_parser_formulas_with_full_ranges() {
for formula in &formulas {
let t = parser.parse(
formula.formula_a1,
&CellReferenceRC {
&Some(CellReferenceRC {
sheet: "Sheet1".to_string(),
row: 1,
column: 1,
},
}),
);
assert_eq!(to_rc_format(&t), formula.formula_r1c1);
assert_eq!(to_string(&t, &cell_reference), formula.formula_a1);
@@ -67,11 +67,11 @@ fn test_parser_formulas_with_full_ranges() {
for formula in &formulas {
let t = parser.parse(
formula.formula_r1c1,
&CellReferenceRC {
&Some(CellReferenceRC {
sheet: "Sheet1".to_string(),
row: 1,
column: 1,
},
}),
);
assert_eq!(to_rc_format(&t), formula.formula_r1c1);
assert_eq!(to_string(&t, &cell_reference), formula.formula_a1);
@@ -81,7 +81,7 @@ fn test_parser_formulas_with_full_ranges() {
#[test]
fn test_range_inverse_order() {
let worksheets = vec!["Sheet1".to_string(), "Sheet2".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
let mut parser = Parser::new(worksheets, HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
@@ -93,7 +93,7 @@ fn test_range_inverse_order() {
// D4:C2 => C2:D4
let t = parser.parse(
"SUM(D4:C2)*SUM(Sheet2!D4:C20)*SUM($C$20:D4)",
&cell_reference,
&Some(cell_reference.clone()),
);
assert_eq!(
to_string(&t, &cell_reference),

View File

@@ -6,8 +6,8 @@ use crate::expressions::parser::stringify::to_string;
use crate::expressions::utils::{number_to_column, parse_reference_a1};
use crate::types::{Table, TableColumn, TableStyleInfo};
use crate::expressions::parser::Parser;
use crate::expressions::types::CellReferenceRC;
use super::super::types::CellReferenceRC;
use super::Parser;
fn create_test_table(
table_name: &str,
@@ -63,7 +63,7 @@ fn simple_table() {
let row_count = 3;
let tables = create_test_table("tblIncome", &column_names, "A1", row_count);
let mut parser = Parser::new(worksheets, vec![], tables);
let mut parser = Parser::new(worksheets, tables);
// Reference cell is 'Sheet One'!F2
let cell_reference = CellReferenceRC {
sheet: "Sheet One".to_string(),
@@ -72,7 +72,7 @@ fn simple_table() {
};
let formula = "SUM(tblIncome[[#This Row],[Jan]:[Dec]])";
let t = parser.parse(formula, &cell_reference);
let t = parser.parse(formula, &Some(cell_reference.clone()));
assert_eq!(to_string(&t, &cell_reference), "SUM($A$2:$E$2)");
// Cell A3
@@ -82,7 +82,7 @@ fn simple_table() {
column: 1,
};
let formula = "SUBTOTAL(109, tblIncome[Jan])";
let t = parser.parse(formula, &cell_reference);
let t = parser.parse(formula, &Some(cell_reference.clone()));
assert_eq!(to_string(&t, &cell_reference), "SUBTOTAL(109,$A$2:$A$3)");
// Cell A3 in 'Second Sheet'
@@ -92,7 +92,7 @@ fn simple_table() {
column: 1,
};
let formula = "SUBTOTAL(109, tblIncome[Jan])";
let t = parser.parse(formula, &cell_reference);
let t = parser.parse(formula, &Some(cell_reference.clone()));
assert_eq!(
to_string(&t, &cell_reference),
"SUBTOTAL(109,'Sheet One'!$A$2:$A$3)"

View File

@@ -1,6 +0,0 @@
mod test_general;
mod test_issue_155;
mod test_move_formula;
mod test_ranges;
mod test_stringify;
mod test_tables;

View File

@@ -1,69 +0,0 @@
#![allow(clippy::panic)]
use std::collections::HashMap;
use crate::expressions::parser::stringify::to_string;
use crate::expressions::parser::Parser;
use crate::expressions::types::CellReferenceRC;
#[test]
fn issue_155_parser() {
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
sheet: "Sheet1".to_string(),
row: 2,
column: 2,
};
let t = parser.parse("A$1:A2", &cell_reference);
assert_eq!(to_string(&t, &cell_reference), "A$1:A2");
}
#[test]
fn issue_155_parser_case_2() {
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
sheet: "Sheet1".to_string(),
row: 20,
column: 20,
};
let t = parser.parse("C$1:D2", &cell_reference);
assert_eq!(to_string(&t, &cell_reference), "C$1:D2");
}
#[test]
fn issue_155_parser_only_row() {
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
sheet: "Sheet1".to_string(),
row: 20,
column: 20,
};
// This is tricky, I am not sure what to do in these cases
let t = parser.parse("A$2:B1", &cell_reference);
assert_eq!(to_string(&t, &cell_reference), "A1:B$2");
}
#[test]
fn issue_155_parser_only_column() {
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
sheet: "Sheet1".to_string(),
row: 20,
column: 20,
};
// This is tricky, I am not sure what to do in these cases
let t = parser.parse("D1:$A3", &cell_reference);
assert_eq!(to_string(&t, &cell_reference), "$A1:D3");
}

View File

@@ -1,34 +0,0 @@
#![allow(clippy::panic)]
use std::collections::HashMap;
use crate::expressions::parser::stringify::to_string;
use crate::expressions::parser::Parser;
use crate::expressions::types::CellReferenceRC;
#[test]
fn exp_order() {
let worksheets = vec!["Sheet1".to_string()];
let mut parser = Parser::new(worksheets, vec![], HashMap::new());
// Reference cell is Sheet1!A1
let cell_reference = CellReferenceRC {
sheet: "Sheet1".to_string(),
row: 1,
column: 1,
};
let t = parser.parse("(1 + 2)^3 + 4", &cell_reference);
assert_eq!(to_string(&t, &cell_reference), "(1+2)^3+4");
let t = parser.parse("(C5 + 3)^R4", &cell_reference);
assert_eq!(to_string(&t, &cell_reference), "(C5+3)^R4");
let t = parser.parse("(C5 + 3)^(R4*6)", &cell_reference);
assert_eq!(to_string(&t, &cell_reference), "(C5+3)^(R4*6)");
let t = parser.parse("(C5)^(R4)", &cell_reference);
assert_eq!(to_string(&t, &cell_reference), "C5^R4");
let t = parser.parse("(5)^(4)", &cell_reference);
assert_eq!(to_string(&t, &cell_reference), "5^4");
}

View File

@@ -263,9 +263,7 @@ pub(crate) fn forward_references(
// TODO: Not implemented
Node::ArrayKind(_) => {}
// Do nothing. Note: we could do a blanket _ => {}
Node::DefinedNameKind(_) => {}
Node::TableNameKind(_) => {}
Node::WrongVariableKind(_) => {}
Node::VariableKind(_) => {}
Node::ErrorKind(_) => {}
Node::ParseErrorKind { .. } => {}
Node::EmptyArgKind => {}

View File

@@ -245,9 +245,6 @@ pub fn format_number(value_original: f64, format: &str, locale: &Locale) -> Form
}
ParsePart::Number(p) => {
let mut text = "".to_string();
if let Some(c) = p.currency {
text = format!("{}", c);
}
let tokens = &p.tokens;
value = value * 100.0_f64.powi(p.percent) / (1000.0_f64.powi(p.comma));
// p.precision is the number of significant digits _after_ the decimal point

View File

@@ -10,7 +10,6 @@ pub struct Lexer {
pub enum Token {
Color(i32), // [Red] or [Color 23]
Condition(Compare, f64), // [<=100] (Comparator, number)
Currency(char), // [$€] ($ currency symbol)
Literal(char), // €, $, (, ), /, :, +, -, ^, ', {, }, <, =, !, ~, > and space or scaped \X
Spacer(char), // *X
Ghost(char), // _X
@@ -275,15 +274,6 @@ impl Lexer {
self.set_error("Failed to parse condition");
Token::ILLEGAL
}
} else if c == '$' {
// currency
self.read_next_char();
if let Some(currency) = self.read_next_char() {
self.read_next_char();
return Token::Currency(currency);
}
self.set_error("Failed to parse currency");
Token::ILLEGAL
} else {
// Color
if let Some(index) = self.consume_color() {

View File

@@ -74,7 +74,6 @@ mod test;
//
// * Color [Red] or [Color 23] or [Color23]
// * Conditions [<100]
// * Currency [$€]
// * Space _X when X is any given char
// * A spacer of chars: *X where X is repeated as much as possible
// * Literals: $, (, ), :, +, - and space

View File

@@ -40,7 +40,6 @@ pub struct NumberPart {
pub is_scientific: bool,
pub scientific_minus: bool,
pub exponent_digit_count: i32,
pub currency: Option<char>,
}
pub struct DatePart {
@@ -115,7 +114,6 @@ impl Parser {
let mut exponent_digit_count = 0;
let mut number = 'i';
let mut index = 0;
let mut currency = None;
while token != Token::EOF && token != Token::Separator {
let next_token = self.lexer.next_token();
@@ -172,9 +170,6 @@ impl Parser {
Token::Condition(cmp, value) => {
condition = Some((cmp, value));
}
Token::Currency(c) => {
currency = Some(c);
}
Token::QuestionMark => {
tokens.push(TextToken::Digit(Digit {
kind: '?',
@@ -296,7 +291,6 @@ impl Parser {
is_scientific,
scientific_minus,
exponent_digit_count,
currency,
})
}
}

View File

@@ -76,14 +76,6 @@ fn test_color() {
assert_eq!(format_number(3.1, "[blue]0.00", locale).color, Some(4));
}
#[test]
fn dollar_euro() {
let locale = get_default_locale();
let format = "[$€]#,##0.00";
let t = format_number(3.1, format, locale);
assert_eq!(t.text, "€3.10");
}
#[test]
fn test_parts() {
let locale = get_default_locale();

View File

@@ -89,9 +89,6 @@ fn compute_future_value(
if rate == 0.0 {
return Ok(-pv - pmt * nper);
}
if rate == -1.0 && nper < 0.0 {
return Err((Error::DIV, "Divide by zero".to_string()));
}
let rate_nper = (1.0 + rate).powf(nper);
let fv = if period_start {

View File

@@ -247,68 +247,46 @@ impl Model {
return CalcResult::Number(cell.sheet as f64 + 1.0);
}
// The arg could be a defined name or a table
// let = &args[0];
match &args[0] {
Node::DefinedNameKind((name, scope)) => {
// Let's see if it is a defined name
if let Some(defined_name) = self
.parsed_defined_names
.get(&(*scope, name.to_lowercase()))
{
match defined_name {
ParsedDefinedName::CellReference(reference) => {
return CalcResult::Number(reference.sheet as f64 + 1.0)
}
ParsedDefinedName::RangeReference(range) => {
return CalcResult::Number(range.left.sheet as f64 + 1.0)
}
ParsedDefinedName::InvalidDefinedNameFormula => {
return CalcResult::Error {
error: Error::ERROR,
origin: cell,
message: "Invalid name".to_string(),
};
}
let arg = &args[0];
if let Node::VariableKind(name) = arg {
// Let's see if it is a defined name
if let Some(defined_name) = self.parsed_defined_names.get(&(None, name.to_lowercase()))
{
match defined_name {
ParsedDefinedName::CellReference(reference) => {
return CalcResult::Number(reference.sheet as f64 + 1.0)
}
} else {
// This should never happen
return CalcResult::Error {
error: Error::ERROR,
origin: cell,
message: "Invalid name".to_string(),
};
}
}
Node::TableNameKind(name) => {
// Now let's see if it is a table
for (table_name, table) in &self.workbook.tables {
if table_name == name {
if let Some(sheet_index) = self.get_sheet_index_by_name(&table.sheet_name) {
return CalcResult::Number(sheet_index as f64 + 1.0);
} else {
break;
}
ParsedDefinedName::RangeReference(range) => {
return CalcResult::Number(range.left.sheet as f64 + 1.0)
}
ParsedDefinedName::InvalidDefinedNameFormula => {
return CalcResult::Error {
error: Error::NA,
origin: cell,
message: "Invalid name".to_string(),
};
}
}
}
Node::WrongVariableKind(name) => {
return CalcResult::Error {
error: Error::NAME,
origin: cell,
message: format!("Name not found: {name}"),
}
}
arg => {
// Now it should be the name of a sheet
let sheet_name = match self.get_string(arg, cell) {
Ok(s) => s,
Err(e) => return e,
};
if let Some(sheet_index) = self.get_sheet_index_by_name(&sheet_name) {
return CalcResult::Number(sheet_index as f64 + 1.0);
// Now let's see if it is a table
for (table_name, table) in &self.workbook.tables {
if table_name == name {
if let Some(sheet_index) = self.get_sheet_index_by_name(&table.sheet_name) {
return CalcResult::Number(sheet_index as f64 + 1.0);
} else {
break;
}
}
}
}
// Now it should be the name of a sheet
let sheet_name = match self.get_string(arg, cell) {
Ok(s) => s,
Err(e) => return e,
};
if let Some(sheet_index) = self.get_sheet_index_by_name(&sheet_name) {
return CalcResult::Number(sheet_index as f64 + 1.0);
}
CalcResult::Error {
error: Error::NA,
origin: cell,

View File

@@ -66,61 +66,24 @@ impl Model {
}
pub(crate) fn fn_and(&mut self, args: &[Node], cell: CellReferenceIndex) -> CalcResult {
self.logical_nary(
args,
cell,
|acc, value| acc.unwrap_or(true) && value,
Some(false),
)
}
pub(crate) fn fn_or(&mut self, args: &[Node], cell: CellReferenceIndex) -> CalcResult {
self.logical_nary(
args,
cell,
|acc, value| acc.unwrap_or(false) || value,
Some(true),
)
}
pub(crate) fn fn_xor(&mut self, args: &[Node], cell: CellReferenceIndex) -> CalcResult {
self.logical_nary(args, cell, |acc, value| acc.unwrap_or(false) ^ value, None)
}
/// Base function for AND, OR, XOR. These are all n-ary functions that perform a boolean operation on a series of
/// boolean values. These boolean values are sourced from `args`. Note that there is not a 1-1 relationship between
/// arguments and boolean values evaluated (see how Ranges are handled for example).
///
/// Each argument in `args` is evaluated and the resulting value is interpreted as a boolean as follows:
/// - Boolean: The value is used directly.
/// - Number: 0 is FALSE, all other values are TRUE.
/// - Range: Each cell in the range is evaluated as if they were individual arguments with some caveats
/// - Empty arg: FALSE
/// - Empty cell & String: Ignored, behaves exactly like the argument wasn't passed in at all
/// - Error: Propagated
///
/// If no arguments are provided, or all arguments are ignored, the function returns a #VALUE! error
///
/// **`fold_fn`:** The function that combines the running result with the next value boolean value. The running result
/// starts as `None`.
///
/// **`short_circuit_value`:** If the running result reaches `short_circuit_value`, the function returns early.
fn logical_nary(
&mut self,
args: &[Node],
cell: CellReferenceIndex,
fold_fn: fn(Option<bool>, bool) -> bool,
short_circuit_value: Option<bool>,
) -> CalcResult {
if args.is_empty() {
return CalcResult::new_args_number_error(cell);
}
let mut result = None;
let mut true_count = 0;
for arg in args {
match self.evaluate_node_in_context(arg, cell) {
CalcResult::Boolean(value) => result = Some(fold_fn(result, value)),
CalcResult::Number(value) => result = Some(fold_fn(result, value != 0.0)),
CalcResult::Boolean(b) => {
if !b {
return CalcResult::Boolean(false);
}
true_count += 1;
}
CalcResult::Number(value) => {
if value == 0.0 {
return CalcResult::Boolean(false);
}
true_count += 1;
}
CalcResult::String(_value) => {
true_count += 1;
}
CalcResult::Range { left, right } => {
if left.sheet != right.sheet {
return CalcResult::new_error(
@@ -136,58 +99,158 @@ impl Model {
row,
column,
}) {
CalcResult::Boolean(value) => result = Some(fold_fn(result, value)),
CalcResult::Boolean(b) => {
if !b {
return CalcResult::Boolean(false);
}
true_count += 1;
}
CalcResult::Number(value) => {
result = Some(fold_fn(result, value != 0.0))
if value == 0.0 {
return CalcResult::Boolean(false);
}
true_count += 1;
}
CalcResult::String(_value) => {
true_count += 1;
}
error @ CalcResult::Error { .. } => return error,
CalcResult::EmptyArg => {} // unreachable
CalcResult::Range { .. }
| CalcResult::String { .. }
| CalcResult::EmptyCell => {}
}
if let (Some(current_result), Some(short_circuit_value)) =
(result, short_circuit_value)
{
if current_result == short_circuit_value {
return CalcResult::Boolean(current_result);
}
CalcResult::Range { .. } => {}
CalcResult::EmptyCell | CalcResult::EmptyArg => {}
}
}
}
}
error @ CalcResult::Error { .. } => return error,
CalcResult::EmptyArg => result = Some(result.unwrap_or(false)),
// Strings are ignored unless they are "TRUE" or "FALSE" (case insensitive). EXCEPT if the string value
// comes from a reference, in which case it is always ignored regardless of its value.
CalcResult::String(..) => {
if !matches!(arg, Node::ReferenceKind { .. }) {
if let Ok(f) = self.get_boolean(arg, cell) {
result = Some(fold_fn(result, f));
CalcResult::EmptyCell | CalcResult::EmptyArg => {}
};
}
if true_count == 0 {
return CalcResult::new_error(
Error::VALUE,
cell,
"Boolean values not found".to_string(),
);
}
CalcResult::Boolean(true)
}
pub(crate) fn fn_or(&mut self, args: &[Node], cell: CellReferenceIndex) -> CalcResult {
let mut result = false;
for arg in args {
match self.evaluate_node_in_context(arg, cell) {
CalcResult::Boolean(value) => result = value || result,
CalcResult::Number(value) => {
if value != 0.0 {
return CalcResult::Boolean(true);
}
}
CalcResult::String(_value) => {
return CalcResult::Boolean(true);
}
CalcResult::Range { left, right } => {
if left.sheet != right.sheet {
return CalcResult::new_error(
Error::VALUE,
cell,
"Ranges are in different sheets".to_string(),
);
}
for row in left.row..(right.row + 1) {
for column in left.column..(right.column + 1) {
match self.evaluate_cell(CellReferenceIndex {
sheet: left.sheet,
row,
column,
}) {
CalcResult::Boolean(value) => {
result = value || result;
}
CalcResult::Number(value) => {
if value != 0.0 {
return CalcResult::Boolean(true);
}
}
CalcResult::String(_value) => {
return CalcResult::Boolean(true);
}
error @ CalcResult::Error { .. } => return error,
CalcResult::Range { .. } => {}
CalcResult::EmptyCell | CalcResult::EmptyArg => {}
}
}
}
}
// References to empty cells are ignored. If all args are ignored the result is #VALUE!
CalcResult::EmptyCell => {}
}
error @ CalcResult::Error { .. } => return error,
CalcResult::EmptyCell | CalcResult::EmptyArg => {}
};
}
CalcResult::Boolean(result)
}
if let (Some(current_result), Some(short_circuit_value)) = (result, short_circuit_value)
{
if current_result == short_circuit_value {
return CalcResult::Boolean(current_result);
/// XOR(logical1, [logical]*,...)
/// Logical1 is required, subsequent logical values are optional. Can be logical values, arrays, or references.
/// The result of XOR is TRUE when the number of TRUE inputs is odd and FALSE when the number of TRUE inputs is even.
pub(crate) fn fn_xor(&mut self, args: &[Node], cell: CellReferenceIndex) -> CalcResult {
let mut true_count = 0;
let mut false_count = 0;
for arg in args {
match self.evaluate_node_in_context(arg, cell) {
CalcResult::Boolean(b) => {
if b {
true_count += 1;
} else {
false_count += 1;
}
}
}
CalcResult::Number(value) => {
if value != 0.0 {
true_count += 1;
} else {
false_count += 1;
}
}
CalcResult::Range { left, right } => {
if left.sheet != right.sheet {
return CalcResult::new_error(
Error::VALUE,
cell,
"Ranges are in different sheets".to_string(),
);
}
for row in left.row..(right.row + 1) {
for column in left.column..(right.column + 1) {
match self.evaluate_cell(CellReferenceIndex {
sheet: left.sheet,
row,
column,
}) {
CalcResult::Boolean(b) => {
if b {
true_count += 1;
} else {
false_count += 1;
}
}
CalcResult::Number(value) => {
if value != 0.0 {
true_count += 1;
} else {
false_count += 1;
}
}
_ => {}
}
}
}
}
_ => {}
};
}
if let Some(result) = result {
CalcResult::Boolean(result)
} else {
CalcResult::new_error(
Error::VALUE,
cell,
"No logical values in argument list".to_string(),
)
if true_count == 0 && false_count == 0 {
return CalcResult::new_error(Error::VALUE, cell, "No booleans found".to_string());
}
CalcResult::Boolean(true_count % 2 == 1)
}
/// =SWITCH(expression, case1, value1, [case, value]*, [default])

View File

@@ -140,7 +140,6 @@ pub enum Function {
Countifs,
Maxifs,
Minifs,
Geomean,
// Date and time
Date,
@@ -249,7 +248,7 @@ pub enum Function {
}
impl Function {
pub fn into_iter() -> IntoIter<Function, 195> {
pub fn into_iter() -> IntoIter<Function, 194> {
[
Function::And,
Function::False,
@@ -349,7 +348,6 @@ impl Function {
Function::Countifs,
Function::Maxifs,
Function::Minifs,
Function::Geomean,
Function::Year,
Function::Day,
Function::Month,
@@ -613,7 +611,6 @@ impl Function {
"COUNTIFS" => Some(Function::Countifs),
"MAXIFS" | "_XLFN.MAXIFS" => Some(Function::Maxifs),
"MINIFS" | "_XLFN.MINIFS" => Some(Function::Minifs),
"GEOMEAN" => Some(Function::Geomean),
// Date and Time
"YEAR" => Some(Function::Year),
"DAY" => Some(Function::Day),
@@ -821,7 +818,6 @@ impl fmt::Display for Function {
Function::Countifs => write!(f, "COUNTIFS"),
Function::Maxifs => write!(f, "MAXIFS"),
Function::Minifs => write!(f, "MINIFS"),
Function::Geomean => write!(f, "GEOMEAN"),
Function::Year => write!(f, "YEAR"),
Function::Day => write!(f, "DAY"),
Function::Month => write!(f, "MONTH"),
@@ -1058,7 +1054,6 @@ impl Model {
Function::Countifs => self.fn_countifs(args, cell),
Function::Maxifs => self.fn_maxifs(args, cell),
Function::Minifs => self.fn_minifs(args, cell),
Function::Geomean => self.fn_geomean(args, cell),
// Date and Time
Function::Year => self.fn_year(args, cell),
Function::Day => self.fn_day(args, cell),

View File

@@ -635,85 +635,4 @@ impl Model {
}
CalcResult::Number(max)
}
pub(crate) fn fn_geomean(&mut self, args: &[Node], cell: CellReferenceIndex) -> CalcResult {
if args.is_empty() {
return CalcResult::new_args_number_error(cell);
}
let mut count = 0.0;
let mut product = 1.0;
for arg in args {
match self.evaluate_node_in_context(arg, cell) {
CalcResult::Number(value) => {
count += 1.0;
product *= value;
}
CalcResult::Boolean(b) => {
if let Node::ReferenceKind { .. } = arg {
} else {
product *= if b { 1.0 } else { 0.0 };
count += 1.0;
}
}
CalcResult::Range { left, right } => {
if left.sheet != right.sheet {
return CalcResult::new_error(
Error::VALUE,
cell,
"Ranges are in different sheets".to_string(),
);
}
for row in left.row..(right.row + 1) {
for column in left.column..(right.column + 1) {
match self.evaluate_cell(CellReferenceIndex {
sheet: left.sheet,
row,
column,
}) {
CalcResult::Number(value) => {
count += 1.0;
product *= value;
}
error @ CalcResult::Error { .. } => return error,
CalcResult::Range { .. } => {
return CalcResult::new_error(
Error::ERROR,
cell,
"Unexpected Range".to_string(),
);
}
_ => {}
}
}
}
}
error @ CalcResult::Error { .. } => return error,
CalcResult::String(s) => {
if let Node::ReferenceKind { .. } = arg {
// Do nothing
} else if let Ok(t) = s.parse::<f64>() {
product *= t;
count += 1.0;
} else {
return CalcResult::Error {
error: Error::VALUE,
origin: cell,
message: "Argument cannot be cast into number".to_string(),
};
}
}
_ => {
// Ignore everything else
}
};
}
if count == 0.0 {
return CalcResult::Error {
error: Error::DIV,
origin: cell,
message: "Division by Zero".to_string(),
};
}
CalcResult::Number(product.powf(1.0 / count))
}
}

View File

@@ -25,8 +25,6 @@
#![doc = include_str!("../examples/formulas_and_errors.rs")]
//! ```
#![warn(clippy::print_stdout)]
pub mod calc_result;
pub mod cell;
pub mod expressions;

View File

@@ -8,15 +8,14 @@ use crate::{
cell::CellValue,
constants::{self, LAST_COLUMN, LAST_ROW},
expressions::{
lexer::LexerMode,
parser::{
move_formula::{move_formula, MoveContext},
stringify::{rename_defined_name_in_node, to_rc_format, to_string},
stringify::{to_rc_format, to_string},
Node, Parser,
},
token::{get_error_by_name, Error, OpCompare, OpProduct, OpSum, OpUnary},
types::*,
utils::{self, is_valid_column_number, is_valid_identifier, is_valid_row},
utils::{self, is_valid_column_number, is_valid_row, parse_reference_a1},
},
formatter::{
format::{format_number, parse_formatted_number},
@@ -73,7 +72,6 @@ pub(crate) enum CellState {
}
/// A parsed formula for a defined name
#[derive(Clone)]
pub(crate) enum ParsedDefinedName {
/// CellReference (`=C4`)
CellReference(CellReferenceIndex),
@@ -81,6 +79,9 @@ pub(crate) enum ParsedDefinedName {
RangeReference(Range),
/// `=SomethingElse`
InvalidDefinedNameFormula,
// TODO: Support constants in defined names
// TODO: Support formulas in defined names
// TODO: Support tables in defined names
}
/// A dynamical IronCalc model.
@@ -416,40 +417,38 @@ impl Model {
// TODO: NOT IMPLEMENTED
CalcResult::new_error(Error::NIMPL, cell, "Arrays not implemented".to_string())
}
DefinedNameKind((name, scope)) => {
if let Ok(Some(parsed_defined_name)) = self.get_parsed_defined_name(name, *scope) {
VariableKind(defined_name) => {
let parsed_defined_name = self
.parsed_defined_names
.get(&(Some(cell.sheet), defined_name.to_lowercase())) // try getting local defined name
.or_else(|| {
self.parsed_defined_names
.get(&(None, defined_name.to_lowercase()))
}); // fallback to global
if let Some(parsed_defined_name) = parsed_defined_name {
match parsed_defined_name {
ParsedDefinedName::CellReference(reference) => {
self.evaluate_cell(reference)
self.evaluate_cell(*reference)
}
ParsedDefinedName::RangeReference(range) => CalcResult::Range {
left: range.left,
right: range.right,
},
ParsedDefinedName::InvalidDefinedNameFormula => CalcResult::new_error(
Error::NAME,
Error::NIMPL,
cell,
format!("Defined name \"{}\" is not a reference.", name),
format!("Defined name \"{}\" is not a reference.", defined_name),
),
}
} else {
CalcResult::new_error(
Error::NAME,
cell,
format!("Defined name \"{}\" not found.", name),
format!("Defined name \"{}\" not found.", defined_name),
)
}
}
TableNameKind(s) => CalcResult::new_error(
Error::NAME,
cell,
format!("table name \"{}\" not supported.", s),
),
WrongVariableKind(s) => CalcResult::new_error(
Error::NAME,
cell,
format!("Variable name \"{}\" not found.", s),
),
CompareKind { kind, left, right } => {
let l = self.evaluate_node_in_context(left, cell);
if l.is_error() {
@@ -683,13 +682,6 @@ impl Model {
Err(format!("Invalid color: {}", color))
}
/// Changes the visibility of a sheet
pub fn set_sheet_state(&mut self, sheet: u32, state: SheetState) -> Result<(), String> {
let worksheet = self.workbook.worksheet_mut(sheet)?;
worksheet.state = state;
Ok(())
}
/// Makes the grid lines in the sheet visible (`true`) or hidden (`false`)
pub fn set_show_grid_lines(&mut self, sheet: u32, show_grid_lines: bool) -> Result<(), String> {
let worksheet = self.workbook.worksheet_mut(sheet)?;
@@ -755,6 +747,29 @@ impl Model {
self.workbook.worksheet(sheet)?.is_empty_cell(row, column)
}
/// Returns 'true' if the cell belongs to any Merged cells
/// # Examples
///
/// ```rust
/// # use ironcalc_base::Model;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut model = Model::new_empty("model", "en", "UTC")?;
/// model.merge_cells(0, "A1:D5");
/// assert_eq!(model.is_part_of_merged_cells(0, 1, 2)?, true);
/// # Ok(())
/// # }
/// ```
pub fn is_part_of_merged_cells(
&self,
sheet: u32,
row: i32,
column: i32,
) -> Result<bool, String> {
self.workbook
.worksheet(sheet)?
.is_part_of_merged_cells(row, column)
}
pub(crate) fn evaluate_cell(&mut self, cell_reference: CellReferenceIndex) -> CalcResult {
let row_data = match self.workbook.worksheets[cell_reference.sheet as usize]
.sheet_data
@@ -865,11 +880,6 @@ impl Model {
let worksheet_names = worksheets.iter().map(|s| s.get_name()).collect();
let defined_names = workbook
.get_defined_names_with_scope()
.iter()
.map(|s| (s.0.to_owned(), s.1))
.collect();
// add all tables
// let mut tables = Vec::new();
// for worksheet in worksheets {
@@ -879,7 +889,7 @@ impl Model {
// }
// tables.push(tables_in_sheet);
// }
let parser = Parser::new(worksheet_names, defined_names, workbook.tables.clone());
let parser = Parser::new(worksheet_names, workbook.tables.clone());
let cells = HashMap::new();
let locale = get_locale(&workbook.settings.locale)
.map_err(|_| "Invalid locale".to_string())?
@@ -1040,7 +1050,7 @@ impl Model {
column: source.column,
};
let formula_str = move_formula(
&self.parser.parse(formula, &cell_reference),
&self.parser.parse(formula, &Some(cell_reference)),
&MoveContext {
source_sheet_name: &source_sheet_name,
row: source.row,
@@ -1148,7 +1158,7 @@ impl Model {
row: source.row,
column: source.column,
};
let formula = &self.parser.parse(formula_str, &cell_reference);
let formula = &self.parser.parse(formula_str, &Some(cell_reference));
let cell_reference = CellReferenceRC {
sheet: target_sheet_name,
row: target.row,
@@ -1238,6 +1248,14 @@ impl Model {
column: i32,
value: &str,
) -> Result<(), String> {
// Checking first whether cell we are updating is part of Merged cells
// if so returning with Err
if self.is_part_of_merged_cells(sheet, row, column)? {
return Err(format!(
"Cell row : {}, col : {} is part of merged cells block, so singular update to the cell is not possible",
row, column
));
}
let style_index = self.get_cell_style_index(sheet, row, column)?;
let new_style_index;
if common::value_needs_quoting(value, &self.language) {
@@ -1288,6 +1306,15 @@ impl Model {
column: i32,
value: bool,
) -> Result<(), String> {
// Checking first whether cell we are updating is part of Merged cells
// if so returning with Err
if self.is_part_of_merged_cells(sheet, row, column)? {
return Err(format!(
"Cell row : {}, col : {} is part of merged cells block, so singular update to the cell is not possible",
row, column
));
}
let style_index = self.get_cell_style_index(sheet, row, column)?;
let new_style_index = if self.workbook.styles.style_is_quote_prefix(style_index) {
self.workbook
@@ -1330,6 +1357,14 @@ impl Model {
column: i32,
value: f64,
) -> Result<(), String> {
// Checking first whether cell we are updating is part of Merged cells
// if so returning with Err
if self.is_part_of_merged_cells(sheet, row, column)? {
return Err(format!(
"Cell row : {}, col : {} is part of merged cells block, so singular update to the cell is not possible",
row, column
));
}
let style_index = self.get_cell_style_index(sheet, row, column)?;
let new_style_index = if self.workbook.styles.style_is_quote_prefix(style_index) {
self.workbook
@@ -1375,6 +1410,12 @@ impl Model {
column: i32,
formula: String,
) -> Result<(), String> {
if self.is_part_of_merged_cells(sheet, row, column)? {
return Err(format!(
"Cell row : {}, col : {} is part of merged cells block, so singular update to the cell is not possible",
row, column
));
}
let mut style_index = self.get_cell_style_index(sheet, row, column)?;
if self.workbook.styles.style_is_quote_prefix(style_index) {
style_index = self
@@ -1427,6 +1468,14 @@ impl Model {
column: i32,
value: String,
) -> Result<(), String> {
// Checking first whether cell we are updating is part of Merged cells
// if so returning with Err
if self.is_part_of_merged_cells(sheet, row, column)? {
return Err(format!(
"Cell row : {}, col : {} is part of merged cells block, so singular update to the cell is not possible",
row, column
));
}
// If value starts with "'" then we force the style to be quote_prefix
let style_index = self.get_cell_style_index(sheet, row, column)?;
if let Some(new_value) = value.strip_prefix('\'') {
@@ -1524,11 +1573,13 @@ impl Model {
column,
};
let shared_formulas = &mut worksheet.shared_formulas;
let mut parsed_formula = self.parser.parse(formula, &cell_reference);
let mut parsed_formula = self.parser.parse(formula, &Some(cell_reference.clone()));
// If the formula fails to parse try adding a parenthesis
// SUM(A1:A3 => SUM(A1:A3)
if let Node::ParseErrorKind { .. } = parsed_formula {
let new_parsed_formula = self.parser.parse(&format!("{})", formula), &cell_reference);
let new_parsed_formula = self
.parser
.parse(&format!("{})", formula), &Some(cell_reference));
match new_parsed_formula {
Node::ParseErrorKind { .. } => {}
_ => parsed_formula = new_parsed_formula,
@@ -1607,42 +1658,6 @@ impl Model {
.set_cell_with_number(row, column, value, style)
}
// Helper function that returns a defined name given the name and scope
fn get_parsed_defined_name(
&self,
name: &str,
scope: Option<u32>,
) -> Result<Option<ParsedDefinedName>, String> {
let name_upper = name.to_uppercase();
for (key, df) in &self.parsed_defined_names {
if key.1.to_uppercase() == name_upper && key.0 == scope {
return Ok(Some(df.clone()));
}
}
Ok(None)
}
// Returns the formula for a defined name
pub(crate) fn get_defined_name_formula(
&self,
name: &str,
scope: Option<u32>,
) -> Result<String, String> {
let name_upper = name.to_uppercase();
let defined_names = &self.workbook.defined_names;
let sheet_id = match scope {
Some(index) => Some(self.workbook.worksheet(index)?.sheet_id),
None => None,
};
for df in defined_names {
if df.name.to_uppercase() == name_upper && df.sheet_id == sheet_id {
return Ok(df.formula.clone());
}
}
Err("Defined name not found".to_string())
}
/// Gets the Excel Value (Bool, Number, String) of a cell
///
/// See also:
@@ -1975,6 +1990,7 @@ impl Model {
/// Sets the number of frozen rows to `frozen_rows` in the workbook.
/// Fails if `frozen`_rows` is either too small (<0) or too large (>LAST_ROW)`
pub fn set_frozen_rows(&mut self, sheet: u32, frozen_rows: i32) -> Result<(), String> {
// TODO: What is frozen rows and do we need to take of this if row we are frozing is part of merge cells ?
if let Some(worksheet) = self.workbook.worksheets.get_mut(sheet as usize) {
if frozen_rows < 0 {
return Err("Frozen rows cannot be negative".to_string());
@@ -1992,6 +2008,7 @@ impl Model {
/// Sets the number of frozen columns to `frozen_column` in the workbook.
/// Fails if `frozen`_columns` is either too small (<0) or too large (>LAST_COLUMN)`
pub fn set_frozen_columns(&mut self, sheet: u32, frozen_columns: i32) -> Result<(), String> {
// TODO: What is frozen columns and do we need to take of this if column we are frozing is part of merge cells ?
if let Some(worksheet) = self.workbook.worksheets.get_mut(sheet as usize) {
if frozen_columns < 0 {
return Err("Frozen columns cannot be negative".to_string());
@@ -2034,135 +2051,162 @@ impl Model {
.set_row_height(column, height)
}
/// Adds a new defined name
pub fn new_defined_name(
&mut self,
name: &str,
scope: Option<u32>,
formula: &str,
) -> Result<(), String> {
if !is_valid_identifier(name) {
return Err("Invalid defined name".to_string());
};
let name_upper = name.to_uppercase();
let defined_names = &self.workbook.defined_names;
let sheet_id = match scope {
Some(index) => Some(self.workbook.worksheet(index)?.sheet_id),
None => None,
};
// if the defined name already exist return error
for df in defined_names {
if df.name.to_uppercase() == name_upper && df.sheet_id == sheet_id {
return Err("Defined name already exists".to_string());
fn parse_merged_range(&mut self, range: &str) -> Result<(i32, i32, i32, i32), String> {
let parts: Vec<&str> = range.split(':').collect();
if parts.len() == 1 {
Err(format!("Invalid range: '{}'", range))
} else if parts.len() == 2 {
match (parse_reference_a1(parts[0]), parse_reference_a1(parts[1])) {
(Some(left), Some(right)) => {
return Ok((left.row, left.column, right.row, right.column));
}
_ => return Err(format!("Invalid range: '{}'", range)),
}
} else {
return Err(format!("Invalid range: '{}'", range));
}
}
// Implementing public APIS related to Merge cells handling
/// Merges given selected cells
/// If no overlap, it will create that merged cells with left most top cell value representing the whole merged cells
/// If new merge cells creation overlaps with any of the existing merged cells, Overlapped merged cells gets unmerged
/// and new merge cells gets added
///
/// # Examples
///
/// ```rust
/// # use ironcalc_base::Model;
/// # use ironcalc_base::cell::CellValue;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut model = Model::new_empty("model", "en", "UTC")?;
/// model.merge_cells(0, "D4:F6").unwrap();
/// model.merge_cells(0, "A1:B4").unwrap();
/// assert_eq!(model.workbook.worksheet(0).unwrap().merged_cells_list.len(), 2);
/// # Ok(())
/// # }
/// ```
///
/// See also:
/// * [Model::update_cell_with_formula()]
/// * [Model::update_cell_with_number()]
/// * [Model::update_cell_with_bool()]
/// * [Model::update_cell_with_text()]
pub fn merge_cells(&mut self, sheet: u32, range_ref: &str) -> Result<(), String> {
match self.parse_merged_range(range_ref) {
Ok(parsed_merge_cell_range) => {
// ATTENTION 2: Below thing we can support here but keeping it simple
// Web or different client needs to keep this in mind
// User can give errored parse ranges like C3:A1
// Where col_start and row_start and is greated then col_end and row_end
// Return error in these scenario
if parsed_merge_cell_range.0 > parsed_merge_cell_range.2
|| parsed_merge_cell_range.1 > parsed_merge_cell_range.3
{
return Err(
"Invalid parse range. Merge Mother cell always be top left cell"
.to_string(),
);
}
let mut merged_cells_overlaped_list: Vec<bool> = Vec::new();
// checking whether our new range overlaps with any of the already existing merged cells
// if so, need to unmerge those and create this new one
{
let worksheet = self.workbook.worksheet(sheet)?;
let merged_cells = worksheet.get_merged_cells_list();
for merge_node in merged_cells {
// checking whether any overlapping exist with this merge cell
if !(parsed_merge_cell_range.1 > merge_node.3
|| parsed_merge_cell_range.3 < merge_node.1
|| parsed_merge_cell_range.0 > merge_node.2
|| parsed_merge_cell_range.2 < merge_node.0)
{
// overlap has happened
merged_cells_overlaped_list.push(true);
} else {
merged_cells_overlaped_list.push(false);
}
}
}
if !merged_cells_overlaped_list.is_empty() {
// Lets take Mutable ref to Merge cell and deletes all those nodes which has overlapped
let worksheet = self.workbook.worksheet_mut(sheet)?;
let merged_cells_list_mut = worksheet.get_merged_cells_list_mut();
let mut merged_cells_overlaped_list_iter = merged_cells_overlaped_list.iter();
merged_cells_list_mut
.retain(|_| !(*merged_cells_overlaped_list_iter.next().unwrap()))
}
// Now need to update (n*m - 1) cells with empty cell ( except the Mother cell )
for row_index in parsed_merge_cell_range.0..=parsed_merge_cell_range.2 {
for col_index in parsed_merge_cell_range.1..=parsed_merge_cell_range.3 {
// skip Mother cell
if row_index == parsed_merge_cell_range.0
&& col_index == parsed_merge_cell_range.2
{
continue;
}
//update the node with empty cell
{
self.workbook.worksheet_mut(sheet)?.update_cell(
row_index,
col_index,
Cell::EmptyCell { s: 0 },
)?;
}
}
}
let new_merged_cells = MergedCells::new(parsed_merge_cell_range);
{
self.workbook
.worksheet_mut(sheet)?
.merged_cells_list
.push(new_merged_cells);
}
}
Err(err) => {
return Err(err);
}
}
self.workbook.defined_names.push(DefinedName {
name: name.to_string(),
formula: formula.to_string(),
sheet_id,
});
self.reset_parsed_structures();
Ok(())
}
/// Delete defined name of name and scope
pub fn delete_defined_name(&mut self, name: &str, scope: Option<u32>) -> Result<(), String> {
let name_upper = name.to_uppercase();
let defined_names = &self.workbook.defined_names;
let sheet_id = match scope {
Some(index) => Some(self.workbook.worksheet(index)?.sheet_id),
None => None,
};
let mut index = None;
for (i, df) in defined_names.iter().enumerate() {
if df.name.to_uppercase() == name_upper && df.sheet_id == sheet_id {
index = Some(i);
/// Unmerges a given/selected merged cells
/// Once unmerged, only top most left corner value gets retained and all the others will have empty cell
/// # Examples
///
/// ```rust
/// # use ironcalc_base::Model;
/// # use ironcalc_base::cell::CellValue;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut model = Model::new_empty("model", "en", "UTC")?;
/// model.merge_cells(0, "D4:F6");
/// model.unmerge_cells(0, "D4:F6");
/// # Ok(())
/// # }
/// ```
pub fn unmerge_cells(&mut self, sheet: u32, range_ref: &str) -> Result<(), String> {
let worksheet = self.workbook.worksheet(sheet)?;
let merged_cells = worksheet.get_merged_cells_list();
for (index, merge_node) in merged_cells.iter().enumerate() {
let merge_block_range_ref = merge_node.get_merged_cells_str_ref()?;
// finding the merge cell node to be deleted
if merge_block_range_ref.as_str() == range_ref {
// Merge cell to be deleted is found
self.workbook
.worksheet_mut(sheet)?
.merged_cells_list
.remove(index);
return Ok(());
}
}
if let Some(i) = index {
self.workbook.defined_names.remove(i);
self.reset_parsed_structures();
Ok(())
} else {
Err("Defined name not found".to_string())
}
}
/// Update defined name
pub fn update_defined_name(
&mut self,
name: &str,
scope: Option<u32>,
new_name: &str,
new_scope: Option<u32>,
new_formula: &str,
) -> Result<(), String> {
if !is_valid_identifier(new_name) {
return Err("Invalid defined name".to_string());
};
let name_upper = name.to_uppercase();
let new_name_upper = new_name.to_uppercase();
if name_upper != new_name_upper || scope != new_scope {
for key in self.parsed_defined_names.keys() {
if key.1.to_uppercase() == new_name_upper && key.0 == new_scope {
return Err("Defined name already exists".to_string());
}
}
}
let defined_names = &self.workbook.defined_names;
let sheet_id = match scope {
Some(index) => Some(self.workbook.worksheet(index)?.sheet_id),
None => None,
};
let new_sheet_id = match new_scope {
Some(index) => Some(self.workbook.worksheet(index)?.sheet_id),
None => None,
};
let mut index = None;
for (i, df) in defined_names.iter().enumerate() {
if df.name.to_uppercase() == name_upper && df.sheet_id == sheet_id {
index = Some(i);
}
}
if let Some(i) = index {
if let Some(df) = self.workbook.defined_names.get_mut(i) {
if new_name != df.name {
// We need to rename the name in every formula:
// Parse all formulas with the old name
// All internal formulas are R1C1
self.parser.set_lexer_mode(LexerMode::R1C1);
let worksheets = &mut self.workbook.worksheets;
for worksheet in worksheets {
let cell_reference = CellReferenceRC {
sheet: worksheet.get_name(),
row: 1,
column: 1,
};
let mut formulas = Vec::new();
for formula in &worksheet.shared_formulas {
let mut t = self.parser.parse(formula, &cell_reference);
rename_defined_name_in_node(&mut t, name, scope, new_name);
formulas.push(to_rc_format(&t));
}
worksheet.shared_formulas = formulas;
}
// Se the mode back to A1
self.parser.set_lexer_mode(LexerMode::A1);
}
df.name = new_name.to_string();
df.sheet_id = new_sheet_id;
df.formula = new_formula.to_string();
self.reset_parsed_structures();
}
Ok(())
} else {
Err("Defined name not found".to_string())
}
Err("Invalid merge_cell_ref, Merged cells to be deleted is not found".to_string())
}
}

View File

@@ -4,7 +4,7 @@ use std::collections::HashMap;
use crate::{
calc_result::Range,
constants::{DEFAULT_WINDOW_HEIGHT, DEFAULT_WINDOW_WIDTH},
constants::{DEFAULT_WINDOW_HEIGH, DEFAULT_WINDOW_WIDTH},
expressions::{
lexer::LexerMode,
parser::{
@@ -57,7 +57,7 @@ impl Model {
rows: vec![],
comments: vec![],
dimension: "A1".to_string(),
merge_cells: vec![],
merged_cells_list: vec![],
name: name.to_string(),
shared_formulas: vec![],
sheet_data: Default::default(),
@@ -85,14 +85,14 @@ impl Model {
let worksheets = &self.workbook.worksheets;
for worksheet in worksheets {
let shared_formulas = &worksheet.shared_formulas;
let cell_reference = CellReferenceRC {
let cell_reference = &Some(CellReferenceRC {
sheet: worksheet.get_name(),
row: 1,
column: 1,
};
});
let mut parse_formula = Vec::new();
for formula in shared_formulas {
let t = self.parser.parse(formula, &cell_reference);
let t = self.parser.parse(formula, cell_reference);
parse_formula.push(t);
}
self.parsed_formulas.push(parse_formula);
@@ -144,14 +144,8 @@ impl Model {
/// Reparses all formulas and defined names
pub(crate) fn reset_parsed_structures(&mut self) {
let defined_names = self
.workbook
.get_defined_names_with_scope()
.iter()
.map(|s| (s.0.to_owned(), s.1))
.collect();
self.parser
.set_worksheets_and_names(self.workbook.get_worksheet_names(), defined_names);
.set_worksheets(self.workbook.get_worksheet_names());
self.parsed_formulas = vec![];
self.parse_formulas();
self.parsed_defined_names = HashMap::new();
@@ -268,11 +262,11 @@ impl Model {
// We use iter because the default would be a mut_iter and we don't need a mutable reference
let worksheets = &mut self.workbook.worksheets;
for worksheet in worksheets {
let cell_reference = &CellReferenceRC {
let cell_reference = &Some(CellReferenceRC {
sheet: worksheet.get_name(),
row: 1,
column: 1,
};
});
let mut formulas = Vec::new();
for formula in &worksheet.shared_formulas {
let mut t = self.parser.parse(formula, cell_reference);
@@ -365,7 +359,7 @@ impl Model {
WorkbookView {
sheet: 0,
window_width: DEFAULT_WINDOW_WIDTH,
window_height: DEFAULT_WINDOW_HEIGHT,
window_height: DEFAULT_WINDOW_HEIGH,
},
);
@@ -394,7 +388,7 @@ impl Model {
let parsed_formulas = Vec::new();
let worksheets = &workbook.worksheets;
let worksheet_names = worksheets.iter().map(|s| s.get_name()).collect();
let parser = Parser::new(worksheet_names, vec![], HashMap::new());
let parser = Parser::new(worksheet_names, HashMap::new());
let cells = HashMap::new();
// FIXME: Add support for display languages

View File

@@ -223,6 +223,14 @@ impl Model {
column: i32,
style: &Style,
) -> Result<(), String> {
// Checking first whether cell we are updating is part of Merged cells
// if so returning with Err
if self.is_part_of_merged_cells(sheet, row, column)? {
return Err(format!(
"Cell row : {}, col : {} is part of merged cells block, so singular update to the cell is not possible",
row, column
));
}
let style_index = self.workbook.styles.get_style_index_or_create(style);
self.workbook
.worksheet_mut(sheet)?
@@ -252,6 +260,14 @@ impl Model {
column: i32,
style_name: &str,
) -> Result<(), String> {
// Checking first whether cell we are updating is part of Merged cells
// if so returning with Err
if self.is_part_of_merged_cells(sheet, row, column)? {
return Err(format!(
"Cell row : {}, col : {} is part of merged cells block, so singular update to the cell is not possible",
row, column
));
}
let style_index = self.workbook.styles.get_style_index_by_name(style_name)?;
self.workbook
.worksheet_mut(sheet)?

View File

@@ -19,7 +19,6 @@ mod test_fn_formulatext;
mod test_fn_if;
mod test_fn_maxifs;
mod test_fn_minifs;
mod test_fn_or_xor;
mod test_fn_product;
mod test_fn_rept;
mod test_fn_sum;
@@ -51,12 +50,10 @@ mod test_number_format;
mod test_escape_quotes;
mod test_extend;
mod test_fn_fv;
mod test_fn_type;
mod test_frozen_rows_and_columns;
mod test_geomean;
mod test_get_cell_content;
mod test_issue_155;
mod test_model_merge_cell_fns;
mod test_percentage;
mod test_set_functions_error_handling;
mod test_today;

View File

@@ -82,21 +82,3 @@ fn test_column_width_higher_edge() {
assert!((worksheet.get_column_width(17).unwrap() - DEFAULT_COLUMN_WIDTH).abs() < f64::EPSILON);
assert_eq!(model.get_cell_style_index(0, 23, 16), Ok(1));
}
#[test]
fn test_column_width_negative() {
let mut model = new_empty_model();
let result = model
.workbook
.worksheet_mut(0)
.unwrap()
.set_column_width(16, -1.0);
assert_eq!(result, Err("Can not set a negative width: -1".to_string()));
assert_eq!(model.workbook.worksheets[0].cols.len(), 0);
let worksheet = model.workbook.worksheet(0).unwrap();
assert_eq!(
(worksheet.get_column_width(16).unwrap()),
DEFAULT_COLUMN_WIDTH
);
assert_eq!(model.get_cell_style_index(0, 23, 16), Ok(0));
}

View File

@@ -2,6 +2,9 @@
use crate::test::util::new_empty_model;
#[test]
fn simple_cases() {}
#[test]
fn wrong_number_of_arguments() {
let mut model = new_empty_model();

View File

@@ -1,36 +0,0 @@
#![allow(clippy::unwrap_used)]
use crate::test::util::new_empty_model;
#[test]
fn computation() {
let i2 = "=-C2*(1+D2)^E2-F2*((D2+1)*((1+D2)^E2-1))/D2";
let mut model = new_empty_model();
model._set("C2", "1");
model._set("D2", "2");
model._set("E2", "3");
model._set("F2", "4");
model._set("I2", i2);
model.evaluate();
assert_eq!(model._get_text("I2"), "-183");
assert_eq!(model._get_formula("I2"), i2);
}
#[test]
fn format_as_currency() {
let mut model = new_empty_model();
model._set("C2", "1");
model._set("D2", "2");
model._set("E2", "3");
model._set("F2", "4");
model._set("I2", "=FV(D2,E2,F2,C2,1)");
model.evaluate();
assert_eq!(model._get_text("I2"), "-$183.00");
}

View File

@@ -1,204 +0,0 @@
#![allow(clippy::unwrap_used)]
#![allow(clippy::print_stdout)]
use crate::test::util::new_empty_model;
// These tests are grouped because in many cases XOR and OR have similar behaviour.
// Test specific to xor
#[test]
fn fn_xor() {
let mut model = new_empty_model();
model._set("A1", "=XOR(1, 1, 1, 0, 0)");
model._set("A2", "=XOR(1, 1, 0, 0, 0)");
model._set("A3", "=XOR(TRUE, TRUE, TRUE, FALSE, FALSE)");
model._set("A4", "=XOR(TRUE, TRUE, FALSE, FALSE, FALSE)");
model._set("A5", "=XOR(FALSE, FALSE, FALSE, FALSE, FALSE)");
model._set("A6", "=XOR(TRUE, TRUE)");
model._set("A7", "=XOR(0,0,0)");
model._set("A8", "=XOR(0,0,1)");
model._set("A9", "=XOR(0,1,0)");
model._set("A10", "=XOR(0,1,1)");
model._set("A11", "=XOR(1,0,0)");
model._set("A12", "=XOR(1,0,1)");
model._set("A13", "=XOR(1,1,0)");
model._set("A14", "=XOR(1,1,1)");
model.evaluate();
assert_eq!(model._get_text("A1"), *"TRUE");
assert_eq!(model._get_text("A2"), *"FALSE");
assert_eq!(model._get_text("A3"), *"TRUE");
assert_eq!(model._get_text("A4"), *"FALSE");
assert_eq!(model._get_text("A5"), *"FALSE");
assert_eq!(model._get_text("A6"), *"FALSE");
assert_eq!(model._get_text("A7"), *"FALSE");
assert_eq!(model._get_text("A8"), *"TRUE");
assert_eq!(model._get_text("A9"), *"TRUE");
assert_eq!(model._get_text("A10"), *"FALSE");
assert_eq!(model._get_text("A11"), *"TRUE");
assert_eq!(model._get_text("A12"), *"FALSE");
assert_eq!(model._get_text("A13"), *"FALSE");
assert_eq!(model._get_text("A14"), *"TRUE");
}
#[test]
fn fn_or() {
let mut model = new_empty_model();
model._set("A1", "=OR(1, 1, 1, 0, 0)");
model._set("A2", "=OR(1, 1, 0, 0, 0)");
model._set("A3", "=OR(TRUE, TRUE, TRUE, FALSE, FALSE)");
model._set("A4", "=OR(TRUE, TRUE, FALSE, FALSE, FALSE)");
model._set("A5", "=OR(FALSE, FALSE, FALSE, FALSE, FALSE)");
model._set("A6", "=OR(TRUE, TRUE)");
model.evaluate();
assert_eq!(model._get_text("A1"), *"TRUE");
assert_eq!(model._get_text("A2"), *"TRUE");
assert_eq!(model._get_text("A3"), *"TRUE");
assert_eq!(model._get_text("A4"), *"TRUE");
assert_eq!(model._get_text("A5"), *"FALSE");
assert_eq!(model._get_text("A6"), *"TRUE");
}
#[test]
fn fn_or_xor() {
inner("or");
inner("xor");
fn inner(func: &str) {
println!("Testing function: {func}");
let mut model = new_empty_model();
// Text args
model._set("A1", &format!(r#"={func}("")"#));
model._set("A2", &format!(r#"={func}("", "")"#));
model._set("A3", &format!(r#"={func}("", TRUE)"#));
model._set("A4", &format!(r#"={func}("", FALSE)"#));
model._set("A5", &format!("={func}(FALSE, TRUE)"));
model._set("A6", &format!("={func}(FALSE, FALSE)"));
model._set("A7", &format!("={func}(TRUE, FALSE)"));
// Reference to empty cell, plus true argument
model._set("A8", &format!("={func}(Z99, 1)"));
// Reference to empty cell/range
model._set("A9", &format!("={func}(Z99)"));
model._set("A10", &format!("={func}(X99:Z99"));
// Reference to cell with reference to empty range
model._set("B11", "=X99:Z99");
model._set("A11", &format!("={func}(B11)"));
// Reference to cell with non-empty range
model._set("X12", "1");
model._set("B12", "=X12:Z12");
model._set("A12", &format!("={func}(B12)"));
// Reference to text cell
model._set("B13", "some_text");
model._set("A13", &format!("={func}(B13)"));
model._set("A14", &format!("={func}(B13, 0)"));
model._set("A15", &format!("={func}(B13, 1)"));
// Reference to Implicit intersection
model._set("X16", "1");
model._set("B16", "=@X15:X16");
model._set("A16", &format!("={func}(B16)"));
// Non-empty range
model._set("B17", "1");
model._set("A17", &format!("={func}(B17:C17)"));
// Non-empty range with text
model._set("B18", "text");
model._set("A18", &format!("={func}(B18:C18)"));
// Non-empty range with text and number
model._set("B19", "text");
model._set("C19", "1");
model._set("A19", &format!("={func}(B19:C19)"));
// range with error
model._set("B20", "=1/0");
model._set("A20", &format!("={func}(B20:C20)"));
model.evaluate();
assert_eq!(model._get_text("A1"), *"#VALUE!");
assert_eq!(model._get_text("A2"), *"#VALUE!");
assert_eq!(model._get_text("A3"), *"TRUE");
assert_eq!(model._get_text("A4"), *"FALSE");
assert_eq!(model._get_text("A5"), *"TRUE");
assert_eq!(model._get_text("A6"), *"FALSE");
assert_eq!(model._get_text("A7"), *"TRUE");
assert_eq!(model._get_text("A8"), *"TRUE");
assert_eq!(model._get_text("A9"), *"#VALUE!");
assert_eq!(model._get_text("A10"), *"#VALUE!");
assert_eq!(model._get_text("A11"), *"#VALUE!");
// TODO: This one depends on spill behaviour which isn't implemented yet
// assert_eq!(model._get_text("A12"), *"TRUE");
assert_eq!(model._get_text("A13"), *"#VALUE!");
assert_eq!(model._get_text("A14"), *"FALSE");
assert_eq!(model._get_text("A15"), *"TRUE");
// TODO: This one depends on @ implicit intersection behaviour which isn't implemented yet
// assert_eq!(model._get_text("A16"), *"TRUE");
assert_eq!(model._get_text("A17"), *"TRUE");
assert_eq!(model._get_text("A18"), *"#VALUE!");
assert_eq!(model._get_text("A19"), *"TRUE");
assert_eq!(model._get_text("A20"), *"#DIV/0!");
}
}
#[test]
fn fn_or_xor_no_arguments() {
inner("or");
inner("xor");
fn inner(func: &str) {
println!("Testing function: {func}");
let mut model = new_empty_model();
model._set("A1", &format!("={}()", func));
model.evaluate();
assert_eq!(model._get_text("A1"), *"#ERROR!");
}
}
#[test]
fn fn_or_xor_missing_arguments() {
inner("or");
inner("xor");
fn inner(func: &str) {
println!("Testing function: {func}");
let mut model = new_empty_model();
model._set("A1", &format!("={func}(,)"));
model._set("A2", &format!("={func}(,1)"));
model._set("A3", &format!("={func}(1,)"));
model._set("A4", &format!("={func}(,B1)"));
model._set("A5", &format!("={func}(,B1:B4)"));
model.evaluate();
assert_eq!(model._get_text("A1"), *"FALSE");
assert_eq!(model._get_text("A2"), *"TRUE");
assert_eq!(model._get_text("A3"), *"TRUE");
assert_eq!(model._get_text("A4"), *"FALSE");
assert_eq!(model._get_text("A5"), *"FALSE");
}
}

View File

@@ -1,7 +1,5 @@
#![allow(clippy::unwrap_used)]
use crate::constants::DEFAULT_ROW_HEIGHT;
use crate::cell::CellValue;
use crate::number_format::to_excel_precision_str;
@@ -115,15 +113,6 @@ fn test_set_row_height() {
worksheet.set_row_height(5, 5.0).unwrap();
let worksheet = model.workbook.worksheet(0).unwrap();
assert!((5.0 - worksheet.row_height(5).unwrap()).abs() < f64::EPSILON);
let worksheet = model.workbook.worksheet_mut(0).unwrap();
let result = worksheet.set_row_height(6, -1.0);
assert_eq!(result, Err("Can not set a negative height: -1".to_string()));
assert_eq!(worksheet.row_height(6).unwrap(), DEFAULT_ROW_HEIGHT);
worksheet.set_row_height(6, 0.0).unwrap();
assert_eq!(worksheet.row_height(6).unwrap(), 0.0);
}
#[test]

View File

@@ -1,27 +0,0 @@
#![allow(clippy::unwrap_used)]
use crate::test::util::new_empty_model;
#[test]
fn test_fn_geomean_arguments() {
let mut model = new_empty_model();
model._set("A1", "=GEOMEAN()");
model.evaluate();
assert_eq!(model._get_text("A1"), *"#ERROR!");
}
#[test]
fn test_fn_geomean_minimal() {
let mut model = new_empty_model();
model._set("B1", "1");
model._set("B2", "2");
model._set("B3", "3");
model._set("B4", "'2");
// B5 is empty
model._set("B6", "true");
model._set("A1", "=GEOMEAN(B1:B6)");
model.evaluate();
assert_eq!(model._get_text("A1"), *"1.817120593");
}

View File

@@ -1,14 +0,0 @@
#![allow(clippy::unwrap_used)]
use crate::test::util::new_empty_model;
#[test]
fn issue_155() {
let mut model = new_empty_model();
model._set("A1", "1");
model._set("A2", "2");
model._set("B2", "=A$1:A2");
model.evaluate();
assert_eq!(model._get_formula("B2"), "=A$1:A2".to_string());
}

View File

@@ -0,0 +1,155 @@
#![allow(clippy::unwrap_used)]
use crate::{test::util::new_empty_model, types::CellType};
#[test]
fn test_model_set_fns_related_to_merge_cells() {
let mut model = new_empty_model();
// creating a merge cell of D1:F2
model.merge_cells(0, "D1:F2").unwrap();
// Updating the mother cell of Merge cells and expecting the update to go through
model.set_user_input(0, 1, 4, "Hello".to_string()).unwrap();
assert_eq!(model.get_cell_content(0, 1, 4).unwrap(), "Hello");
assert_eq!(model.get_cell_type(0, 1, 4).unwrap(), CellType::Text);
// Updating cell which is not in Merge cell block
assert_eq!(model.set_user_input(0, 1, 3, "Hello".to_string()), Ok(()));
assert_eq!(model.get_cell_content(0, 1, 3), Ok("Hello".to_string()));
assert_eq!(model.get_cell_type(0, 1, 3), Ok(CellType::Text));
// 1: testing with set_user_input()
assert_eq!(
model
.set_user_input(0, 1, 5, "Hello".to_string()),
Err("Cell row : 1, col : 5 is part of merged cells block, so singular update to the cell is not possible".to_string())
);
assert_eq!(model.get_cell_content(0, 1, 5), Ok("".to_string()));
assert_eq!(model.get_cell_type(0, 1, 5), Ok(CellType::Number));
// 2: testing with update_cell_with_bool()
assert_eq!(
model
.update_cell_with_bool(0, 1, 5, true),
Err("Cell row : 1, col : 5 is part of merged cells block, so singular update to the cell is not possible".to_string())
);
assert_eq!(model.get_cell_content(0, 1, 5), Ok("".to_string()));
assert_eq!(model.get_cell_type(0, 1, 5), Ok(CellType::Number));
// 3: testing with update_cell_with_formula()
assert_eq!(
model
.update_cell_with_formula(0, 1, 5, "=SUM(A1+A2)".to_string()),
Err("Cell row : 1, col : 5 is part of merged cells block, so singular update to the cell is not possible".to_string())
);
assert_eq!(model.get_cell_type(0, 1, 5), Ok(CellType::Number));
// 4: testing with update_cell_with_number()
assert_eq!(
model
.update_cell_with_number(0, 1, 5, 10.0),
Err("Cell row : 1, col : 5 is part of merged cells block, so singular update to the cell is not possible".to_string())
);
assert_eq!(model.get_cell_content(0, 1, 5), Ok("".to_string()));
assert_eq!(model.get_cell_type(0, 1, 5), Ok(CellType::Number));
// 5: testing with update_cell_with_text()
assert_eq!(
model
.update_cell_with_text(0, 1, 5, "new text"),
Err("Cell row : 1, col : 5 is part of merged cells block, so singular update to the cell is not possible".to_string())
);
assert_eq!(model.get_cell_content(0, 1, 5), Ok("".to_string()));
assert_eq!(model.get_cell_type(0, 1, 5), Ok(CellType::Number));
}
#[test]
fn test_model_merge_cells_crud_api() {
let mut model = new_empty_model();
// creating a merge cell of D4:F6
model.merge_cells(0, "D4:F6").unwrap();
model
.set_user_input(0, 4, 4, "Merge Block".to_string())
.unwrap();
// CRUD APIS testing on Merge Cells
// Case1: Creating a new merge cell without overlapping
// Newly created Merge block is left to D4:F6
assert_eq!(model.merge_cells(0, "A1:B4"), Ok(()));
assert_eq!(
model.workbook.worksheet(0).unwrap().merged_cells_list.len(),
2
);
model.set_user_input(0, 1, 1, "left".to_string()).unwrap();
// Newly created Merge block is right to D4:F6
assert_eq!(model.merge_cells(0, "G1:H7"), Ok(()));
assert_eq!(
model.workbook.worksheet(0).unwrap().merged_cells_list.len(),
3
);
model.set_user_input(0, 1, 7, "right".to_string()).unwrap();
// Newly created Merge block is above to D4:F6
assert_eq!(model.merge_cells(0, "C1:D3"), Ok(()));
assert_eq!(
model.workbook.worksheet(0).unwrap().merged_cells_list.len(),
4
);
model.set_user_input(0, 1, 3, "top".to_string()).unwrap();
// Newly created Merge block is down to D4:F6
assert_eq!(model.merge_cells(0, "D8:E9"), Ok(()));
assert_eq!(
model.workbook.worksheet(0).unwrap().merged_cells_list.len(),
5
);
model.set_user_input(0, 8, 4, "down".to_string()).unwrap();
// Case2: Creating a new merge cell with overlapping with other 3 merged cell
assert_eq!(model.merge_cells(0, "C1:G4"), Ok(()));
assert_eq!(
model.workbook.worksheet(0).unwrap().merged_cells_list.len(),
3
);
model
.set_user_input(0, 1, 3, "overlapped_new_merge_block".to_string())
.unwrap();
// Case3: Giving wrong parsing range
assert_eq!(
model.merge_cells(0, "C3:A1"),
Err("Invalid parse range. Merge Mother cell always be top left cell".to_string())
);
assert_eq!(
model.merge_cells(0, "CA:A1"),
Err("Invalid range: 'CA:A1'".to_string())
);
assert_eq!(
model.merge_cells(0, "C0:A1"),
Err("Invalid range: 'C0:A1'".to_string())
);
assert_eq!(
model.merge_cells(0, "C1:A0"),
Err("Invalid range: 'C1:A0'".to_string())
);
assert_eq!(
model.merge_cells(0, "C1"),
Err("Invalid range: 'C1'".to_string())
);
assert_eq!(
model.merge_cells(0, "C1:A1:B1"),
Err("Invalid range: 'C1:A1:B1'".to_string())
);
// Case3: Giving wrong merge_ref, which would resulting in error (Merge cell to be deleted is not found)
assert_eq!(
model.unmerge_cells(0, "C1:E1"),
Err("Invalid merge_cell_ref, Merged cells to be deleted is not found".to_string())
);
// Case4: unmerge scenario
assert_eq!(model.unmerge_cells(0, "C1:G4"), Ok(()));
}

View File

@@ -62,3 +62,45 @@ fn test_create_named_style() {
let style = model.get_style_for_cell(0, 1, 1).unwrap();
assert!(style.font.b);
}
#[test]
fn test_model_style_set_fns_in_merge_cell_context() {
let mut model = new_empty_model();
// creating a merge cell of D1:F2
model.merge_cells(0, "D1:F2").unwrap();
model.set_user_input(0, 1, 4, "Hello".to_string()).unwrap();
let mut style = model.get_style_for_cell(0, 1, 1).unwrap();
assert!(!style.font.b);
style.font.b = true;
// Updating the mother cell of Merge cells and expecting the update to go through
// This should make the text "Hello" in bold format
assert_eq!(model.set_cell_style(0, 1, 4, &style), Ok(()));
// 1: testing with set_cell_style()
let original_style: Style = model.get_style_for_cell(0, 1, 5).unwrap();
assert_eq!(
model
.set_cell_style(0, 1, 5, &style),
Err("Cell row : 1, col : 5 is part of merged cells block, so singular update to the cell is not possible".to_string())
);
assert_eq!(model.get_style_for_cell(0, 1, 5), Ok(original_style));
// 2: testing with set_cell_style_by_name
let mut style = model.get_style_for_cell(0, 1, 4).unwrap();
style.font.b = true;
assert_eq!(
model.workbook.styles.create_named_style("bold", &style),
Ok(())
);
let original_style: Style = model.get_style_for_cell(0, 1, 5).unwrap();
assert_eq!(
model
.set_cell_style_by_name(0, 1, 5, "bold"),
Err("Cell row : 1, col : 5 is part of merged cells block, so singular update to the cell is not possible".to_string())
);
assert_eq!(model.get_style_for_cell(0, 1, 5), Ok(original_style));
}

View File

@@ -283,3 +283,87 @@ fn test_worksheet_navigate_to_edge_in_direction() {
assert_eq!(navigate(8, 3, NavigationDirection::Up), (6, 3));
assert_eq!(navigate(9, 3, NavigationDirection::Up), (6, 3));
}
// Tests Merge cells related functions of worksheet
#[test]
fn test_merge_cell_fns_worksheet() {
let mut model = new_empty_model();
// Adding one Merge cell
model.merge_cells(0, "D1:E3").unwrap();
// Lets check whether D1 (Mother Merge cell) is part of Merge block or not
// It should not be considered as part of Merge cell
assert!(!model
.workbook
.worksheet(0)
.unwrap()
.is_part_of_merged_cells(1, 4)
.unwrap(),);
// Lets give cell which is actually part of Merge block and expect true from fn
assert!(model
.workbook
.worksheet(0)
.unwrap()
.is_part_of_merged_cells(2, 4)
.unwrap());
// Lets give cell which is not a part of Merge block and expect false from fn
assert!(!model
.workbook
.worksheet(0)
.unwrap()
.is_part_of_merged_cells(2, 6)
.unwrap());
// Lets give an Invalid row
assert_eq!(
model
.workbook
.worksheet(0)
.unwrap()
.is_part_of_merged_cells(0, 1),
Err("Incorrect row or column".to_string())
);
//Lets give Invalid column
assert_eq!(
model
.workbook
.worksheet(0)
.unwrap()
.is_part_of_merged_cells(1, 0),
Err("Incorrect row or column".to_string())
);
// Verifying get fns of worksheet
assert_eq!(
model
.workbook
.worksheet(0)
.unwrap()
.get_merged_cells_list()
.len(),
1
);
{
let merge_cell_vec = model
.workbook
.worksheet_mut(0)
.unwrap()
.get_merged_cells_list_mut();
merge_cell_vec.remove(0);
assert_eq!(
model
.workbook
.worksheet(0)
.unwrap()
.get_merged_cells_list()
.len(),
0
);
}
}

View File

@@ -3,7 +3,6 @@ mod test_autofill_columns;
mod test_autofill_rows;
mod test_border;
mod test_clear_cells;
mod test_defined_names;
mod test_diff_queue;
mod test_evaluation;
mod test_general;
@@ -15,7 +14,6 @@ mod test_on_paste_styles;
mod test_paste_csv;
mod test_rename_sheet;
mod test_row_column;
mod test_sheet_state;
mod test_styles;
mod test_to_from_bytes;
mod test_undo_redo;

View File

@@ -1,398 +0,0 @@
#![allow(clippy::unwrap_used)]
use crate::UserModel;
#[test]
fn create_defined_name() {
let mut model = UserModel::new_empty("model", "en", "UTC").unwrap();
model.set_user_input(0, 1, 1, "42").unwrap();
model
.new_defined_name("myName", None, "Sheet1!$A$1")
.unwrap();
model.set_user_input(0, 5, 7, "=myName").unwrap();
assert_eq!(
model.get_formatted_cell_value(0, 5, 7),
Ok("42".to_string())
);
assert_eq!(
model.get_defined_name_list(),
vec![("myName".to_string(), None, "Sheet1!$A$1".to_string())]
);
// delete it
model.delete_defined_name("myName", None).unwrap();
assert_eq!(
model.get_formatted_cell_value(0, 5, 7),
Ok("#NAME?".to_string())
);
assert_eq!(model.get_defined_name_list().len(), 0);
model.undo().unwrap();
assert_eq!(
model.get_formatted_cell_value(0, 5, 7),
Ok("42".to_string())
);
}
#[test]
fn scopes() {
let mut model = UserModel::new_empty("model", "en", "UTC").unwrap();
model.set_user_input(0, 1, 1, "42").unwrap();
// Global
model
.new_defined_name("myName", None, "Sheet1!$A$1")
.unwrap();
model.set_user_input(0, 5, 7, "=myName").unwrap();
// Local to Sheet2
model.new_sheet().unwrap();
model.set_user_input(1, 2, 1, "145").unwrap();
model
.new_defined_name("myName", Some(1), "Sheet2!$A$2")
.unwrap();
model.set_user_input(1, 8, 8, "=myName").unwrap();
// Sheet 3
model.new_sheet().unwrap();
model.set_user_input(2, 2, 2, "=myName").unwrap();
// Global
assert_eq!(
model.get_formatted_cell_value(0, 5, 7),
Ok("42".to_string())
);
assert_eq!(
model.get_formatted_cell_value(1, 8, 8),
Ok("145".to_string())
);
assert_eq!(
model.get_formatted_cell_value(2, 2, 2),
Ok("42".to_string())
);
}
#[test]
fn delete_sheet() {
let mut model = UserModel::new_empty("model", "en", "UTC").unwrap();
model.set_user_input(0, 1, 1, "Hello").unwrap();
model
.set_user_input(0, 2, 1, r#"=CONCATENATE(MyName, " world!")"#)
.unwrap();
model.new_sheet().unwrap();
model
.new_defined_name("myName", Some(1), "Sheet1!$A$1")
.unwrap();
model
.set_user_input(1, 2, 1, r#"=CONCATENATE(MyName, " my world!")"#)
.unwrap();
assert_eq!(
model.get_formatted_cell_value(0, 2, 1),
Ok("#NAME?".to_string())
);
assert_eq!(
model.get_formatted_cell_value(1, 2, 1),
Ok("Hello my world!".to_string())
);
model.delete_sheet(0).unwrap();
assert_eq!(
model.get_formatted_cell_value(0, 2, 1),
Ok("#NAME?".to_string())
);
assert_eq!(
model.get_cell_content(0, 2, 1),
Ok(r#"=CONCATENATE(MyName," my world!")"#.to_string())
);
}
#[test]
fn change_scope() {
let mut model = UserModel::new_empty("model", "en", "UTC").unwrap();
model.set_user_input(0, 1, 1, "Hello").unwrap();
model
.set_user_input(0, 2, 1, r#"=CONCATENATE(MyName, " world!")"#)
.unwrap();
model.new_sheet().unwrap();
model
.new_defined_name("myName", Some(1), "Sheet1!$A$1")
.unwrap();
assert_eq!(
model.get_formatted_cell_value(0, 2, 1),
Ok("#NAME?".to_string())
);
model
.update_defined_name("myName", Some(1), "myName", None, "Sheet1!$A$1")
.unwrap();
assert_eq!(
model.get_formatted_cell_value(0, 2, 1),
Ok("Hello world!".to_string())
);
}
#[test]
fn rename_defined_name() {
let mut model = UserModel::new_empty("model", "en", "UTC").unwrap();
model.set_user_input(0, 1, 1, "Hello").unwrap();
model
.set_user_input(0, 2, 1, r#"=CONCATENATE(MyName, " world!")"#)
.unwrap();
model.new_sheet().unwrap();
model
.new_defined_name("myName", None, "Sheet1!$A$1")
.unwrap();
assert_eq!(
model.get_formatted_cell_value(0, 2, 1),
Ok("Hello world!".to_string())
);
model
.update_defined_name("myName", None, "newName", None, "Sheet1!$A$1")
.unwrap();
assert_eq!(
model.get_formatted_cell_value(0, 2, 1),
Ok("Hello world!".to_string())
);
assert_eq!(
model.get_cell_content(0, 2, 1),
Ok(r#"=CONCATENATE(newName," world!")"#.to_string())
);
}
#[test]
fn rename_defined_name_operations() {
let mut model = UserModel::new_empty("model", "en", "UTC").unwrap();
model.set_user_input(0, 1, 1, "42").unwrap();
model.set_user_input(0, 1, 2, "123").unwrap();
model
.new_defined_name("answer", None, "Sheet1!$A$1")
.unwrap();
model
.set_user_input(0, 2, 1, "=IF(answer<2, answer*2, answer^2)")
.unwrap();
model
.set_user_input(0, 3, 1, "=badDunction(-answer)")
.unwrap();
model.new_sheet().unwrap();
model.set_user_input(1, 1, 1, "78").unwrap();
model
.new_defined_name("answer", Some(1), "Sheet1!$A$1")
.unwrap();
model.set_user_input(1, 3, 1, "=answer").unwrap();
model
.update_defined_name("answer", None, "respuesta", None, "Sheet1!$A$1")
.unwrap();
assert_eq!(
model.get_cell_content(0, 2, 1),
Ok("=IF(respuesta<2,respuesta*2,respuesta^2)".to_string())
);
assert_eq!(
model.get_cell_content(0, 3, 1),
Ok("=badDunction(-respuesta)".to_string())
);
// A defined name with the same name but different scope
assert_eq!(model.get_cell_content(1, 3, 1), Ok("=answer".to_string()));
}
#[test]
fn rename_defined_name_string_operations() {
let mut model = UserModel::new_empty("model", "en", "UTC").unwrap();
model.set_user_input(0, 1, 1, "Hello").unwrap();
model.set_user_input(0, 1, 2, "World").unwrap();
model
.new_defined_name("hello", None, "Sheet1!$A$1")
.unwrap();
model
.new_defined_name("world", None, "Sheet1!$B$1")
.unwrap();
model.set_user_input(0, 2, 1, "=hello&world").unwrap();
model
.update_defined_name("hello", None, "HolaS", None, "Sheet1!$A$1")
.unwrap();
assert_eq!(
model.get_cell_content(0, 2, 1),
Ok("=HolaS&world".to_string())
);
}
#[test]
fn invalid_names() {
let mut model = UserModel::new_empty("model", "en", "UTC").unwrap();
model.set_user_input(0, 1, 1, "Hello").unwrap();
model
.new_defined_name("MyName", None, "Sheet1!$A$1")
.unwrap();
// spaces
assert_eq!(
model.new_defined_name("A real", None, "Sheet1!$A$1"),
Err("Invalid defined name".to_string())
);
// Starts with number
assert_eq!(
model.new_defined_name("2real", None, "Sheet1!$A$1"),
Err("Invalid defined name".to_string())
);
// Updating also fails
assert_eq!(
model.update_defined_name("MyName", None, "My Name", None, "Sheet1!$A$1"),
Err("Invalid defined name".to_string())
);
}
#[test]
fn already_existing() {
let mut model = UserModel::new_empty("model", "en", "UTC").unwrap();
model
.new_defined_name("MyName", None, "Sheet1!$A$1")
.unwrap();
model
.new_defined_name("Another", None, "Sheet1!$A$1")
.unwrap();
// Can't create a new name with the same name
assert_eq!(
model.new_defined_name("MyName", None, "Sheet1!$A$2"),
Err("Defined name already exists".to_string())
);
// Can't update one into an existing
assert_eq!(
model.update_defined_name("Another", None, "MyName", None, "Sheet1!$A$1"),
Err("Defined name already exists".to_string())
);
}
#[test]
fn invalid_sheet() {
let mut model = UserModel::new_empty("model", "en", "UTC").unwrap();
model.set_user_input(0, 1, 1, "Hello").unwrap();
model
.new_defined_name("MyName", None, "Sheet1!$A$1")
.unwrap();
assert_eq!(
model.new_defined_name("Mything", Some(2), "Sheet1!$A$1"),
Err("Invalid sheet index".to_string())
);
assert_eq!(
model.update_defined_name("MyName", None, "MyName", Some(2), "Sheet1!$A$1"),
Err("Invalid sheet index".to_string())
);
assert_eq!(
model.update_defined_name("MyName", Some(9), "YourName", None, "Sheet1!$A$1"),
Err("Invalid sheet index".to_string())
);
}
#[test]
fn invalid_formula() {
let mut model = UserModel::new_empty("model", "en", "UTC").unwrap();
model.set_user_input(0, 1, 1, "Hello").unwrap();
model.new_defined_name("MyName", None, "A1").unwrap();
model.set_user_input(0, 1, 2, "=MyName").unwrap();
assert_eq!(
model.get_formatted_cell_value(0, 1, 2),
Ok("#NAME?".to_string())
);
}
#[test]
fn undo_redo() {
let mut model = UserModel::new_empty("model", "en", "UTC").unwrap();
model.set_user_input(0, 1, 1, "Hello").unwrap();
model.set_user_input(0, 2, 1, "Hola").unwrap();
model.set_user_input(0, 1, 2, r#"=MyName&"!""#).unwrap();
model
.new_defined_name("MyName", None, "Sheet1!$A$1")
.unwrap();
assert_eq!(
model.get_formatted_cell_value(0, 1, 2),
Ok("Hello!".to_string())
);
model.undo().unwrap();
assert_eq!(model.get_defined_name_list().len(), 0);
assert_eq!(
model.get_formatted_cell_value(0, 1, 2),
Ok("#NAME?".to_string())
);
model.redo().unwrap();
assert_eq!(model.get_defined_name_list().len(), 1);
assert_eq!(
model.get_formatted_cell_value(0, 1, 2),
Ok("Hello!".to_string())
);
model
.update_defined_name("MyName", None, "MyName", None, "Sheet1!$A$2")
.unwrap();
assert_eq!(model.get_defined_name_list().len(), 1);
assert_eq!(
model.get_formatted_cell_value(0, 1, 2),
Ok("Hola!".to_string())
);
model.undo().unwrap();
assert_eq!(model.get_defined_name_list().len(), 1);
assert_eq!(
model.get_formatted_cell_value(0, 1, 2),
Ok("Hello!".to_string())
);
model.redo().unwrap();
assert_eq!(model.get_defined_name_list().len(), 1);
assert_eq!(
model.get_formatted_cell_value(0, 1, 2),
Ok("Hola!".to_string())
);
let send_queue = model.flush_send_queue();
let mut model2 = UserModel::new_empty("model", "en", "UTC").unwrap();
model2.apply_external_diffs(&send_queue).unwrap();
assert_eq!(model2.get_defined_name_list().len(), 1);
assert_eq!(
model2.get_formatted_cell_value(0, 1, 2),
Ok("Hola!".to_string())
);
}

View File

@@ -91,6 +91,7 @@ fn insert_remove_columns() {
let mut model = UserModel::from_model(model);
// column E
let column_width = model.get_column_width(0, 5).unwrap();
println!("{column_width}");
// Insert some data in row 5 (and change the style) in E1
assert!(model.set_user_input(0, 1, 5, "100$").is_ok());

View File

@@ -2,7 +2,7 @@
use crate::{
constants::{
DEFAULT_COLUMN_WIDTH, DEFAULT_ROW_HEIGHT, DEFAULT_WINDOW_HEIGHT, DEFAULT_WINDOW_WIDTH,
DEFAULT_COLUMN_WIDTH, DEFAULT_ROW_HEIGHT, DEFAULT_WINDOW_HEIGH, DEFAULT_WINDOW_WIDTH,
LAST_COLUMN,
},
test::util::new_empty_model,
@@ -87,7 +87,7 @@ fn last_colum() {
fn page_down() {
let model = new_empty_model();
let mut model = UserModel::from_model(model);
let window_height = DEFAULT_WINDOW_HEIGHT as f64;
let window_height = DEFAULT_WINDOW_HEIGH as f64;
let row_height = DEFAULT_ROW_HEIGHT;
let row_count = f64::floor(window_height / row_height) as i32;
model.on_page_down().unwrap();

View File

@@ -99,7 +99,7 @@ fn cut_paste() {
// paste in cell D4 (4, 4)
model
.paste_from_clipboard(0, (1, 1, 2, 2), &copy.data, true)
.paste_from_clipboard((1, 1, 2, 2), &copy.data, true)
.unwrap();
assert_eq!(model.get_cell_content(0, 4, 4), Ok("42".to_string()));
@@ -119,26 +119,6 @@ fn cut_paste() {
assert_eq!(model.get_cell_content(0, 2, 2), Ok("".to_string()));
}
#[test]
fn cut_paste_different_sheet() {
let mut model = UserModel::new_empty("model", "en", "UTC").unwrap();
model.set_user_input(0, 1, 1, "42").unwrap();
model.set_selected_range(1, 1, 1, 1).unwrap();
let copy = model.copy_to_clipboard().unwrap();
model.new_sheet().unwrap();
model.set_selected_sheet(1).unwrap();
model.set_selected_cell(4, 4).unwrap();
// paste in cell D4 (4, 4) of Sheet2
model
.paste_from_clipboard(0, (1, 1, 1, 1), &copy.data, true)
.unwrap();
assert_eq!(model.get_cell_content(1, 4, 4), Ok("42".to_string()));
assert_eq!(model.get_cell_content(0, 1, 1), Ok("".to_string()));
}
#[test]
fn copy_paste_internal() {
let mut model = UserModel::new_empty("model", "en", "UTC").unwrap();
@@ -172,7 +152,7 @@ fn copy_paste_internal() {
// paste in cell D4 (4, 4)
model
.paste_from_clipboard(0, (1, 1, 2, 2), &copy.data, false)
.paste_from_clipboard((1, 1, 2, 2), &copy.data, false)
.unwrap();
assert_eq!(model.get_cell_content(0, 4, 4), Ok("42".to_string()));

View File

@@ -1,57 +0,0 @@
#![allow(clippy::unwrap_used)]
use crate::test::util::new_empty_model;
use crate::UserModel;
#[test]
fn basic_tests() {
let model = new_empty_model();
let mut model = UserModel::from_model(model);
// add three more sheets
model.new_sheet().unwrap();
model.new_sheet().unwrap();
model.new_sheet().unwrap();
let info = model.get_worksheets_properties();
assert_eq!(info.len(), 4);
for sheet in &info {
assert_eq!(sheet.state, "visible".to_string());
}
model.set_selected_sheet(2).unwrap();
assert_eq!(info.get(2).unwrap().name, "Sheet3".to_string());
model.hide_sheet(2).unwrap();
let info = model.get_worksheets_properties();
assert_eq!(model.get_selected_sheet(), 3);
assert_eq!(info.get(2).unwrap().state, "hidden".to_string());
model.undo().unwrap();
let info = model.get_worksheets_properties();
assert_eq!(info.get(2).unwrap().state, "visible".to_string());
model.redo().unwrap();
let info = model.get_worksheets_properties();
assert_eq!(info.get(2).unwrap().state, "hidden".to_string());
model.set_selected_sheet(3).unwrap();
model.hide_sheet(3).unwrap();
assert_eq!(model.get_selected_sheet(), 0);
model.unhide_sheet(2).unwrap();
model.unhide_sheet(3).unwrap();
let info = model.get_worksheets_properties();
assert_eq!(info.len(), 4);
for sheet in &info {
assert_eq!(sheet.state, "visible".to_string());
}
model.undo().unwrap();
let info = model.get_worksheets_properties();
assert_eq!(info.get(3).unwrap().state, "hidden".to_string());
model.redo().unwrap();
let info = model.get_worksheets_properties();
assert_eq!(info.get(3).unwrap().state, "visible".to_string());
}

View File

@@ -1,7 +1,7 @@
#![allow(clippy::unwrap_used)]
use crate::{
constants::{DEFAULT_ROW_HEIGHT, DEFAULT_WINDOW_HEIGHT, DEFAULT_WINDOW_WIDTH},
constants::{DEFAULT_ROW_HEIGHT, DEFAULT_WINDOW_HEIGH, DEFAULT_WINDOW_WIDTH},
test::util::new_empty_model,
UserModel,
};
@@ -11,7 +11,7 @@ fn basic_test() {
let model = new_empty_model();
let mut model = UserModel::from_model(model);
let window_height = model.get_window_height().unwrap();
assert_eq!(window_height, DEFAULT_WINDOW_HEIGHT);
assert_eq!(window_height, DEFAULT_WINDOW_HEIGH);
let window_width = model.get_window_width().unwrap();
assert_eq!(window_width, DEFAULT_WINDOW_WIDTH);

View File

@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
use std::{collections::HashMap, fmt::Display};
use crate::expressions::token::Error;
use crate::expressions::utils::number_to_column;
fn default_as_false() -> bool {
false
@@ -35,7 +36,7 @@ pub struct WorkbookView {
pub sheet: u32,
/// The current width of the window
pub window_width: i64,
/// The current height of the window
/// The current heigh of the window
pub window_height: i64,
}
@@ -110,7 +111,7 @@ pub struct Worksheet {
pub sheet_id: u32,
pub state: SheetState,
pub color: Option<String>,
pub merge_cells: Vec<String>,
pub merged_cells_list: Vec<MergedCells>,
pub comments: Vec<Comment>,
pub frozen_rows: i32,
pub frozen_columns: i32,
@@ -351,6 +352,43 @@ pub enum FontScheme {
None,
}
// MergedCells type
// There will be one MergedCells struct maintained for every Merged cells that we load
// merge_cell_range : Its tuple having [row_start, column_start, row_end, column_end]
#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone)]
pub struct MergedCells(pub i32, pub i32, pub i32, pub i32);
// implementing accessor function
impl MergedCells {
// Method which returns range_ref from the tuple
// ex : (3,1,4,2) is interpreted as A3:B4
pub fn get_merged_cells_str_ref(&self) -> Result<String, String> {
let start_column = number_to_column(self.1).ok_or(format!(
"Error while converting column start {} number to column string ref",
self.1
))?;
let end_column = number_to_column(self.3).ok_or(format!(
"Error while converting column end {} number to column string ref",
self.3
))?;
return Ok(start_column
+ &self.0.to_string()
+ &":".to_string()
+ &end_column
+ &self.2.to_string());
}
// Only Public function where Merge cell can be created
pub fn new(merge_cell_parsed_range: (i32, i32, i32, i32)) -> Self {
Self(
merge_cell_parsed_range.0,
merge_cell_parsed_range.1,
merge_cell_parsed_range.2,
merge_cell_parsed_range.3,
)
}
}
impl Display for FontScheme {
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {

View File

@@ -293,9 +293,7 @@ impl Model {
Node::EmptyArgKind => None,
Node::InvalidFunctionKind { .. } => None,
Node::ArrayKind(_) => None,
Node::DefinedNameKind(_) => None,
Node::TableNameKind(_) => None,
Node::WrongVariableKind(_) => None,
Node::VariableKind(_) => None,
Node::CompareKind { .. } => None,
Node::OpPowerKind { .. } => None,
}
@@ -311,7 +309,6 @@ impl Model {
Function::Sum => self.units_fn_sum_like(args, cell),
Function::Average => self.units_fn_sum_like(args, cell),
Function::Pmt => self.units_fn_currency(args, cell),
Function::Fv => self.units_fn_currency(args, cell),
Function::Nper => self.units_fn_currency(args, cell),
Function::Npv => self.units_fn_currency(args, cell),
Function::Irr => self.units_fn_percentage(args, cell),

View File

@@ -13,8 +13,8 @@ use crate::{
},
model::Model,
types::{
Alignment, BorderItem, CellType, Col, HorizontalAlignment, SheetProperties, SheetState,
Style, VerticalAlignment,
Alignment, BorderItem, CellType, Col, HorizontalAlignment, SheetProperties, Style,
VerticalAlignment,
},
utils::is_valid_hex_color,
};
@@ -39,7 +39,6 @@ pub struct ClipboardCell {
pub struct Clipboard {
pub(crate) csv: String,
pub(crate) data: ClipboardData,
pub(crate) sheet: u32,
pub(crate) range: (i32, i32, i32, i32),
}
@@ -343,7 +342,7 @@ impl UserModel {
old_value: Box::new(old_value),
}];
let line_count = value.split('\n').count();
let line_count = value.split("\n").count();
let row_height = self.model.get_row_height(sheet, row)?;
let cell_height = (line_count as f64) * DEFAULT_ROW_HEIGHT;
if cell_height > row_height {
@@ -440,48 +439,6 @@ impl UserModel {
Ok(())
}
/// Hides sheet by index
///
/// See also:
/// * [Model::set_sheet_state]
/// * [UserModel::unhide_sheet]
pub fn hide_sheet(&mut self, sheet: u32) -> Result<(), String> {
let sheet_count = self.model.workbook.worksheets.len() as u32;
for index in 1..sheet_count {
let sheet_index = (sheet + index) % sheet_count;
if self.model.workbook.worksheet(sheet_index)?.state == SheetState::Visible {
if let Some(view) = self.model.workbook.views.get_mut(&self.model.view_id) {
view.sheet = sheet_index;
};
break;
}
}
let old_value = self.model.workbook.worksheet(sheet)?.state.clone();
self.push_diff_list(vec![Diff::SetSheetState {
index: sheet,
new_value: SheetState::Hidden,
old_value,
}]);
self.model.set_sheet_state(sheet, SheetState::Hidden)?;
Ok(())
}
/// Un hides sheet by index
///
/// See also:
/// * [Model::set_sheet_state]
/// * [UserModel::hide_sheet]
pub fn unhide_sheet(&mut self, sheet: u32) -> Result<(), String> {
let old_value = self.model.workbook.worksheet(sheet)?.state.clone();
self.push_diff_list(vec![Diff::SetSheetState {
index: sheet,
new_value: SheetState::Visible,
old_value,
}]);
self.model.set_sheet_state(sheet, SheetState::Visible)?;
Ok(())
}
/// Sets sheet color
///
/// Note: an empty string will remove the color
@@ -756,7 +713,7 @@ impl UserModel {
/// Paste `styles` in the selected area
pub fn on_paste_styles(&mut self, styles: &[Vec<Style>]) -> Result<(), String> {
let styles_height = styles.len() as i32;
let styles_heigh = styles.len() as i32;
let styles_width = styles[0].len() as i32;
let sheet = if let Some(view) = self.model.workbook.views.get(&self.model.view_id) {
view.sheet
@@ -775,13 +732,13 @@ impl UserModel {
// If the pasted area is smaller than the selected area we increase it
let [row_start, column_start, row_end, column_end] = range;
let last_row = row_end.max(row_start + styles_height - 1);
let last_row = row_end.max(row_start + styles_heigh - 1);
let last_column = column_end.max(column_start + styles_width - 1);
let mut diff_list = Vec::new();
for row in row_start..=last_row {
for column in column_start..=last_column {
let row_index = ((row - row_start) % styles_height) as usize;
let row_index = ((row - row_start) % styles_heigh) as usize;
let column_index = ((column - column_start) % styles_width) as usize;
let style = &styles[row_index][column_index];
let old_value = self.model.get_style_for_cell(sheet, row, column)?;
@@ -1563,7 +1520,6 @@ impl UserModel {
Ok(Clipboard {
csv,
data,
sheet,
range: (row_start, column_start, row_end, column_end),
})
}
@@ -1571,7 +1527,6 @@ impl UserModel {
/// Paste text that we copied
pub fn paste_from_clipboard(
&mut self,
source_sheet: u32,
source_range: ClipboardTuple,
clipboard: &ClipboardData,
is_cut: bool,
@@ -1662,17 +1617,17 @@ impl UserModel {
let old_value = self
.model
.workbook
.worksheet(source_sheet)?
.worksheet(sheet)?
.cell(row, column)
.cloned();
diff_list.push(Diff::CellClearContents {
sheet: source_sheet,
sheet,
row,
column,
old_value: Box::new(old_value),
});
self.model.cell_clear_contents(source_sheet, row, column)?;
self.model.cell_clear_contents(sheet, row, column)?;
}
}
}
@@ -1734,68 +1689,6 @@ impl UserModel {
Ok(())
}
/// Returns the list of defined names
pub fn get_defined_name_list(&self) -> Vec<(String, Option<u32>, String)> {
self.model.workbook.get_defined_names_with_scope()
}
/// Delete an existing defined name
pub fn delete_defined_name(&mut self, name: &str, scope: Option<u32>) -> Result<(), String> {
let old_value = self.model.get_defined_name_formula(name, scope)?;
let diff_list = vec![Diff::DeleteDefinedName {
name: name.to_string(),
scope,
old_value,
}];
self.push_diff_list(diff_list);
self.model.delete_defined_name(name, scope)?;
self.evaluate_if_not_paused();
Ok(())
}
/// Create a new defined name
pub fn new_defined_name(
&mut self,
name: &str,
scope: Option<u32>,
formula: &str,
) -> Result<(), String> {
self.model.new_defined_name(name, scope, formula)?;
let diff_list = vec![Diff::CreateDefinedName {
name: name.to_string(),
scope,
value: formula.to_string(),
}];
self.push_diff_list(diff_list);
self.evaluate_if_not_paused();
Ok(())
}
/// Updates a defined name
pub fn update_defined_name(
&mut self,
name: &str,
scope: Option<u32>,
new_name: &str,
new_scope: Option<u32>,
new_formula: &str,
) -> Result<(), String> {
let old_formula = self.model.get_defined_name_formula(name, scope)?;
let diff_list = vec![Diff::UpdateDefinedName {
name: name.to_string(),
scope,
old_formula: old_formula.to_string(),
new_name: new_name.to_string(),
new_scope,
new_formula: new_formula.to_string(),
}];
self.push_diff_list(diff_list);
self.model
.update_defined_name(name, scope, new_name, new_scope, new_formula)?;
self.evaluate_if_not_paused();
Ok(())
}
// **** Private methods ****** //
fn push_diff_list(&mut self, diff_list: DiffList) {
@@ -1966,41 +1859,6 @@ impl UserModel {
} => {
self.model.set_show_grid_lines(*sheet, *old_value)?;
}
Diff::CreateDefinedName {
name,
scope,
value: _,
} => {
self.model.delete_defined_name(name, *scope)?;
}
Diff::DeleteDefinedName {
name,
scope,
old_value,
} => {
self.model.new_defined_name(name, *scope, old_value)?;
}
Diff::UpdateDefinedName {
name,
scope,
old_formula,
new_name,
new_scope,
new_formula: _,
} => {
self.model.update_defined_name(
new_name,
*new_scope,
name,
*scope,
old_formula,
)?;
}
Diff::SetSheetState {
index,
old_value,
new_value: _,
} => self.model.set_sheet_state(*index, old_value.clone())?,
}
}
if needs_evaluation {
@@ -2128,33 +1986,6 @@ impl UserModel {
} => {
self.model.set_show_grid_lines(*sheet, *new_value)?;
}
Diff::CreateDefinedName { name, scope, value } => {
self.model.new_defined_name(name, *scope, value)?
}
Diff::DeleteDefinedName {
name,
scope,
old_value: _,
} => self.model.delete_defined_name(name, *scope)?,
Diff::UpdateDefinedName {
name,
scope,
old_formula: _,
new_name,
new_scope,
new_formula,
} => self.model.update_defined_name(
name,
*scope,
new_name,
*new_scope,
new_formula,
)?,
Diff::SetSheetState {
index,
old_value: _,
new_value,
} => self.model.set_sheet_state(*index, new_value.clone())?,
}
}

View File

@@ -2,7 +2,7 @@ use std::collections::HashMap;
use bitcode::{Decode, Encode};
use crate::types::{Cell, Col, Row, SheetState, Style};
use crate::types::{Cell, Col, Row, Style};
#[derive(Clone, Encode, Decode)]
pub(crate) struct RowData {
@@ -104,35 +104,11 @@ pub(crate) enum Diff {
old_value: String,
new_value: String,
},
SetSheetState {
index: u32,
old_value: SheetState,
new_value: SheetState,
},
SetShowGridLines {
sheet: u32,
old_value: bool,
new_value: bool,
},
CreateDefinedName {
name: String,
scope: Option<u32>,
value: String,
},
DeleteDefinedName {
name: String,
scope: Option<u32>,
old_value: String,
},
UpdateDefinedName {
name: String,
scope: Option<u32>,
old_formula: String,
new_name: String,
new_scope: Option<u32>,
new_formula: String,
},
// FIXME: we are missing SetViewDiffs
}, // FIXME: we are missing SetViewDiffs
}
pub(crate) type DiffList = Vec<Diff>;

View File

@@ -27,27 +27,4 @@ impl Workbook {
.get_mut(worksheet_index as usize)
.ok_or_else(|| "Invalid sheet index".to_string())
}
/// Returns the a list of defined names in the workbook with their scope
pub(crate) fn get_defined_names_with_scope(&self) -> Vec<(String, Option<u32>, String)> {
let sheet_id_index: Vec<u32> = self.worksheets.iter().map(|s| s.sheet_id).collect();
let defined_names = self
.defined_names
.iter()
.map(|dn| {
let index = dn
.sheet_id
.and_then(|sheet_id| {
// returns an Option<usize>
sheet_id_index.iter().position(|&x| x == sheet_id)
})
// convert Option<usize> to Option<u32>
.map(|pos| pos as u32);
(dn.name.clone(), index, dn.formula.clone())
})
.collect::<Vec<_>>();
defined_names
}
}

View File

@@ -255,14 +255,11 @@ impl Worksheet {
/// * If the row does not a have a style we add it.
/// * If it has we modify the height and make sure it is applied.
///
/// Fails if row index is outside allowed range or height is negative.
/// Fails if column index is outside allowed range.
pub fn set_row_height(&mut self, row: i32, height: f64) -> Result<(), String> {
if !is_valid_row(row) {
return Err(format!("Row number '{row}' is not valid."));
}
if height < 0.0 {
return Err(format!("Can not set a negative height: {height}"));
}
let rows = &mut self.rows;
for r in rows.iter_mut() {
@@ -287,7 +284,7 @@ impl Worksheet {
/// * If the column does not a have a width we simply add it
/// * If it has, it might be part of a range and we ned to split the range.
///
/// Fails if column index is outside allowed range or width is negative.
/// Fails if column index is outside allowed range.
pub fn set_column_width(&mut self, column: i32, width: f64) -> Result<(), String> {
self.set_column_width_and_style(column, width, None)
}
@@ -301,9 +298,6 @@ impl Worksheet {
if !is_valid_column_number(column) {
return Err(format!("Column number '{column}' is not valid."));
}
if width < 0.0 {
return Err(format!("Can not set a negative width: {width}"));
}
let cols = &mut self.cols;
let mut col = Col {
min: column,
@@ -530,6 +524,23 @@ impl Worksheet {
Ok(is_empty)
}
/// Returns true if cell part of Merged Cells.
/// First cell of Merged cells block is not considered as part of Merged cells
/// Ex : if Merged cells were A1-C3, A1 is not considered as part of Merged cells block
pub fn is_part_of_merged_cells(&self, row: i32, column: i32) -> Result<bool, String> {
if !is_valid_column_number(column) || !is_valid_row(row) {
return Err("Incorrect row or column".to_string());
}
// traverse through Vector of Merged Cells and return (linear search)
for merged_cells in &self.merged_cells_list {
if merged_cells.is_cell_part_of_merged_cells(row, column) {
return Ok(true);
}
}
Ok(false)
}
/// It provides convenient method for user navigation in the spreadsheet by jumping to edges.
/// Spreadsheet engines usually allow this method of navigation by using CTRL+arrows.
/// Behaviour summary:
@@ -583,6 +594,16 @@ impl Worksheet {
}
}
}
/// Returns mutable reference to Vector of Merged cells list
pub fn get_merged_cells_list_mut(&mut self) -> &mut Vec<MergedCells> {
&mut self.merged_cells_list
}
/// Returns reference to Vector of Merged cells list
pub fn get_merged_cells_list(&self) -> &Vec<MergedCells> {
&self.merged_cells_list
}
}
struct WalkFoundCells {

View File

@@ -10,8 +10,6 @@ use xlsx::import;
mod types;
use crate::types::PyCellType;
create_exception!(_ironcalc, WorkbookError, PyException);
/// This is a model implementing the 'raw' API
@@ -60,21 +58,6 @@ impl PyModel {
// Get values
/// Get raw value
pub fn get_cell_content(&self, sheet: u32, row: i32, column: i32) -> PyResult<String> {
self.model
.get_cell_content(sheet, row, column)
.map_err(|e| WorkbookError::new_err(e.to_string()))
}
/// Get cell type
pub fn get_cell_type(&self, sheet: u32, row: i32, column: i32) -> PyResult<PyCellType> {
self.model
.get_cell_type(sheet, row, column)
.map(|cell_type| cell_type.into())
.map_err(|e| WorkbookError::new_err(e.to_string()))
}
/// Get formatted value
pub fn get_formatted_cell_value(&self, sheet: u32, row: i32, column: i32) -> PyResult<String> {
self.model

View File

@@ -1,7 +1,7 @@
use pyo3::prelude::*;
use xlsx::base::types::{
Alignment, Border, BorderItem, BorderStyle, CellType, Fill, Font, FontScheme,
HorizontalAlignment, Style, VerticalAlignment,
Alignment, Border, BorderItem, BorderStyle, Fill, Font, FontScheme, HorizontalAlignment, Style,
VerticalAlignment,
};
#[derive(Clone)]
@@ -161,17 +161,6 @@ pub struct PyFill {
pub bg_color: Option<String>,
}
#[pyclass(eq, eq_int)]
#[derive(PartialEq, Clone)]
pub enum PyCellType {
Number = 1,
Text = 2,
LogicalValue = 4,
ErrorValue = 16,
Array = 64,
CompoundData = 128,
}
// Conversions from references to Py* types to non-Py types
// Enums
@@ -437,31 +426,3 @@ impl From<Style> for PyStyle {
}
}
}
// Conversion from PyCellType to CellType
impl From<PyCellType> for CellType {
fn from(py_cell_type: PyCellType) -> Self {
match py_cell_type {
PyCellType::Number => CellType::Number,
PyCellType::Text => CellType::Text,
PyCellType::LogicalValue => CellType::LogicalValue,
PyCellType::ErrorValue => CellType::ErrorValue,
PyCellType::Array => CellType::Array,
PyCellType::CompoundData => CellType::CompoundData,
}
}
}
// Conversion from CellType to PyCellType
impl From<CellType> for PyCellType {
fn from(cell_type: CellType) -> Self {
match cell_type {
CellType::Number => PyCellType::Number,
CellType::Text => PyCellType::Text,
CellType::LogicalValue => PyCellType::LogicalValue,
CellType::ErrorValue => PyCellType::ErrorValue,
CellType::Array => PyCellType::Array,
CellType::CompoundData => PyCellType::CompoundData,
}
}
}

View File

@@ -169,36 +169,20 @@ clipboard_types = r"""
paste_from_clipboard = r"""
/**
* @param {number} source_sheet
* @param {any} source_range
* @param {any} clipboard
* @param {boolean} is_cut
*/
pasteFromClipboard(source_sheet: number, source_range: any, clipboard: any, is_cut: boolean): void;
pasteFromClipboard(source_range: any, clipboard: any, is_cut: boolean): void;
"""
paste_from_clipboard_types = r"""
/**
* @param {number} source_sheet
* @param {[number, number, number, number]} source_range
* @param {ClipboardData} clipboard
* @param {boolean} is_cut
*/
pasteFromClipboard(source_sheet: number, source_range: [number, number, number, number], clipboard: ClipboardData, is_cut: boolean): void;
"""
defined_name_list = r"""
/**
* @returns {any}
*/
getDefinedNameList(): any;
"""
defined_name_list_types = r"""
/**
* @returns {DefinedName[]}
*/
getDefinedNameList(): DefinedName[];
pasteFromClipboard(source_range: [number, number, number, number], clipboard: ClipboardData, is_cut: boolean): void;
"""
def fix_types(text):
@@ -214,7 +198,6 @@ def fix_types(text):
text = text.replace(paste_csv_string, paste_csv_string_types)
text = text.replace(clipboard, clipboard_types)
text = text.replace(paste_from_clipboard, paste_from_clipboard_types)
text = text.replace(defined_name_list, defined_name_list_types)
with open("types.ts") as f:
types_str = f.read()
header_types = "{}\n\n{}".format(header, types_str)

View File

@@ -1,4 +1,3 @@
use serde::Serialize;
use wasm_bindgen::{
prelude::{wasm_bindgen, JsError},
JsValue,
@@ -30,13 +29,6 @@ pub fn column_name_from_number(column: i32) -> Result<String, JsError> {
}
}
#[derive(Serialize)]
struct DefinedName {
name: String,
scope: Option<u32>,
formula: String,
}
#[wasm_bindgen]
pub struct Model {
model: BaseModel,
@@ -114,16 +106,6 @@ impl Model {
self.model.delete_sheet(sheet).map_err(to_js_error)
}
#[wasm_bindgen(js_name = "hideSheet")]
pub fn hide_sheet(&mut self, sheet: u32) -> Result<(), JsError> {
self.model.hide_sheet(sheet).map_err(to_js_error)
}
#[wasm_bindgen(js_name = "unhideSheet")]
pub fn unhide_sheet(&mut self, sheet: u32) -> Result<(), JsError> {
self.model.unhide_sheet(sheet).map_err(to_js_error)
}
#[wasm_bindgen(js_name = "renameSheet")]
pub fn rename_sheet(&mut self, sheet: u32, name: &str) -> Result<(), JsError> {
self.model.rename_sheet(sheet, name).map_err(to_js_error)
@@ -538,7 +520,6 @@ impl Model {
#[wasm_bindgen(js_name = "pasteFromClipboard")]
pub fn paste_from_clipboard(
&mut self,
source_sheet: u32,
source_range: JsValue,
clipboard: JsValue,
is_cut: bool,
@@ -548,7 +529,7 @@ impl Model {
let clipboard: ClipboardData =
serde_wasm_bindgen::from_value(clipboard).map_err(|e| to_js_error(e.to_string()))?;
self.model
.paste_from_clipboard(source_sheet, source_range, &clipboard, is_cut)
.paste_from_clipboard(source_range, &clipboard, is_cut)
.map_err(|e| to_js_error(e.to_string()))
}
@@ -560,52 +541,4 @@ impl Model {
.paste_csv_string(&range, csv)
.map_err(|e| to_js_error(e.to_string()))
}
#[wasm_bindgen(js_name = "getDefinedNameList")]
pub fn get_defined_name_list(&self) -> Result<JsValue, JsError> {
let data: Vec<DefinedName> = self
.model
.get_defined_name_list()
.iter()
.map(|s| DefinedName {
name: s.0.to_owned(),
scope: s.1,
formula: s.2.to_owned(),
})
.collect();
serde_wasm_bindgen::to_value(&data).map_err(|e| to_js_error(e.to_string()))
}
#[wasm_bindgen(js_name = "newDefinedName")]
pub fn new_defined_name(
&mut self,
name: &str,
scope: Option<u32>,
formula: &str,
) -> Result<(), JsError> {
self.model
.new_defined_name(name, scope, formula)
.map_err(|e| to_js_error(e.to_string()))
}
#[wasm_bindgen(js_name = "updateDefinedName")]
pub fn update_defined_name(
&mut self,
name: &str,
scope: Option<u32>,
new_name: &str,
new_scope: Option<u32>,
new_formula: &str,
) -> Result<(), JsError> {
self.model
.update_defined_name(name, scope, new_name, new_scope, new_formula)
.map_err(|e| to_js_error(e.to_string()))
}
#[wasm_bindgen(js_name = "deleteDefinedName")]
pub fn delete_definedname(&mut self, name: &str, scope: Option<u32>) -> Result<(), JsError> {
self.model
.delete_defined_name(name, scope)
.map_err(|e| to_js_error(e.to_string()))
}
}

View File

@@ -113,7 +113,6 @@ export interface WorksheetProperties {
name: string;
color: string;
sheet_id: number;
state: string;
}
interface CellStyleFill {
@@ -227,10 +226,4 @@ export interface Clipboard {
csv: string;
data: ClipboardData;
range: [number, number, number, number];
}
export interface DefinedName {
name: string;
scope?: number;
formula: string;
}

View File

@@ -58,18 +58,6 @@ export default defineConfig({
text: "Error Types",
link: "/features/error-types",
},
{
text: "Value Types",
link: "/features/value-types",
},
{
text: "Optional Arguments",
link: "/features/optional-arguments",
},
{
text: "Units",
link: "/features/units",
},
{
text: "Unsupported Features",
link: "/features/unsupported-features",
@@ -2015,7 +2003,7 @@ export default defineConfig({
link: "/programming/python-bindings",
},
{
text: "JavaScript",
text: "JavScript",
link: "/programming/javascript-bindings",
},
],

View File

@@ -7,39 +7,31 @@ lang: en-US
# Error Types
::: warning
**Note:** This draft page is under construction 🚧
**Note:** This page is in construction 🚧
:::
The result of a formula is sometimes an _error_. In some situations those errors are expected and your formulas might be dealing with them.
The error `#N/A` might signal that there is no data to evaluate the formula yet. Maybe the payroll has not been introduced for that month just yet.
When working with formulas, you may encounter these common errors:
Some other errors like `#SPILL!`, `#CIRC!` or `#ERROR!` signal an error in your spreadsheet logic and must be corrected.
---
The first kind of errors or 'common errors' are found in other spreadsheet engines like Excel while other errors like `#ERROR!` or `#N/IMPL` are particular to IronCalc.
### **`#ERROR!`**
## Common Errors
**Cause:** General formula issue, like syntax errors or invalid references.
**Fix:** Check the formula for mistakes or invalid cell references.
---
### **`#VALUE!`**
It might be caused by mismatched data types (e.g., text used where numbers are expected):
**Cause:** Mismatched data types (e.g., text used where numbers are expected).
**Fix:** Ensure input types are correct; convert text to numbers if needed.
```
=5+"two"
```
The engine doesn't know how to add the number `5` to the string `two` resulting in a `#VALUE!`.
It is an actual error in your spreadsheet. It indicates that the formula isnt working as intended.
---
### **`#DIV/0!`**
Division by zero or an empty cell:
```
=1/0
```
Usually this is an error. However, in cases where a denominator might be blank (e.g., data not yet filled in), this could be expected. Use `IFERROR` or `IF` to handle it:
**Cause:** Division by zero or an empty cell.
**Fix:** Ensure the denominator isnt zero or blank. Use `IF` to handle such cases:
```
=IF(B1=0, "N/A", A1/B1)
@@ -47,42 +39,23 @@ Usually this is an error. However, in cases where a denominator might be blank (
### **`#NAME?`**
Found when a name is not recognized. Maybe a misspelled name for a function or a reference to a previously defined name that has since been deleted:
```
=UNKNOWN_FUNCTION(A1)
```
This indicates an error in your spreadsheet logic.
**Cause:** Unrecognized text in the formula (e.g., misspelled function names or undefined named ranges).
**Fix:** Correct spelling or define the missing name.
### **`#REF!`**
Indicates an invalid cell reference, often from deleting cells used in a formula.
They can appear as a result of a computation or in a formula. Example:
```
=Sheet34!A1
```
If `Sheet34` doesn't exist it will return `#REF!`
This is a genuine error. It indicates that part of your formula references a cell or range that is missing.
**Cause:** Invalid cell reference, often from deleting cells used in a formula.
**Fix:** Update the formula with correct references.
### **`#NUM!`**
Invalid numeric operation (e.g., calculating the square root of a negative number).
Adjust the formula to ensure valid numeric operations.
Sometimes a `#NUM!` error might be expected, signalling to the user that some parameter is out of scope.
**Cause:** Invalid numeric operation (e.g., calculating a square root of a negative number).
**Fix:** Adjust the formula to ensure valid numeric operations.
### **`#N/A`**
A value is not available, often in lookup functions like VLOOKUP.
This is frequently not an error in your spreadsheet logic.
You can produce a prettier answer using the [`IFNA`](/functions/information/isna) formula:
**Cause:** A value is not available, often in lookup functions like VLOOKUP.
**Fix:** Ensure the lookup value exists or use IFNA() to handle missing values:
```
=IFNA(VLOOKUP(A1, B1:C10, 2, FALSE), "Not Found")
@@ -90,62 +63,17 @@ You can produce a prettier answer using the [`IFNA`](/functions/information/isna
### **`#NULL!`**
Incorrect range operator in a formula (e.g., missing a colon between cell references).
**Cause:** Incorrect range operator in a formula (e.g., missing a colon between cell references).
**Fix:** Use correct range operators (e.g., A1:A10).
### **`#SPILL!`**
A cell in a formula will overwrite content in other cells.
This cannot happen right now in IronCalc as formulas don't spill yet.
### **`#CIRC!`**
Circular reference. This is an error in your spreadsheet and must be fixed.
It means that during the course of a computation, a circular dependency was found.
A circular dependency is a dependency of a formula on itself.
For instance, in the cell `A1` the formula `=A1*2` is a circular dependency.
Other spreadsheet engines use circular dependencies to do "loop computations", run "sensitivity analysis" or "goal seek".
IronCalc doesn't support any of those at the moment.
## IronCalc specific errors
### **`#ERROR!`**
General formula issue, like syntax errors or invalid references.
In general, Excel does not let you enter incorrect formulas, but IronCalc will.
This will make your workbook imcompatible with Excel.
Typical examples might be an incomplete formula, such as `=A1+`, or a function call with too few arguments, such as `=FV(1,2)`.
### **`#N/IMPL!`**
A particular feature is not yet implemented in IronCalc
Check if there is a [Github](https://github.com/ironcalc) ticket or contact us via [email](mailto:hello@ironcalc.com) or [Discord](https://discord.com/invite/zZYWfh3RHJ).
## Error propagation
Some errors are created by some formulas. For instance, the function `SQRT` can create the error `#NUM!`, but can't ceate the error `#DIV/0`.
Once an error is created it is normally _propagated_ by all the formulas. So if cell `C3` evaluates to `#ERROR!`, then the formula
`=SQRT(C3)` will return `#ERROR!`.
Not all functions propagate errors in their arguments. For instance the function `IF(condition, if_true, if_false)` will only propagate an error in the `if_false` argument if the `condition` is `FALSE`. This is called _lazy evaluation_ - the function `IF` is _lazy_ because it only evaluates the arguments when needed. The opposite of lazy evaulaution is called _eager evaluation_.
Some functions also expect an error as an argument like [`ERROR.TYPE`](/functions/information/error.type) and will not propagate the error.
**Cause:** Circular reference.
**Fix:** Remove the circular reference.
## See also
### **`#####`**
The following functions are convenient when working with errors
- [`ISERR(ref)`](/functions/information/iserr), `TRUE` if `ref` is any error type except the `#N/A` error.
- [`ISERROR(ref)`](/functions/information/iserror), `TRUE` if `ref` is any error.
- [`ISNA(ref)`](/functions/information/isna), `TRUE` if ref is `#N/A`.
- [`ERROR.TYPE`](/functions/information/error.type) returns the numeric code for a given error.
- [`IFERROR(ref, value)`](/functions/logical/iferror) returns `value` if the content of `ref` is an error.
- [`IFNA(ref, value)`](/functions/logical/ifna) returns `value` only if the content of `ref` is the `#N/A` error.
**Cause:** The column isnt wide enough to display the value.
**Fix:** Resize the column width to fit the content.

View File

@@ -1,49 +0,0 @@
---
layout: doc
outline: deep
lang: en-US
---
# Optional Arguments
::: warning
**Note:** This draft page is under construction 🚧
:::
Any IronCalc function may accept zero, one or more arguments, which are values passed to the function when it is called from a spreadsheet formula.
Many function arguments are _required_. For such arguments, always pass a suitable value in the function call.
Some function arguments are _optional_. Optional arguments need not be passed in the function call and, in such cases, the function instead uses a predefined default value.
Consider a notional function called _FN\_NAME_, with the following syntax:
<p style="font-weight:bold;text-align:center;">FN_NAME(<span title="Number" style="color:#1E88E5">arg1</span>, <span title="Number" style="color:#1E88E5">arg2</span>, <span title="Number" style="color:#1E88E5">arg3</span>, <span title="Number" style="color:#1E88E5">arg4</span>=def1, <span title="Number" style="color:#1E88E5">arg5</span>=def2, <span title="Number" style="color:#1E88E5">arg6</span>=def3) => <span title="Number" style="color:#1E88E5" >fn_name</span></p>
Notes about this syntax:
* _FN_NAME_ is a function that takes six arguments (_arg1_, _arg2_, _arg3_, _arg4_, _arg5_ and _arg6_) and returns a value referred to as _fn_name_.
* For convenience in this case, all arguments and the returned value are colour-coded to indicate that they are numbers.
* Arguments _arg1_, _arg2_ and _arg3_ are <u>required</u> arguments and this would normally be stated in the **Argument descriptions** section of the function's description page.
* Arguments _arg4_, _arg5_ and _arg6_ are <u>optional</u> arguments and again this would normally be stated in the **Argument descriptions** section of the function's description page. In addition, optional arguments are usually indicated by the specification of a default value in the syntax.
* If _arg4_ is omitted, then the value _def1_ is assumed.
* If _arg5_ is omitted, then the value _def2_ is assumed.
* If _arg6_ is omitted, then the value _def3_ is assumed.
With this syntax, the following would all be valid calls to the _FN_NAME_ function:
**=FN\_NAME(1,2,3)**. All optional arguments omitted.
**=FN\_NAME(1,2,3,4)**. _arg4_ set to 4; optional arguments _arg5_ and _arg6_ assume default values.
**=FN\_NAME(1,2,3,,5)**. _arg5_ set to 5; optional arguments _arg4_ and _arg6_ assume default values.
**=FN\_NAME(1,2,3,,,6)**. _arg6_ set to 6; optional arguments _arg4_ and _arg5_ assume default values.
**=FN\_NAME(1,2,3,4,5)**. _arg4_ and _arg5_ set to 4 and 5 respectively; optional argument _arg6_ assumes default value.
**=FN\_NAME(1,2,3,4,,6)**. _arg4_ and _arg6_ set to 4 and 6 respectively; optional argument _arg5_ assumes default value.
**=FN\_NAME(1,2,3,,5,6)**. _arg5_ and _arg6_ set to 5 and 6 respectively; optional argument _arg4_ assumes default value.
**=FN\_NAME(1,2,3,4,5,6)**. Values passed for all optional arguments.

View File

@@ -1,13 +0,0 @@
---
layout: doc
outline: deep
lang: en-US
---
# Units
::: warning
**Note:** This draft page is under construction 🚧
:::
Some IronCalc functions return values that have units like currencies, percentage or dates.

View File

@@ -1,69 +0,0 @@
---
layout: doc
outline: deep
lang: en-US
---
# Value Types
::: warning
**Note:** This draft page is under construction 🚧
:::
In IronCalc a value, a result of a calculation, can be one of the following.
## Numbers
Numbers in IronCalc are [IEEE 754 double-precision](https://en.wikipedia.org/wiki/Double-precision_floating-point_format).
Numbers are only displayed up to 15 significant figures. That's why `=0.1+0.2` gives `0.3`.
Also, numbers are compared up to 15 significant figures. So `=IF(0.1+0.2=0.3, "Valid", "Invalid")` gives `Valid`.
However, `=0.3-0.2-0.1` will not give exactly `0` in IronCalc.
### Casting into numbers
Strings and booleans are sometimes converted to numbers:
`=1+"2"` => `3`
Some functions cast in weird ways:
`=SUM(1,TRUE)` => `1` and `=SUM(1,"1")` => `1`
And `=SUM(1,A1)` => `1` (where A1 contains `TRUE` or `"1"`)
Sometimes the conversion happens as might be expected. For example, `="123"+1` is `124`, `=SQRT("4")` is `2` and `=SQRT(TRUE)` is `1`.
Some functions, however, are more strict. For example, `=BIN2DEC(TRUE)` gives the #VALUE! error.
### Dates and times
IronCalc uses numbers to represent dates and times.
The integer part of the number represents the date, as a count of days since the fixed starting date of December 30, 1899.
The fractional part of the number represents the time of day. 0.0 corresponds to 00:00:00 (midnight) and 0.5 corresponds to 12:00:00 (noon).
## Strings
### Complex numbers
Using IronCalc, a complex number is a string of the form "1+j3".
## Booleans
### Casting from numbers
## Errors
### Casting from strings
"#N/A" => #N/A
## Arrays

View File

@@ -3,53 +3,9 @@ layout: doc
outline: deep
lang: en-US
---
# FV function
# FV
::: warning
**Note:** This draft page is under construction 🚧
:::
## Overview
FV (<u>F</u>uture <u>V</u>alue) is a function of the Financial category that can be used to predict the future value of an investment or asset based on its present value.
FV can be used to calculate future value over a specified number of compounding periods. A fixed interest rate or yield is assumed over all periods, and a fixed payment or deposit can be applied at the start or end of every period.
If your interest rate varies between periods, use the [FVSCHEDULE](/functions/financial/fvschedule) function instead of FV.
## Usage
### Syntax
**FV(<span title="Number" style="color:#1E88E5">rate</span>, <span title="Number" style="color:#1E88E5">nper</span>, <span title="Number" style="color:#1E88E5">pmt</span>, <span title="Number" style="color:#1E88E5">pv</span>=0, <span title="Boolean" style="color:#43A047">type</span>=FALSE) => <span title="Number" style="color:#1E88E5">fv</span>**
### Argument descriptions
* *rate* ([number](/features/value-types#numbers), required). The fixed percentage interest rate or yield per period.
* *nper* ([number](/features/value-types#numbers), required). "nper" stands for <u>n</u>umber of <u>per</u>iods, in this case the number of compounding periods to be taken into account. While this will often be an integer, non-integer values are accepted and processed.
* *pmt* ([number](/features/value-types#numbers), required). "pmt" stands for <u>p</u>ay<u>m</u>en<u>t</u>, in this case the fixed amount paid or deposited each compounding period.
* *pv* ([number](/features/value-types#numbers), [optional](/features/optional-arguments.md)). "pv" is the <u>p</u>resent <u>v</u>alue or starting amount of the asset (default 0).
* *type* ([boolean](/features/value-types/#booleans), [optional](/features/optional-arguments.md)). A logical value indicating whether the payment due dates are at the end (FALSE or 0) of the compounding periods or at the beginning (TRUE or any non-zero value). The default is FALSE when omitted.
### Additional guidance
* Make sure that the *rate* argument specifies the interest rate or yield applicable to the compounding period, based on the value chosen for *nper*.
* The *pmt* and *pv* arguments should be expressed in the same currency unit.
* To ensure a worthwhile result, one of the *pmt* and *pv* arguments should be non-zero.
* The setting of the *type* argument only affects the calculation for non-zero values of the *pmt* argument.
### Returned value
FV returns a [number](/features/value-types/#numbers) representing the future value expressed in the same [currency unit](/features/units) that was used for the *pmt* and *pv* arguments.
### Error conditions
* In common with many other IronCalc functions, FV propagates errors that are found in any of its arguments.
* If too few or too many arguments are supplied, FV returns the [`#ERROR!`](/features/error-types.md#error) error.
* If the value of any of the *rate*, *nper*, *pmt* or *pv* arguments is not (or cannot be converted to) a [number](/features/value-types#value), then FV returns the [`#VALUE!`](/features/error-types.md#value) error.
* If the value of the *type* argument is not (or cannot be converted to) a [Boolean](/features/value-types#booleans), then FV again returns the [`#VALUE!`](/features/error-types.md#value) error.
* For some combinations of valid argument values, FV may return a [`#NUM!`](/features/error-types.md#num) error or a [`#DIV/0!`](/features/error-types.md#div-0) error.
<!--@include: ../markdown-snippets/error-type-details.txt-->
## Details
* If $\text{type} \neq 0$, $\text{fv}$ is given by the equation:
$$ \text{fv} = -\text{pv} \times (1 + \text{rate})^\text{nper} - \dfrac{\text{pmt}\times\big({(1+\text{rate})^\text{nper}-1}\big) \times(1+\text{rate})}{\text{rate}}$$
* If $\text{type} = 0$, $\text{fv}$ is given by the equation:
$$ \text{fv} = -\text{pv} \times (1 + \text{rate})^{\text{nper}} - \dfrac{\text{pmt}\times\big({(1+\text{rate})^\text{nper}-1}\big)}{\text{rate}}$$
* For any $\text{type}$, in the special case of $\text{rate} = 0$, $\text{fv}$ is given by the equation:
$$ \text{fv} = -\text{pv} - (\text{pmt} \times \text{nper}) $$
## Examples
[See some examples in IronCalc](https://app.ironcalc.com/?example=fv).
## Links
* For more information about the concept of "future value" in finance, visit Wikipedia's [Future value](https://en.wikipedia.org/wiki/Future_value) page.
* See also IronCalc's [NPER](/functions/financial/nper), [PMT](/functions/financial/pmt), [PV](/functions/financial/pv) and [RATE](/functions/financial/rate) functions.
* Visit Microsoft Excel's [FV function](https://support.microsoft.com/en-gb/office/fv-function-2eef9f44-a084-4c61-bdd8-4fe4bb1b71b3) page.
* Both [Google Sheets](https://support.google.com/docs/answer/3093224) and [LibreOffice Calc](https://wiki.documentfoundation.org/Documentation/Calc_Functions/FV) provide versions of the FV function.
🚧 This function is implemented but currently lacks detailed documentation. For guidance, you may refer to the equivalent functionality in [Microsoft Excel documentation](https://support.microsoft.com/en-us/office/excel-functions-by-category-5f91f4e9-7b42-46d2-9bd1-63f26a86c0eb).
:::

View File

@@ -1 +0,0 @@
* For more information about the different types of errors that you may encounter when using IronCalc functions, visit our [Error Types](/features/error-types) page.

View File

@@ -9,13 +9,13 @@ lang: en-US
At the moment IronCalc only supports a few function in this section.
You can track the progress in this [GitHub issue](https://github.com/ironcalc/IronCalc/issues/55).
| Function | Status | Documentation |
| ------------------------ |--------------------------------------------------| ------------- |
| Function | Status | Documentation |
| ------------------------ | ---------------------------------------------- | ------------- |
| AVEDEV | <Badge type="info" text="Not implemented yet" /> | |
| AVERAGE | <Badge type="tip" text="Available" /> | |
| AVERAGEA | <Badge type="tip" text="Available" /> | |
| AVERAGEIF | <Badge type="tip" text="Available" /> | |
| AVERAGEIFS | <Badge type="tip" text="Available" /> | |
| AVERAGE | <Badge type="tip" text="Available" /> | |
| AVERAGEA | <Badge type="tip" text="Available" /> | |
| AVERAGEIF | <Badge type="tip" text="Available" /> | |
| AVERAGEIFS | <Badge type="tip" text="Available" /> | |
| BETA.DIST | <Badge type="info" text="Not implemented yet" /> | |
| BETA.INV | <Badge type="info" text="Not implemented yet" /> | |
| BINOM.DIST | <Badge type="info" text="Not implemented yet" /> | |
@@ -29,11 +29,11 @@ You can track the progress in this [GitHub issue](https://github.com/ironcalc/Ir
| CONFIDENCE.NORM | <Badge type="info" text="Not implemented yet" /> | |
| CONFIDENCE.T | <Badge type="info" text="Not implemented yet" /> | |
| CORREL | <Badge type="info" text="Not implemented yet" /> | |
| COUNT | <Badge type="tip" text="Available" /> | |
| COUNTA | <Badge type="tip" text="Available" /> | |
| COUNTBLANK | <Badge type="tip" text="Available" /> | |
| COUNTIF | <Badge type="tip" text="Available" /> | |
| COUNTIFS | <Badge type="tip" text="Available" /> | |
| COUNT | <Badge type="tip" text="Available" /> | |
| COUNTA | <Badge type="tip" text="Available" /> | |
| COUNTBLANK | <Badge type="tip" text="Available" /> | |
| COUNTIF | <Badge type="tip" text="Available" /> | |
| COUNTIFS | <Badge type="tip" text="Available" /> | |
| COVARIANCE.P | <Badge type="info" text="Not implemented yet" /> | |
| COVARIANCE.S | <Badge type="info" text="Not implemented yet" /> | |
| DEVSQ | <Badge type="info" text="Not implemented yet" /> | |
@@ -58,7 +58,7 @@ You can track the progress in this [GitHub issue](https://github.com/ironcalc/Ir
| GAMMALN | <Badge type="info" text="Not implemented yet" /> | |
| GAMMALN.PRECISE | <Badge type="info" text="Not implemented yet" /> | |
| GAUSS | <Badge type="info" text="Not implemented yet" /> | |
| GEOMEAN | <Badge type="info" text="Available" /> | |
| GEOMEAN | <Badge type="info" text="Not implemented yet" /> | |
| GROWTH | <Badge type="info" text="Not implemented yet" /> | |
| HARMEAN | <Badge type="info" text="Not implemented yet" /> | |
| HYPGEOM.DIST | <Badge type="info" text="Not implemented yet" /> | |
@@ -69,9 +69,9 @@ You can track the progress in this [GitHub issue](https://github.com/ironcalc/Ir
| LOGEST | <Badge type="info" text="Not implemented yet" /> | |
| LOGNORM.DIST | <Badge type="info" text="Not implemented yet" /> | |
| LOGNORM.INV | <Badge type="info" text="Not implemented yet" /> | |
| MAX | <Badge type="tip" text="Available" /> | |
| MAX | <Badge type="tip" text="Available" /> | |
| MAXA | <Badge type="info" text="Not implemented yet" /> | |
| MAXIFS | <Badge type="tip" text="Available" /> | |
| MAXIFS | <Badge type="tip" text="Available" /> | |
| MEDIAN | <Badge type="info" text="Not implemented yet" /> | |
| MODE.MULT | <Badge type="info" text="Not implemented yet" /> | |
| MODE.SNGL | <Badge type="info" text="Not implemented yet" /> | |

View File

@@ -7,5 +7,6 @@ lang: en-US
# GEOMEAN
::: warning
🚧 This function is implemented but currently lacks detailed documentation. For guidance, you may refer to the equivalent functionality in [Microsoft Excel documentation](https://support.microsoft.com/en-us/office/excel-functions-by-category-5f91f4e9-7b42-46d2-9bd1-63f26a86c0eb).
🚧 This function is not yet available in IronCalc.
[Follow development here](https://github.com/ironcalc/IronCalc/labels/Functions)
:::

View File

@@ -1,185 +0,0 @@
import styled from "@emotion/styled";
import { Trash2 } from "lucide-react";
import { useEffect, useRef } from "react";
interface DeleteWorkbookDialogProperties {
onClose: () => void;
onConfirm: () => void;
workbookName: string;
}
function DeleteWorkbookDialog(properties: DeleteWorkbookDialogProperties) {
const deleteButtonRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
const root = document.getElementById("root");
if (root) {
root.style.filter = "blur(2px)";
}
if (deleteButtonRef.current) {
deleteButtonRef.current.focus();
}
return () => {
const root = document.getElementById("root");
if (root) {
root.style.filter = "none";
}
};
}, []);
return (
<DialogWrapper
tabIndex={-1}
onKeyDown={(event) => {
if (event.code === "Escape") {
properties.onClose();
}
}}
role="dialog"
aria-labelledby="delete-dialog-title"
aria-describedby="delete-dialog-description"
>
<IconWrapper>
<Trash2 />
</IconWrapper>
<ContentWrapper>
<Title>Are you sure?</Title>
<Body>
The workbook <strong>'{properties.workbookName}'</strong> will be
permanently deleted. This action cannot be undone.
</Body>
<ButtonGroup>
<DeleteButton
onClick={() => {
properties.onConfirm();
properties.onClose();
}}
ref={deleteButtonRef}
>
Yes, delete workbook
</DeleteButton>
<CancelButton onClick={properties.onClose}>Cancel</CancelButton>
</ButtonGroup>
</ContentWrapper>
</DialogWrapper>
);
}
DeleteWorkbookDialog.displayName = "DeleteWorkbookDialog";
// some colors taken from the IronCalc palette
const COMMON_WHITE = "#FFF";
const COMMON_BLACK = "#272525";
const ERROR_MAIN = "#EB5757";
const ERROR_DARK = "#CB4C4C";
const GREY_200 = "#EEEEEE";
const GREY_300 = "#E0E0E0";
const GREY_700 = "#616161";
const GREY_900 = "#333333";
const PRIMARY_MAIN = "#F2994A";
const PRIMARY_DARK = "#D68742";
const DialogWrapper = styled.div`
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
display: flex;
flex-direction: column;
gap: 16px;
padding: 12px;
border-radius: 8px;
box-shadow: 0px 1px 3px 0px ${COMMON_BLACK}1A;
width: 280px;
max-width: calc(100% - 40px);
z-index: 50;
font-family: "Inter", sans-serif;
`;
const IconWrapper = styled.div`
display: flex;
justify-content: center;
align-items: center;
width: 36px;
height: 36px;
border-radius: 4px;
background-color: ${ERROR_MAIN}1A;
margin: 12px auto 0 auto;
color: ${ERROR_MAIN};
svg {
width: 16px;
height: 16px;
}
`;
const ContentWrapper = styled.div`
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
font-size: 14px;
word-break: break-word;
`;
const Title = styled.h2`
margin: 0;
font-weight: 600;
font-size: inherit;
color: ${GREY_900};
`;
const Body = styled.p`
margin: 0;
text-align: center;
color: ${GREY_900};
font-size: 12px;
`;
const ButtonGroup = styled.div`
display: flex;
flex-direction: column;
gap: 8px;
margin-top: 8px;
width: 100%;
`;
const Button = styled.button`
cursor: pointer;
color: ${COMMON_WHITE};
background-color: ${PRIMARY_MAIN};
padding: 0px 10px;
height: 36px;
border-radius: 4px;
border: none;
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
text-overflow: ellipsis;
transition: background-color 150ms;
&:hover {
background-color: ${PRIMARY_DARK};
}
`;
const DeleteButton = styled(Button)`
background-color: ${ERROR_MAIN};
color: ${COMMON_WHITE};
&:hover {
background-color: ${ERROR_DARK};
}
`;
const CancelButton = styled(Button)`
background-color: ${GREY_200};
color: ${GREY_700};
&:hover {
background-color: ${GREY_300};
}
`;
export default DeleteWorkbookDialog;

View File

@@ -35,11 +35,6 @@ export function FileBar(properties: {
}}
onDelete={properties.onDelete}
/>
<HelpButton
onClick={() => window.open("https://docs.ironcalc.com", "_blank")}
>
Help
</HelpButton>
<WorkbookTitle
name={properties.model.getName()}
onNameChange={(name) => {
@@ -89,7 +84,7 @@ export function FileBar(properties: {
const StyledDesktopLogo = styled(IronCalcLogo)`
width: 120px;
margin-left: 12px;
margin-left: 10px;
@media (max-width: 769px) {
display: none;
}
@@ -103,19 +98,6 @@ const StyledIronCalcIcon = styled(IronCalcIcon)`
}
`;
const HelpButton = styled("div")`
display: flex;
align-items: center;
font-size: 12px;
font-family: Inter;
padding: 8px;
border-radius: 4px;
cursor: pointer;
&:hover {
background-color: #f2f2f2;
}
`;
const Toast = styled("div")`
font-weight: 400;
font-size: 12px;
@@ -125,7 +107,7 @@ const Toast = styled("div")`
`;
const Divider = styled("div")`
margin: 0px 8px 0px 16px;
margin: 10px;
height: 12px;
border-left: 1px solid #e0e0e0;
`;

View File

@@ -1,9 +1,8 @@
import styled from "@emotion/styled";
import { Menu, MenuItem, Modal } from "@mui/material";
import { Check, FileDown, FileUp, Plus, Trash2 } from "lucide-react";
import { FileDown, FileUp, Plus, Trash2 } from "lucide-react";
import { useRef, useState } from "react";
import DeleteWorkbookDialog from "./DeleteWorkbookDialog";
import UploadFileDialog from "./UploadFileDialog";
import { UploadFileDialog } from "./UploadFileDialog";
import { getModelsMetadata, getSelectedUuid } from "./storage";
export function FileMenu(props: {
@@ -19,7 +18,6 @@ export function FileMenu(props: {
const models = getModelsMetadata();
const uuids = Object.keys(models);
const selectedUuid = getSelectedUuid();
const [isDeleteDialogOpen, setDeleteDialogOpen] = useState(false);
const elements = [];
for (const uuid of uuids) {
@@ -31,9 +29,9 @@ export function FileMenu(props: {
setMenuOpen(false);
}}
>
<CheckIndicator>
{uuid === selectedUuid ? <StyledCheck /> : ""}
</CheckIndicator>
<span style={{ width: "20px" }}>
{uuid === selectedUuid ? "•" : ""}
</span>
<MenuItemText
style={{
maxWidth: "240px",
@@ -59,19 +57,9 @@ export function FileMenu(props: {
open={isMenuOpen}
onClose={(): void => setMenuOpen(false)}
anchorEl={anchorElement.current}
sx={{
"& .MuiPaper-root": { borderRadius: "8px", padding: "4px 0px" },
"& .MuiList-root": { padding: "0" },
}}
// anchorOrigin={properties.anchorOrigin}
>
<MenuItemWrapper
onClick={() => {
props.newModel();
setMenuOpen(false);
}}
>
<MenuItemWrapper onClick={props.newModel}>
<StyledPlus />
<MenuItemText>New</MenuItemText>
</MenuItemWrapper>
@@ -90,14 +78,16 @@ export function FileMenu(props: {
Download (.xlsx)
</MenuItemText>
</MenuItemWrapper>
<MenuItemWrapper
onClick={() => {
setDeleteDialogOpen(true);
setMenuOpen(false);
}}
>
<MenuItemWrapper>
<StyledTrash />
<MenuItemText>Delete workbook</MenuItemText>
<MenuItemText
onClick={() => {
props.onDelete();
setMenuOpen(false);
}}
>
Delete workbook
</MenuItemText>
</MenuItemWrapper>
<MenuDivider />
{elements}
@@ -105,6 +95,10 @@ export function FileMenu(props: {
<Modal
open={isImportMenuOpen}
onClose={() => {
const root = document.getElementById("root");
if (root) {
root.style.filter = "";
}
setImportMenuOpen(false);
}}
aria-labelledby="modal-modal-title"
@@ -113,26 +107,16 @@ export function FileMenu(props: {
<>
<UploadFileDialog
onClose={() => {
const root = document.getElementById("root");
if (root) {
root.style.filter = "";
}
setImportMenuOpen(false);
}}
onModelUpload={props.onModelUpload}
/>
</>
</Modal>
<Modal
open={isDeleteDialogOpen}
onClose={() => setDeleteDialogOpen(false)}
aria-labelledby="delete-dialog-title"
aria-describedby="delete-dialog-description"
>
<>
<DeleteWorkbookDialog
onClose={() => setDeleteDialogOpen(false)}
onConfirm={props.onDelete}
workbookName={selectedUuid ? models[selectedUuid] : ""}
/>
</>
</Modal>
</>
);
}
@@ -165,19 +149,12 @@ const StyledTrash = styled(Trash2)`
padding-right: 10px;
`;
const StyledCheck = styled(Check)`
width: 16px;
height: 16px;
color: #333333;
padding-right: 10px;
`;
const MenuDivider = styled("div")`
width: 100%;
width: 80%;
margin: auto;
margin-top: 4px;
margin-bottom: 4px;
border-top: 1px solid #eeeeee;
margin-top: 8px;
margin-bottom: 8px;
border-top: 1px solid #e0e0e0;
`;
const MenuItemText = styled("div")`
@@ -189,12 +166,7 @@ const MenuItemWrapper = styled(MenuItem)`
display: flex;
justify-content: flex-start;
font-size: 14px;
width: calc(100% - 8px);
min-width: 172px;
margin: 0px 4px;
border-radius: 4px;
padding: 8px;
height: 32px;
width: 100%;
`;
const FileMenuWrapper = styled("div")`
@@ -202,16 +174,11 @@ const FileMenuWrapper = styled("div")`
align-items: center;
font-size: 12px;
font-family: Inter;
padding: 8px;
padding: 10px;
height: 20px;
border-radius: 4px;
cursor: pointer;
&:hover {
background-color: #f2f2f2;
}
`;
const CheckIndicator = styled("span")`
display: flex;
justify-content: center;
min-width: 26px;
`;

View File

@@ -1,34 +1,17 @@
import styled from "@emotion/styled";
import { BookOpen, FileUp, X } from "lucide-react";
import { type DragEvent, useEffect, useRef, useState } from "react";
import { BookOpen, FileUp } from "lucide-react";
import { type DragEvent, useRef, useState } from "react";
function UploadFileDialog(properties: {
export function UploadFileDialog(properties: {
onClose: () => void;
onModelUpload: (blob: ArrayBuffer, fileName: string) => Promise<void>;
}) {
const [hover, setHover] = useState(false);
const [message, setMessage] = useState("");
const fileInputRef = useRef<HTMLInputElement>(null);
const crossRef = useRef<HTMLDivElement>(null);
const { onModelUpload } = properties;
useEffect(() => {
const root = document.getElementById("root");
if (root) {
root.style.filter = "blur(2px)";
}
if (crossRef.current) {
crossRef.current.focus();
}
return () => {
const root = document.getElementById("root");
if (root) {
root.style.filter = "none";
}
};
}, []);
const handleClose = () => {
properties.onClose();
};
@@ -96,16 +79,12 @@ function UploadFileDialog(properties: {
reader.readAsArrayBuffer(file);
};
const root = document.getElementById("root");
if (root) {
root.style.filter = "blur(4px)";
}
return (
<UploadDialog
tabIndex={-1}
role="dialog"
onKeyDown={(event) => {
if (event.code === "Escape") {
handleClose();
}
}}
>
<UploadDialog>
<UploadTitle>
<span style={{ flexGrow: 2, marginLeft: 12 }}>
Import an .xlsx file
@@ -113,11 +92,29 @@ function UploadFileDialog(properties: {
<Cross
style={{ marginRight: 12 }}
onClick={handleClose}
title="Close Dialog"
ref={crossRef}
tabIndex={0}
onKeyDown={() => {}}
>
<X />
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<title>Close</title>
<path
d="M12 4.5L4 12.5"
stroke="#333333"
strokeLinecap="round"
strokeLinejoin="round"
/>
<path
d="M4 4.5L12 12.5"
stroke="#333333"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</Cross>
</UploadTitle>
{message === "" ? (
@@ -137,7 +134,7 @@ function UploadFileDialog(properties: {
width: 16,
color: "#EFAA6D",
backgroundColor: "#F2994A1A",
padding: "2px 6px",
padding: "2px 4px",
borderRadius: 4,
}}
/>
@@ -195,13 +192,7 @@ function UploadFileDialog(properties: {
<BookOpen
style={{ width: 16, height: 16, marginLeft: 12, marginRight: 8 }}
/>
<UploadFooterLink
href="https://docs.ironcalc.com/web-application/importing-files.html"
target="_blank"
rel="noopener noreferrer"
>
Learn more about importing files into IronCalc
</UploadFooterLink>
<span>Learn more about importing files into IronCalc</span>
</UploadFooter>
</UploadDialog>
);
@@ -211,51 +202,34 @@ const Cross = styled("div")`
&:hover {
background-color: #f5f5f5;
}
display: flex;
border-radius: 4px;
height: 24px;
width: 24px;
cursor: pointer;
align-items: center;
justify-content: center;
svg {
width: 16px;
height: 16px;
stroke-width: 1.5;
}
height: 16px;
width: 16px;
`;
const DocLink = styled("span")`
color: #f2994a;
text-decoration: none;
text-decoration: underline;
&:hover {
text-decoration: underline;
font-weight: bold;
}
`;
const UploadFooter = styled("div")`
height: 44px;
height: 40px;
border-top: 1px solid #e0e0e0;
color: #757575;
display: flex;
align-items: center;
`;
const UploadFooterLink = styled("a")`
font-size: 12px;
font-weight: 400;
color: #757575;
text-decoration: none;
&:hover {
text-decoration: underline;
}
display: flex;
align-items: center;
`;
const UploadTitle = styled("div")`
display: flex;
align-items: center;
border-bottom: 1px solid #e0e0e0;
height: 44px;
height: 40px;
font-size: 14px;
font-weight: 500;
`;
@@ -267,8 +241,7 @@ const UploadDialog = styled("div")`
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 460px;
max-width: 90%;
width: 455px;
height: 285px;
background: #fff;
border: 1px solid #e0e0e0;
@@ -278,16 +251,6 @@ const UploadDialog = styled("div")`
`;
const DropZone = styled("div")`
&:hover {
border: 1px dashed #f2994a;
transition: 0.2s ease-in-out;
gap: 8px;
background: linear-gradient(
180deg,
rgba(242, 153, 74, 0.12) 0%,
rgba(242, 153, 74, 0) 100%
);
}
flex-grow: 2;
border-radius: 10px;
text-align: center;
@@ -296,7 +259,7 @@ const DropZone = styled("div")`
font-family: Arial, sans-serif;
cursor: pointer;
background-color: #faebd7;
border: 1px dashed #efaa6d;
border: 1px dashed #f2994a;
background: linear-gradient(
180deg,
rgba(242, 153, 74, 0.08) 0%,
@@ -305,8 +268,4 @@ const DropZone = styled("div")`
display: flex;
flex-direction: column;
vertical-align: center;
gap: 16px;
transition: 0.2s ease-in-out;
`;
export default UploadFileDialog;

View File

@@ -1,430 +0,0 @@
import type { DefinedName, Model } from "@ironcalc/wasm";
import {
Box,
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
IconButton,
Stack,
styled,
Box,
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
IconButton,
Stack,
styled,
} from "@mui/material";
import { t } from "i18next";
import { BookOpen, Check, X } from "lucide-react";
import { useEffect, useState } from "react";
import NamedRange from "./NamedRange";
import { getFullRangeToString } from "./util";
type NameManagerDialogProperties = {
onClose: () => void;
open: boolean;
model: Model;
onClose: () => void;
open: boolean;
model: Model;
};
function NameManagerDialog(props: NameManagerDialogProperties) {
const [definedNamesLocal, setDefinedNamesLocal] = useState<DefinedName[]>();
const [definedName, setDefinedName] = useState<DefinedName>({
name: "",
scope: undefined,
formula: "",
});
// render definedNames from model
useEffect(() => {
if (props.open) {
const definedNamesModel = props.model.getDefinedNameList();
setDefinedNamesLocal(definedNamesModel);
console.log("definedNamesModel EFFECT", definedNamesModel);
}
}, [props.open]);
const handleSave = () => {
try {
console.log("SAVE", definedName);
props.model.newDefinedName(
definedName.name,
definedName.scope,
definedName.formula,
);
} catch (error) {
console.log("DefinedName save failed", error);
}
props.onClose();
};
const handleChange = (
field: keyof DefinedName,
value: string | number | undefined,
) => {
setDefinedName((prev: DefinedName) => ({
...prev,
[field]: value,
}));
};
const handleDelete = (name: string, scope: number | undefined) => {
try {
props.model.deleteDefinedName(name, scope);
} catch (error) {
console.log("DefinedName delete failed", error);
}
// should re-render modal
};
const handleUpdate = (
name: string,
scope: number | undefined,
newName: string,
newScope: number | undefined,
newFormula: string,
) => {
try {
// partially update?
props.model.updateDefinedName(name, scope, newName, newScope, newFormula);
} catch (error) {
console.log("DefinedName update failed", error);
}
};
const formatFormula = (): string => {
const worksheets = props.model.getWorksheetsProperties();
const selectedView = props.model.getSelectedView();
const formatFormula = (): string => {
const worksheets = props.model.getWorksheetsProperties();
const selectedView = props.model.getSelectedView();
return getFullRangeToString(selectedView, worksheets);
};
return getFullRangeToString(selectedView, worksheets);
};
return (
<StyledDialog
open={props.open}
onClose={props.onClose}
maxWidth={false}
scroll="paper"
>
<StyledDialogTitle>
Named Ranges
<IconButton onClick={() => props.onClose()}>
<X size={16} />
</IconButton>
</StyledDialogTitle>
<StyledDialogContent dividers>
<StyledRangesHeader>
<Box width="171px">{t("name_manager_dialog.name")}</Box>
<Box width="171px">{t("name_manager_dialog.range")}</Box>
<Box width="171px">{t("name_manager_dialog.scope")}</Box>
</StyledRangesHeader>
{definedNamesLocal?.map((definedName) => (
<NamedRange
worksheets={props.model.getWorksheetsProperties()}
name={definedName.name}
scope={definedName.scope}
formula={definedName.formula}
key={definedName.name}
model={props.model}
onChange={handleChange}
onDelete={handleDelete}
canDelete={true}
/>
))}
<NamedRange
worksheets={props.model.getWorksheetsProperties()}
formula={formatFormula()}
onChange={handleChange}
canDelete={false}
model={props.model}
/>
</StyledDialogContent>
<StyledDialogActions>
<Box display="flex" alignItems="center" gap={"8px"}>
<BookOpen color="grey" size={16} />
<span style={{ fontSize: "12px", fontFamily: "Inter" }}>
{t("name_manager_dialog.help")}
</span>
</Box>
<Box display="flex" gap="8px" width={"155px"}>
{/* change hover color? */}
<Button
onClick={() => props.onClose()}
variant="contained"
disableElevation
color="info"
sx={{
bgcolor: (theme): string => theme.palette.grey["200"],
color: (theme): string => theme.palette.grey["700"],
textTransform: "none",
}}
>
Cancel
</Button>
<Button
onClick={handleSave}
variant="contained"
disableElevation
sx={{ textTransform: "none" }}
startIcon={<Check size={16} />}
// disabled={} // disable when error
>
Save
</Button>
</Box>
</StyledDialogActions>
</StyledDialog>
);
}
const StyledDialog = styled(Dialog)(() => ({
"& .MuiPaper-root": {
height: "380px",
minWidth: "620px",
},
}));
const StyledDialogTitle = styled(DialogTitle)`
padding: 12px 20px;
font-size: 14px;
font-weight: 600;
display: flex;
align-items: center;
justify-content: space-between;
`;
const StyledDialogContent = styled(DialogContent)`
display: flex;
flex-direction: column;
gap: 12px;
padding: 20px 12px 20px 20px;
`;
const StyledRangesHeader = styled(Stack)(({ theme }) => ({
flexDirection: "row",
gap: "12px",
fontFamily: theme.typography.fontFamily,
fontSize: "12px",
fontWeight: "700",
color: theme.palette.info.main,
}));
const StyledDialogActions = styled(DialogActions)`
padding: 12px 20px;
height: 40px;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 12px;
color: #757575;
`;
export default NameManagerDialog;
import type { DefinedName, Model } from "@ironcalc/wasm";
import {
Box,
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
IconButton,
Stack,
styled,
} from "@mui/material";
import { t } from "i18next";
import { BookOpen, Check, X } from "lucide-react";
import { useEffect, useState } from "react";
import NamedRange from "./NamedRange";
import { getShortRangeToString } from "./util";
type NameManagerDialogProperties = {
onClose: () => void;
open: boolean;
model: Model;
};
function NameManagerDialog(props: NameManagerDialogProperties) {
const [definedNamesLocal, setDefinedNamesLocal] = useState<DefinedName[]>();
const [definedName, setDefinedName] = useState<DefinedName>({
name: "",
scope: 0,
formula: "",
});
// render named ranges from model
useEffect(() => {
const definedNamesModel = props.model.getDefinedNameList();
setDefinedNamesLocal(definedNamesModel);
console.log("definedNamesModel EFFECT", definedNamesModel);
});
const handleSave = () => {
console.log("SAVE DIALOG", definedName);
// create newDefinedName and close
// props.model.newDefinedName(
// definedName.name,
// definedName.scope,
// definedName.formula,
// );
props.onClose();
};
const handleChange = (field: keyof DefinedName, value: string | number) => {
setDefinedName((prev: DefinedName) => ({
...prev,
[field]: value,
}));
};
const handleDelete = () => {
console.log("definedName marked for deletion");
};
const formatFormula = (): string => {
const selectedView = props.model.getSelectedView();
return getShortRangeToString(selectedView);
};
return (
<StyledDialog
open={props.open}
onClose={props.onClose}
maxWidth={false}
scroll="paper"
>
<StyledDialogTitle>
Named Ranges
<IconButton onClick={() => props.onClose()}>
<X size={16} />
</IconButton>
</StyledDialogTitle>
<StyledDialogContent dividers>
<StyledRangesHeader>
<Box width="171px">{t("name_manager_dialog.name")}</Box>
<Box width="171px">{t("name_manager_dialog.range")}</Box>
<Box width="171px">{t("name_manager_dialog.scope")}</Box>
</StyledRangesHeader>
{definedNamesLocal?.map((definedName) => (
<NamedRange
worksheets={props.model.getWorksheetsProperties()}
name={definedName.name}
scope={definedName.scope}
formula={definedName.formula}
key={definedName.name}
model={props.model}
onChange={handleChange}
onDelete={handleDelete}
/>
))}
<NamedRange
worksheets={props.model.getWorksheetsProperties()}
formula={formatFormula()}
onChange={handleChange}
model={props.model}
/>
</StyledDialogContent>
<StyledDialogActions>
<Box display="flex" alignItems="center" gap={"8px"}>
<BookOpen color="grey" size={16} />
<span style={{ fontSize: "12px", fontFamily: "Inter" }}>
{t("name_manager_dialog.help")}
</span>
</Box>
<Box display="flex" gap="8px" width={"155px"}>
{/* change hover color? */}
<Button
onClick={() => props.onClose()}
variant="contained"
disableElevation
color="info"
sx={{
bgcolor: (theme): string => theme.palette.grey["200"],
color: (theme): string => theme.palette.grey["700"],
textTransform: "none",
}}
>
Cancel
</Button>
<Button
onClick={handleSave}
variant="contained"
disableElevation
sx={{ textTransform: "none" }}
startIcon={<Check size={16} />}
>
Save
</Button>
</Box>
</StyledDialogActions>
</StyledDialog>
);
}
const StyledDialog = styled(Dialog)(() => ({
"& .MuiPaper-root": {
height: "380px",
minWidth: "620px",
},
"& .MuiPaper-root": {
height: "380px",
minWidth: "620px",
},
}));
const StyledDialogTitle = styled(DialogTitle)`
padding: 12px 20px;
font-size: 14px;
font-weight: 600;
display: flex;
align-items: center;
justify-content: space-between;
`;
const StyledDialogContent = styled(DialogContent)`
display: flex;
flex-direction: column;
gap: 12px;
padding: 20px 12px 20px 20px;
`;
const StyledRangesHeader = styled(Stack)(({ theme }) => ({
flexDirection: "row",
gap: "12px",
fontFamily: theme.typography.fontFamily,
fontSize: "12px",
fontWeight: "700",
color: theme.palette.info.main,
flexDirection: "row",
gap: "12px",
fontFamily: theme.typography.fontFamily,
fontSize: "12px",
fontWeight: "700",
color: theme.palette.info.main,
}));
const StyledDialogActions = styled(DialogActions)`
padding: 12px 20px;
height: 40px;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 12px;
color: #757575;
`;
export default NameManagerDialog;

View File

@@ -1,168 +0,0 @@
import type { DefinedName, Model, WorksheetProperties } from "@ironcalc/wasm";
import {
Box,
Divider,
IconButton,
MenuItem,
TextField,
styled,
Box,
Divider,
IconButton,
MenuItem,
TextField,
styled,
} from "@mui/material";
import { Trash2 } from "lucide-react";
import { useEffect, useState } from "react";
type NamedRangeProperties = {
name?: string;
scope?: number;
formula: string;
model: Model;
worksheets: WorksheetProperties[];
onChange: (
field: keyof DefinedName,
value: string | number | undefined,
) => void;
onDelete?: (name: string, scope: number | undefined) => void;
canDelete: boolean;
onUpdate?: (
name: string,
scope: number | undefined,
newName: string,
newScope: number | undefined,
newFormula: string,
) => void;
};
function NamedRange(props: NamedRangeProperties) {
const [name, setName] = useState(props.name || "");
const [scope, setScope] = useState(props.scope || undefined);
const [formula, setFormula] = useState(props.formula);
const [nameError, setNameError] = useState(false);
const [formulaError, setFormulaError] = useState(false);
const handleChange = (
field: keyof DefinedName,
value: string | number | undefined,
) => {
if (field === "name") {
setName(value as string);
props.onChange("name", value);
}
if (field === "scope") {
setScope(value as number | undefined);
props.onChange("scope", value);
}
if (field === "formula") {
setFormula(value as string);
props.onChange("formula", value);
}
};
useEffect(() => {
// send initial formula value to parent
handleChange("formula", formula);
}, []);
const handleDelete = () => {
props.onDelete?.(name, scope);
};
return (
<>
<StyledBox>
<StyledTextField
id="name"
variant="outlined"
size="small"
margin="none"
fullWidth
error={nameError}
value={name}
onChange={(event) => handleChange("name", event.target.value)}
onKeyDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => event.stopPropagation()}
/>
<StyledTextField
id="scope"
variant="outlined"
select
size="small"
margin="none"
fullWidth
value={scope ?? "Workbook (Global)"}
onChange={(event) =>
handleChange(
"scope",
event.target.value === "Workbook (Global)"
? undefined
: event.target.value,
)
}
>
<MenuItem value="Workbook (Global)">Workbook (Global)</MenuItem>
{props.worksheets.map((option, index) => (
<MenuItem key={option.sheet_id} value={index}>
{option.name}
</MenuItem>
))}
</StyledTextField>
<StyledTextField
id="formula"
variant="outlined"
size="small"
margin="none"
fullWidth
error={formulaError}
value={formula}
onChange={(event) => handleChange("formula", event.target.value)}
onKeyDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => event.stopPropagation()}
/>
<StyledIconButton onClick={handleDelete} disabled={!props.canDelete}>
<Trash2 size={12} />
</StyledIconButton>
</StyledBox>
<Divider />
</>
);
}
const StyledBox = styled(Box)`
display: flex;
gap: 12px;
width: 577px;
`;
const StyledTextField = styled(TextField)(() => ({
"& .MuiInputBase-root": {
height: "28px",
margin: 0,
},
"& .MuiInputBase-root": {
height: "28px",
margin: 0,
},
}));
const StyledIconButton = styled(IconButton)(({ theme }) => ({
color: theme.palette.error.main,
"&.Mui-disabled": {
opacity: 0.6,
color: theme.palette.error.light,
},
color: theme.palette.error.main,
"&.Mui-disabled": {
opacity: 0.6,
color: theme.palette.error.light,
},
}));
export default NamedRange;

View File

@@ -1,151 +0,0 @@
import { Dialog, TextField, styled } from "@mui/material";
import { Check, X } from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { theme } from "../../theme";
interface SheetRenameDialogProps {
open: boolean;
onClose: () => void;
onNameChanged: (name: string) => void;
defaultName: string;
}
const SheetRenameDialog = (properties: SheetRenameDialogProps) => {
const { t } = useTranslation();
const [name, setName] = useState(properties.defaultName);
const handleClose = () => {
properties.onClose();
};
return (
<Dialog open={properties.open} onClose={properties.onClose}>
<StyledDialogTitle>
{t("sheet_rename.title")}
<Cross
onClick={handleClose}
title={t("sheet_rename.close")}
tabIndex={-1}
onKeyDown={() => {}}
>
<X />
</Cross>
</StyledDialogTitle>
<StyledDialogContent>
<StyledTextField
autoFocus
defaultValue={properties.defaultName}
onClick={(event) => event.stopPropagation()}
onKeyDown={(event) => {
event.stopPropagation();
if (event.key === "Enter") {
properties.onNameChanged(name);
properties.onClose();
} else if (event.key === "Escape") {
properties.onClose();
}
}}
onChange={(event) => {
setName(event.target.value);
}}
spellCheck="false"
onPaste={(event) => event.stopPropagation()}
onCopy={(event) => event.stopPropagation()}
onCut={(event) => event.stopPropagation()}
/>
</StyledDialogContent>
<DialogFooter>
<StyledButton
onClick={() => {
properties.onNameChanged(name);
}}
>
<Check
style={{ width: "16px", height: "16px", marginRight: "8px" }}
/>
{t("sheet_rename.rename")}
</StyledButton>
</DialogFooter>
</Dialog>
);
};
const StyledDialogTitle = styled("div")`
display: flex;
align-items: center;
height: 44px;
font-size: 14px;
font-weight: 500;
font-family: Inter;
padding: 0px 12px;
justify-content: space-between;
border-bottom: 1px solid ${theme.palette.grey["300"]};
`;
const Cross = styled("div")`
&:hover {
background-color: ${theme.palette.grey["50"]};
}
display: flex;
border-radius: 4px;
height: 24px;
width: 24px;
cursor: pointer;
align-items: center;
justify-content: center;
svg {
width: 16px;
height: 16px;
stroke-width: 1.5;
}
`;
const StyledDialogContent = styled("div")`
font-size: 12px;
margin: 12px;
`;
const StyledTextField = styled(TextField)`
width: 100%;
border-radius: 4px;
overflow: hidden;
& .MuiInputBase-input {
font-size: 14px;
padding: 10px;
border: 1px solid ${theme.palette.grey["300"]};
border-radius: 4px;
color: ${theme.palette.common.black};
background-color: ${theme.palette.common.white};
}
&:hover .MuiInputBase-input {
border: 1px solid ${theme.palette.grey["500"]};
}
`;
const DialogFooter = styled("div")`
color: #757575;
display: flex;
align-items: center;
border-top: 1px solid ${theme.palette.grey["300"]};
font-family: Inter;
justify-content: flex-end;
padding: 12px;
`;
const StyledButton = styled("div")`
cursor: pointer;
color: #ffffff;
background: #f2994a;
padding: 0px 10px;
height: 36px;
line-height: 36px;
border-radius: 4px;
display: flex;
align-items: center;
font-family: "Inter";
font-size: 14px;
&:hover {
background: #d68742;
}
`;
export default SheetRenameDialog;

View File

@@ -1 +0,0 @@
export { default } from "./SheetTabBar";

View File

@@ -5,10 +5,10 @@ export const headerGlobalSelectorColor = "#EAECF4";
export const headerSelectedBackground = "#EEEEEE";
export const headerFullSelectedBackground = "#D3D6E9";
export const headerSelectedColor = "#333";
export const headerBorderColor = "#E0E0E0";
export const headerBorderColor = "#DEE0EF";
export const gridColor = "#E0E0E0";
export const gridSeparatorColor = "#E0E0E0";
export const gridSeparatorColor = "#D3D6E9";
export const defaultTextColor = "#2E414D";
export const outlineColor = "#F2994A";

View File

@@ -867,18 +867,14 @@ export default class WorksheetCanvas {
frozenRows,
frozenColumns,
);
if (frozenColumns > 0) {
xFrozenEnd += this.getColumnWidth(
this.model.getSelectedSheet(),
frozenColumns,
);
}
if (frozenRows > 0) {
yFrozenEnd += this.getRowHeight(
this.model.getSelectedSheet(),
frozenRows,
);
}
xFrozenEnd += this.getColumnWidth(
this.model.getSelectedSheet(),
frozenColumns,
);
yFrozenEnd += this.getRowHeight(
this.model.getSelectedSheet(),
frozenRows,
);
if (startRow <= frozenRows && endRow > frozenRows) {
yEnd = Math.max(yEnd, yFrozenEnd);
}

View File

@@ -38,7 +38,7 @@ const BorderPicker = (properties: BorderPickerProps) => {
const { t } = useTranslation();
const [borderSelected, setBorderSelected] = useState<BorderType | null>(null);
const [borderColor, setBorderColor] = useState(theme.palette.common.white);
const [borderColor, setBorderColor] = useState("#000000");
const [borderStyle, setBorderStyle] = useState(BorderStyle.Thin);
const [colorPickerOpen, setColorPickerOpen] = useState(false);
const [stylePickerOpen, setStylePickerOpen] = useState(false);
@@ -62,7 +62,7 @@ const BorderPicker = (properties: BorderPickerProps) => {
// biome-ignore lint/correctness/useExhaustiveDependencies: We reset the styles, every time we open (or close) the widget
useEffect(() => {
setBorderSelected(null);
setBorderColor(theme.palette.common.white);
setBorderColor("#000000");
setBorderStyle(BorderStyle.Thin);
}, [properties.open]);
@@ -240,21 +240,31 @@ const BorderPicker = (properties: BorderPickerProps) => {
</Borders>
<Divider />
<Styles>
<ButtonWrapper
onClick={() => setColorPickerOpen(true)}
ref={borderColorButton}
>
<PencilLine />
<ButtonWrapper onClick={() => setColorPickerOpen(true)}>
<Button
type="button"
$pressed={false}
disabled={false}
ref={borderColorButton}
title={t("toolbar.borders.color")}
>
<PencilLine />
</Button>
<div style={{ flexGrow: 2 }}>Border color</div>
<ChevronRightStyled />
</ButtonWrapper>
<ButtonWrapper
onClick={() => setStylePickerOpen(true)}
ref={borderStyleButton}
>
<BorderStyleIcon />
<Button
type="button"
$pressed={false}
disabled={false}
title={t("toolbar.borders.style")}
>
<BorderStyleIcon />
</Button>
<div style={{ flexGrow: 2 }}>Border style</div>
<ChevronRightStyled />
</ButtonWrapper>
@@ -271,14 +281,6 @@ const BorderPicker = (properties: BorderPickerProps) => {
}}
anchorEl={borderColorButton}
open={colorPickerOpen}
anchorOrigin={{
vertical: "top", // Keep vertical alignment at the top
horizontal: "right", // Set horizontal alignment to right
}}
transformOrigin={{
vertical: "top", // Keep vertical alignment at the top
horizontal: "left", // Set horizontal alignment to left
}}
/>
<StyledPopover
open={stylePickerOpen}
@@ -286,10 +288,8 @@ const BorderPicker = (properties: BorderPickerProps) => {
setStylePickerOpen(false);
}}
anchorEl={borderStyleButton.current}
anchorOrigin={{
vertical: "top",
horizontal: "right",
}}
anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
transformOrigin={{ vertical: 38, horizontal: -6 }}
>
<BorderStyleDialog>
<LineWrapper
@@ -336,12 +336,12 @@ const LineWrapper = styled("div")<LineWrapperProperties>`
align-items: center;
background-color: ${({ $checked }): string => {
if ($checked) {
return theme.palette.grey["200"];
return "#EEEEEE;";
}
return "inherit;";
}};
&:hover {
border: 1px solid ${theme.palette.grey["200"]};
border: 1px solid #eeeeee;
}
padding: 8px;
cursor: pointer;
@@ -351,59 +351,52 @@ const LineWrapper = styled("div")<LineWrapperProperties>`
const SolidLine = styled("div")`
width: 68px;
border-top: 1px solid ${theme.palette.grey["900"]};
border-top: 1px solid #333333;
`;
const MediumLine = styled("div")`
width: 68px;
border-top: 2px solid ${theme.palette.grey["900"]};
border-top: 2px solid #333333;
`;
const ThickLine = styled("div")`
width: 68px;
border-top: 1px solid ${theme.palette.grey["900"]};
border-top: 3px solid #333333;
`;
const Divider = styled("div")`
width: 100%;
margin: auto;
border-top: 1px solid ${theme.palette.grey["200"]};
display: inline-flex;
heigh: 1px;
border-bottom: 1px solid #eee;
margin-left: 0px;
margin-right: 0px;
`;
const Borders = styled("div")`
display: flex;
flex-direction: column;
gap: 4px;
padding: 4px;
padding-bottom: 4px;
`;
const Styles = styled("div")`
display: flex;
flex-direction: column;
padding: 4px;
`;
const Line = styled("div")`
display: flex;
flex-direction: row;
align-items: center;
gap: 4px;
`;
const ButtonWrapper = styled("div")`
display: flex;
flex-direction: row;
align-items: center;
border-radius: 4px;
gap: 8px;
&:hover {
background-color: ${theme.palette.grey["200"]};
border-top-color: ${(): string => theme.palette.grey["200"]};
background-color: #eee;
border-top-color: ${(): string => theme.palette.grey["400"]};
}
cursor: pointer;
padding: 8px;
svg {
width: 16px;
height: 16px;
}
`;
const BorderStyleDialog = styled("div")`
@@ -416,7 +409,7 @@ const BorderStyleDialog = styled("div")`
const StyledPopover = styled(Popover)`
.MuiPopover-paper {
border-radius: 8px;
border-radius: 10px;
border: 0px solid ${({ theme }): string => theme.palette.background.default};
box-shadow: 1px 2px 8px rgba(139, 143, 173, 0.5);
}
@@ -432,6 +425,7 @@ const StyledPopover = styled(Popover)`
const BorderPickerDialog = styled("div")`
background: ${({ theme }): string => theme.palette.background.default};
padding: 4px;
display: flex;
flex-direction: column;
`;
@@ -450,8 +444,10 @@ const Button = styled("button")<TypeButtonProperties>(
alignItems: "center",
justifyContent: "center",
// fontSize: "26px",
border: `0px solid ${theme.palette.common.white}`,
border: "0px solid #fff",
borderRadius: "4px",
marginRight: "5px",
transition: "all 0.2s",
cursor: "pointer",
padding: "0px",
};
@@ -464,15 +460,13 @@ const Button = styled("button")<TypeButtonProperties>(
}
return {
...result,
borderTop: $underlinedColor
? `3px solid ${theme.palette.common.white}`
: "none",
borderTop: $underlinedColor ? "3px solid #FFF" : "none",
borderBottom: $underlinedColor ? `3px solid ${$underlinedColor}` : "none",
color: `${theme.palette.grey["900"]}`,
color: "#21243A",
backgroundColor: $pressed ? theme.palette.grey["200"] : "inherit",
"&:hover": {
outline: `1px solid ${theme.palette.grey["200"]}`,
borderTopColor: theme.palette.grey["200"],
backgroundColor: "#F1F2F8",
borderTopColor: "#F1F2F8",
},
svg: {
width: "16px",

View File

@@ -45,8 +45,8 @@ const ColorPicker = (properties: ColorPickerProps) => {
"#3BB68A",
"#8CB354",
"#F8CD3C",
"#F2994A",
"#EC5753",
"#A23C52",
"#D03627",
"#523E93",
"#3358B7",
@@ -71,7 +71,6 @@ const ColorPicker = (properties: ColorPickerProps) => {
setColor(newColor);
}}
/>
<HorizontalDivider />
<ColorPickerInput>
<HexWrapper>
<HexLabel>{"Hex"}</HexLabel>
@@ -132,8 +131,6 @@ const ColorPicker = (properties: ColorPickerProps) => {
const RecentLabel = styled.div`
font-family: "Inter";
font-size: 12px;
font-family: Inter;
margin: 8px 8px 0px 8px;
color: ${theme.palette.text.secondary};
`;
@@ -141,17 +138,14 @@ const ColorList = styled.div`
display: flex;
flex-wrap: wrap;
flex-direction: row;
margin: 8px;
justify-content: flex-start;
gap: 4.7px;
`;
const Button = styled.button<{ $color: string }>`
width: 16px;
height: 16px;
width: 20px;
height: 20px;
${({ $color }): string => {
if ($color.toUpperCase() === "#FFFFFF") {
return `border: 1px solid ${theme.palette.grey["300"]};`;
return `border: 1px solid ${theme.palette.grey["600"]};`;
}
return `border: 1px solid ${$color};`;
}}
@@ -159,19 +153,17 @@ const Button = styled.button<{ $color: string }>`
return $color;
}};
box-sizing: border-box;
margin-top: 0px;
border-radius: 4px;
&:hover {
cursor: pointer;
outline: 1px solid ${theme.palette.grey["300"]};
outline-offset: 1px;
}
margin-top: 10px;
margin-right: 10px;
border-radius: 2px;
`;
const HorizontalDivider = styled.div`
height: 0px;
width: 100%;
border-top: 1px solid ${theme.palette.grey["200"]};
border-top: 1px solid ${theme.palette.grey["400"]};
margin-top: 15px;
margin-bottom: 5px;
`;
// const StyledPopover = styled(Popover)`
@@ -191,7 +183,7 @@ const HorizontalDivider = styled.div`
const ColorPickerDialog = styled.div`
background: ${theme.palette.background.default};
width: ${colorPickerWidth}px;
padding: 0px;
padding: 15px;
display: flex;
flex-direction: column;
@@ -201,11 +193,11 @@ const ColorPickerDialog = styled.div`
}
& .react-colorful__saturation {
border-bottom: none;
border-radius: 0px;
border-radius: 5px;
}
& .react-colorful__hue {
height: 8px;
margin: 8px;
height: 20px;
margin-top: 15px;
border-radius: 5px;
}
& .react-colorful__saturation-pointer {
@@ -214,22 +206,19 @@ const ColorPickerDialog = styled.div`
}
& .react-colorful__hue-pointer {
width: 7px;
border-radius: 8px;
height: 16px;
width: 16px;
border-bottom: 1px solid #eee;
border-radius: 3px;
}
`;
const HashLabel = styled.div`
margin: auto 0px auto 10px;
font-size: 13px;
color: #333;
color: #7d8ec2;
font-family: ${theme.typography.button.fontFamily};
`;
const HexLabel = styled.div`
margin: auto 0px;
margin: auto 10px auto 0px;
font-size: 12px;
display: inline-flex;
font-family: ${theme.typography.button.fontFamily};
@@ -238,22 +227,15 @@ const HexLabel = styled.div`
const HexColorInputBox = styled.div`
display: inline-flex;
flex-grow: 1;
margin-right: 10px;
width: 140px;
height: 28px;
border: 1px solid ${theme.palette.grey["300"]};
border: 1px solid ${theme.palette.grey["600"]};
border-radius: 5px;
&:hover {
border: 1px solid ${theme.palette.grey["600"]};
}
&:focus-within {
outline: 2px solid ${theme.palette.secondary.main};
outline-offset: 1px;
}
`;
const HexWrapper = styled.div`
display: flex;
gap: 8px;
flex-grow: 1;
& input {
min-width: 0px;
@@ -277,7 +259,7 @@ const Swatch = styled.div<{ $color: string }>`
display: inline-flex;
${({ $color }): string => {
if ($color.toUpperCase() === "#FFFFFF") {
return `border: 1px solid ${theme.palette.grey["300"]};`;
return `border: 1px solid ${theme.palette.grey["600"]};`;
}
return `border: 1px solid ${$color};`;
}}
@@ -291,8 +273,7 @@ const ColorPickerInput = styled.div`
display: flex;
flex-direction: row;
align-items: center;
margin: 8px;
gap: 8px;
margin-top: 15px;
`;
export default ColorPicker;

View File

@@ -1,3 +1,3 @@
export const TOOLBAR_HEIGHT = 48;
export const FORMULA_BAR_HEIGHT = 40;
export const NAVIGATION_HEIGHT = 40;
export const TOOLBAR_HEIGH = 48;
export const FORMULA_BAR_HEIGH = 40;
export const NAVIGATION_HEIGH = 40;

View File

@@ -7,16 +7,6 @@ import {
} from "@ironcalc/wasm";
import type { ActiveRange } from "../workbookState";
function sliceString(
text: string,
startScalar: number,
endScalar: number,
): string {
const scalarValues = Array.from(text);
const sliced = scalarValues.slice(startScalar, endScalar);
return sliced.join("");
}
export function tokenIsReferenceType(token: TokenType): token is Reference {
return typeof token === "object" && "Reference" in token;
}
@@ -137,7 +127,7 @@ function getFormulaHTML(
}
html.push(
<span key={index} style={{ color }}>
{sliceString(formula, start, end)}
{formula.slice(start, end)}
</span>,
);
activeRanges.push({
@@ -172,7 +162,7 @@ function getFormulaHTML(
}
html.push(
<span key={index} style={{ color }}>
{sliceString(formula, start, end)}
{formula.slice(start, end)}
</span>,
);
colorCount += 1;
@@ -186,7 +176,7 @@ function getFormulaHTML(
color,
});
} else {
html.push(<span key={index}>{sliceString(formula, start, end)}</span>);
html.push(<span key={index}>{formula.slice(start, end)}</span>);
}
}
html = [<span key="equals">=</span>].concat(html);

View File

@@ -34,18 +34,11 @@ const FormatMenu = (properties: FormatMenuProps) => {
>
{properties.children}
</ChildrenWrapper>
<StyledMenu
<Menu
open={isMenuOpen}
onClose={(): void => setMenuOpen(false)}
anchorEl={anchorElement.current}
anchorOrigin={{
vertical: "bottom",
horizontal: "left",
}}
transformOrigin={{
vertical: "top",
horizontal: "left",
}}
anchorOrigin={properties.anchorOrigin}
>
<MenuItemWrapper onClick={(): void => onSelect(NumberFormats.AUTO)}>
<MenuItemText>{t("toolbar.format_menu.auto")}</MenuItemText>
@@ -114,7 +107,7 @@ const FormatMenu = (properties: FormatMenuProps) => {
<MenuItemWrapper onClick={(): void => setPickerOpen(true)}>
<MenuItemText>{t("toolbar.format_menu.custom")}</MenuItemText>
</MenuItemWrapper>
</StyledMenu>
</Menu>
<FormatPicker
numFmt={properties.numFmt}
onChange={onSelect}
@@ -126,40 +119,18 @@ const FormatMenu = (properties: FormatMenuProps) => {
);
};
const StyledMenu = styled(Menu)`
& .MuiPaper-root {
border-radius: 8px;
padding: 4px 0px;
margin-left: -4px; // Starting with a small offset
}
& .MuiList-root {
padding: 0;
}
`;
const MenuItemWrapper = styled(MenuItem)`
display: flex;
justify-content: space-between;
font-size: 12px;
width: calc(100% - 8px);
min-width: 172px;
margin: 0px 4px;
border-radius: 4px;
padding: 8px;
height: 32px;
width: 100%;
`;
const ChildrenWrapper = styled("div")`
display: flex;
`;
const MenuDivider = styled("div")`
width: 100%;
margin: auto;
margin-top: 4px;
margin-bottom: 4px;
border-top: 1px solid #eeeeee;
`;
const MenuDivider = styled("div")``;
const MenuItemText = styled("div")`
color: #000;

View File

@@ -1,9 +1,13 @@
import styled from "@emotion/styled";
import { Dialog, TextField } from "@mui/material";
import { Check, X } from "lucide-react";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
TextField,
} from "@mui/material";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { theme } from "../theme";
type FormatPickerProps = {
className?: string;
@@ -18,33 +22,17 @@ const FormatPicker = (properties: FormatPickerProps) => {
const { t } = useTranslation();
const [formatCode, setFormatCode] = useState(properties.numFmt);
const handleClose = () => {
properties.onClose();
};
const onSubmit = (format_code: string): void => {
properties.onChange(format_code);
properties.onClose();
};
return (
<Dialog
open={properties.open}
onClose={properties.onClose}
PaperProps={{
style: { minWidth: "280px" },
}}
>
<StyledDialogTitle>
{t("num_fmt.title")}
<Cross onClick={handleClose} title={t("num_fmt.close")}>
<X />
</Cross>
</StyledDialogTitle>
<StyledDialogContent>
<StyledTextField
autoFocus
<Dialog open={properties.open} onClose={properties.onClose}>
<DialogTitle>{t("num_fmt.title")}</DialogTitle>
<DialogContent dividers>
<TextField
defaultValue={properties.numFmt}
label={t("num_fmt.label")}
name="format_code"
onChange={(event) => setFormatCode(event.target.value)}
onKeyDown={(event) => {
@@ -52,99 +40,15 @@ const FormatPicker = (properties: FormatPickerProps) => {
}}
spellCheck="false"
onClick={(event) => event.stopPropagation()}
onFocus={(event) => event.target.select()}
/>
</StyledDialogContent>
<DialogFooter>
<StyledButton onClick={() => onSubmit(formatCode)}>
<Check
style={{ width: "16px", height: "16px", marginRight: "8px" }}
/>
</DialogContent>
<DialogActions>
<Button onClick={() => onSubmit(formatCode)}>
{t("num_fmt.save")}
</StyledButton>
</DialogFooter>
</Button>
</DialogActions>
</Dialog>
);
};
const StyledDialogTitle = styled("div")`
display: flex;
align-items: center;
height: 44px;
font-size: 14px;
font-weight: 500;
font-family: Inter;
padding: 0px 12px;
justify-content: space-between;
border-bottom: 1px solid ${theme.palette.grey["300"]};
`;
const Cross = styled("div")`
&:hover {
background-color: ${theme.palette.grey["50"]};
}
display: flex;
border-radius: 4px;
height: 24px;
width: 24px;
cursor: pointer;
align-items: center;
justify-content: center;
svg {
width: 16px;
height: 16px;
stroke-width: 1.5;
}
`;
const StyledDialogContent = styled("div")`
font-size: 12px;
margin: 12px;
`;
const StyledTextField = styled(TextField)`
width: 100%;
min-width: 320px;
border-radius: 4px;
overflow: hidden;
& .MuiInputBase-input {
font-size: 14px;
padding: 10px;
border: 1px solid ${theme.palette.grey["300"]};
border-radius: 4px;
color: ${theme.palette.common.black};
background-color: ${theme.palette.common.white};
}
&:hover .MuiInputBase-input {
border: 1px solid ${theme.palette.grey["500"]};
}
`;
const DialogFooter = styled("div")`
color: #757575;
display: flex;
align-items: center;
border-top: 1px solid ${theme.palette.grey["300"]};
font-family: Inter;
justify-content: flex-end;
padding: 12px;
`;
const StyledButton = styled("div")`
cursor: pointer;
color: #ffffff;
background: #f2994a;
padding: 0px 10px;
height: 36px;
line-height: 36px;
border-radius: 4px;
display: flex;
align-items: center;
font-family: "Inter";
font-size: 14px;
&:hover {
background: #d68742;
}
`;
export default FormatPicker;

View File

@@ -5,7 +5,7 @@ import {
COLUMN_WIDTH_SCALE,
ROW_HEIGH_SCALE,
} from "./WorksheetCanvas/constants";
import { FORMULA_BAR_HEIGHT } from "./constants";
import { FORMULA_BAR_HEIGH } from "./constants";
import Editor from "./editor/editor";
import type { WorkbookState } from "./workbookState";
@@ -122,7 +122,7 @@ const Container = styled("div")`
align-items: center;
background: ${(properties): string =>
properties.theme.palette.background.default};
height: ${FORMULA_BAR_HEIGHT}px;
height: ${FORMULA_BAR_HEIGH}px;
`;
const AddressContainer = styled("div")`

View File

@@ -0,0 +1,2 @@
export { default } from "./navigation";
export type { NavigationProps } from "./navigation";

View File

@@ -1,16 +1,66 @@
import { styled } from "@mui/material";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
TextField,
styled,
} from "@mui/material";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import { Check } from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import type { SheetOptions } from "./types";
function isWhiteColor(color: string): boolean {
return ["#FFF", "#FFFFFF"].includes(color);
}
interface SheetRenameDialogProps {
isOpen: boolean;
close: () => void;
onNameChanged: (name: string) => void;
defaultName: string;
}
export const SheetRenameDialog = (properties: SheetRenameDialogProps) => {
const { t } = useTranslation();
const [name, setName] = useState(properties.defaultName);
return (
<Dialog open={properties.isOpen} onClose={properties.close}>
<DialogTitle>{t("sheet_rename.title")}</DialogTitle>
<DialogContent dividers>
<TextField
defaultValue={properties.defaultName}
label={t("sheet_rename.label")}
onClick={(event) => event.stopPropagation()}
onKeyDown={(event) => {
event.stopPropagation();
}}
onChange={(event) => {
setName(event.target.value);
}}
spellCheck="false"
/>
</DialogContent>
<DialogActions>
<Button
onClick={() => {
properties.onNameChanged(name);
}}
>
{t("sheet_rename.rename")}
</Button>
</DialogActions>
</Dialog>
);
};
interface SheetListMenuProps {
open: boolean;
onClose: () => void;
isOpen: boolean;
close: () => void;
anchorEl: HTMLButtonElement | null;
onSheetSelected: (index: number) => void;
sheetOptionsList: SheetOptions[];
@@ -19,8 +69,8 @@ interface SheetListMenuProps {
const SheetListMenu = (properties: SheetListMenuProps) => {
const {
open,
onClose,
isOpen,
close,
anchorEl,
onSheetSelected,
sheetOptionsList,
@@ -31,8 +81,8 @@ const SheetListMenu = (properties: SheetListMenuProps) => {
return (
<StyledMenu
open={open}
onClose={onClose}
open={isOpen}
onClose={close}
anchorEl={anchorEl}
anchorOrigin={{
vertical: "top",
@@ -59,10 +109,7 @@ const SheetListMenu = (properties: SheetListMenuProps) => {
)}
{hasColors && <ItemColor style={{ backgroundColor: tab.color }} />}
<ItemName
style={{
fontWeight: index === selectedIndex ? "bold" : "normal",
color: tab.state === "visible" ? "#333" : "#888",
}}
style={{ fontWeight: index === selectedIndex ? "bold" : "normal" }}
>
{tab.name}
</ItemName>

View File

@@ -2,15 +2,14 @@ import { styled } from "@mui/material";
import { Menu, Plus } from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { theme } from "../../theme";
import { NAVIGATION_HEIGHT } from "../constants";
import { NAVIGATION_HEIGH } from "../constants";
import { StyledButton } from "../toolbar";
import type { WorkbookState } from "../workbookState";
import SheetListMenu from "./SheetListMenu";
import SheetTab from "./SheetTab";
import SheetListMenu from "./menus";
import Sheet from "./sheet";
import type { SheetOptions } from "./types";
export interface SheetTabBarProps {
export interface NavigationProps {
sheets: SheetOptions[];
selectedIndex: number;
workbookState: WorkbookState;
@@ -19,10 +18,9 @@ export interface SheetTabBarProps {
onSheetColorChanged: (hex: string) => void;
onSheetRenamed: (name: string) => void;
onSheetDeleted: () => void;
onHideSheet: () => void;
}
function SheetTabBar(props: SheetTabBarProps) {
function Navigation(props: NavigationProps) {
const { t } = useTranslation();
const { workbookState, onSheetSelected, sheets, selectedIndex } = props;
const [anchorEl, setAnchorEl] = useState<null | HTMLButtonElement>(null);
@@ -34,57 +32,40 @@ function SheetTabBar(props: SheetTabBarProps) {
setAnchorEl(null);
};
const nonHidenSheets = sheets
.map((s, index) => {
return {
state: s.state,
index,
name: s.name,
color: s.color,
sheetId: s.sheetId,
};
})
.filter((s) => s.state === "visible");
return (
<Container>
<LeftButtonsContainer>
<StyledButton
title={t("navigation.add_sheet")}
$pressed={false}
onClick={props.onAddBlankSheet}
>
<Plus />
</StyledButton>
<StyledButton
onClick={handleClick}
title={t("navigation.sheet_list")}
$pressed={false}
>
<Menu />
</StyledButton>
</LeftButtonsContainer>
<VerticalDivider />
<StyledButton
title={t("navigation.add_sheet")}
$pressed={false}
onClick={props.onAddBlankSheet}
>
<Plus />
</StyledButton>
<StyledButton
onClick={handleClick}
title={t("navigation.sheet_list")}
$pressed={false}
>
<Menu />
</StyledButton>
<Sheets>
<SheetInner>
{nonHidenSheets.map((tab) => (
<SheetTab
{sheets.map((tab, index) => (
<Sheet
key={tab.sheetId}
name={tab.name}
color={tab.color}
selected={tab.index === selectedIndex}
onSelected={() => onSheetSelected(tab.index)}
selected={index === selectedIndex}
onSelected={() => onSheetSelected(index)}
onColorChanged={(hex: string): void => {
props.onSheetColorChanged(hex);
}}
onRenamed={(name: string): void => {
props.onSheetRenamed(name);
}}
canDelete={nonHidenSheets.length > 1}
onDeleted={(): void => {
props.onSheetDeleted();
}}
onHideSheet={props.onHideSheet}
workbookState={workbookState}
/>
))}
@@ -95,8 +76,8 @@ function SheetTabBar(props: SheetTabBarProps) {
</Advert>
<SheetListMenu
anchorEl={anchorEl}
open={open}
onClose={handleClose}
isOpen={open}
close={handleClose}
sheetOptionsList={sheets}
onSheetSelected={(index) => {
onSheetSelected(index);
@@ -110,29 +91,22 @@ function SheetTabBar(props: SheetTabBarProps) {
// Note I have to specify the font-family in every component that can be considered stand-alone
const Container = styled("div")`
display: flex;
flex-direction: row;
position: absolute;
bottom: 0px;
left: 0px;
right: 0px;
display: flex;
height: ${NAVIGATION_HEIGHT}px;
height: ${NAVIGATION_HEIGH}px;
align-items: center;
padding: 0px 12px;
padding-left: 12px;
font-family: Inter;
background-color: ${theme.palette.common.white};
border-top: 1px solid ${theme.palette.grey["300"]};
background-color: #fff;
border-top: 1px solid #E0E0E0;
`;
const Sheets = styled("div")`
flex-grow: 2;
overflow: hidden;
overflow-x: auto;
scrollbar-width: none;
padding-left: 12px;
display: flex;
flex-direction: row;
`;
const SheetInner = styled("div")`
@@ -140,35 +114,10 @@ const SheetInner = styled("div")`
`;
const Advert = styled("a")`
display: flex;
align-items: center;
color: ${theme.palette.primary.main};
padding: 0px 0px 0px 12px;
color: #f2994a;
margin-right: 12px;
font-size: 12px;
text-decoration: none;
border-left: 1px solid ${theme.palette.grey["300"]};
transition: color 0.2s ease-in-out;
&:hover {
text-decoration: underline;
}
@media (max-width: 769px) {
height: 100%;
}
`;
const LeftButtonsContainer = styled("div")`
display: flex;
flex-direction: row;
gap: 4px;
padding-right: 12px;
`;
const VerticalDivider = styled("div")`
height: 100%;
width: 0px;
@media (max-width: 769px) {
border-right: 1px solid ${theme.palette.grey["200"]};
}
`;
export default SheetTabBar;
export default Navigation;

View File

@@ -1,27 +1,23 @@
import { Button, Menu, MenuItem, styled } from "@mui/material";
import type { MenuItemProps } from "@mui/material";
import { ChevronDown } from "lucide-react";
import { useRef, useState } from "react";
import { theme } from "../../theme";
import ColorPicker from "../colorPicker";
import { isInReferenceMode } from "../editor/util";
import type { WorkbookState } from "../workbookState";
import SheetRenameDialog from "./SheetRenameDialog";
import { SheetRenameDialog } from "./menus";
interface SheetTabProps {
interface SheetProps {
name: string;
color: string;
selected: boolean;
onSelected: () => void;
onColorChanged: (hex: string) => void;
onRenamed: (name: string) => void;
canDelete: boolean;
onDeleted: () => void;
onHideSheet: () => void;
workbookState: WorkbookState;
}
function SheetTab(props: SheetTabProps) {
function Sheet(props: SheetProps) {
const { name, color, selected, workbookState, onSelected } = props;
const [anchorEl, setAnchorEl] = useState<null | HTMLButtonElement>(null);
const [colorPickerOpen, setColorPickerOpen] = useState(false);
@@ -42,9 +38,8 @@ function SheetTab(props: SheetTabProps) {
};
return (
<>
<TabWrapper
$color={color}
$selected={selected}
<Wrapper
style={{ borderBottomColor: color, fontWeight: selected ? 600 : 400 }}
onClick={(event) => {
onSelected();
event.stopPropagation();
@@ -60,11 +55,11 @@ function SheetTab(props: SheetTabProps) {
}}
ref={colorButton}
>
<Name onDoubleClick={handleOpenRenameDialog}>{name}</Name>
<Name>{name}</Name>
<StyledButton onClick={handleOpen}>
<ChevronDown />
</StyledButton>
</TabWrapper>
</Wrapper>
<StyledMenu
anchorEl={anchorEl}
open={open}
@@ -95,27 +90,18 @@ function SheetTab(props: SheetTabProps) {
Change Color
</StyledMenuItem>
<StyledMenuItem
disabled={!props.canDelete}
onClick={() => {
props.onDeleted();
handleClose();
}}
>
{" "}
Delete
</StyledMenuItem>
<StyledMenuItem
disabled={!props.canDelete}
onClick={() => {
props.onHideSheet();
handleClose();
}}
>
Hide sheet
</StyledMenuItem>
</StyledMenu>
<SheetRenameDialog
open={renameDialogOpen}
onClose={handleCloseRenameDialog}
isOpen={renameDialogOpen}
close={handleCloseRenameDialog}
defaultName={name}
onNameChanged={(newName) => {
props.onRenamed(newName);
@@ -138,42 +124,10 @@ function SheetTab(props: SheetTabProps) {
);
}
const StyledMenu = styled(Menu)`
& .MuiPaper-root {
border-radius: 8px;
padding: 4px 0px;
margin-left: -4px;
}
& .MuiList-root {
padding: 0;
}
`;
const StyledMenu = styled(Menu)``;
const StyledMenuItem = styled(MenuItem)<MenuItemProps>(() => ({
display: "flex",
justifyContent: "space-between",
fontSize: "12px",
width: "calc(100% - 8px)",
margin: "0px 4px",
borderRadius: "4px",
padding: "8px",
height: "32px",
"&:disabled": {
color: "#BDBDBD",
},
}));
const TabWrapper = styled("div")<{ $color: string; $selected: boolean }>`
display: flex;
margin-right: 12px;
border-bottom: 3px solid ${(props) => props.$color};
line-height: 37px;
padding: 0px 4px;
align-items: center;
cursor: pointer;
font-weight: ${(props) => (props.$selected ? 600 : 400)};
background-color: ${(props) =>
props.$selected ? `${theme.palette.grey[50]}80` : "transparent"};
const StyledMenuItem = styled(MenuItem)`
font-size: 12px;
`;
const StyledButton = styled(Button)`
@@ -183,27 +137,26 @@ const StyledButton = styled(Button)`
padding: 0px;
color: inherit;
font-weight: inherit;
&:hover {
background-color: transparent;
}
&:active {
background-color: transparent;
}
svg {
width: 15px;
height: 15px;
transition: transform 0.2s;
}
&:hover svg {
transform: translateY(2px);
}
`;
const Wrapper = styled("div")`
display: flex;
margin-left: 20px;
border-bottom: 3px solid;
border-top: 3px solid white;
line-height: 34px;
align-items: center;
cursor: pointer;
`;
const Name = styled("div")`
font-size: 12px;
margin-right: 5px;
text-wrap: nowrap;
user-select: none;
`;
export default SheetTab;
export default Sheet;

View File

@@ -2,5 +2,4 @@ export interface SheetOptions {
name: string;
color: string;
sheetId: number;
state: string;
}

View File

@@ -1,7 +1,6 @@
import type {
BorderOptions,
HorizontalAlignment,
Model,
VerticalAlignment,
} from "@ironcalc/wasm";
import { styled } from "@mui/material/styles";
@@ -19,11 +18,10 @@ import {
Grid2x2X,
Italic,
PaintBucket,
PaintRoller,
Paintbrush2,
Percent,
Redo2,
Strikethrough,
Tags,
Type,
Underline,
Undo2,
@@ -36,11 +34,9 @@ import {
DecimalPlacesIncreaseIcon,
} from "../icons";
import { theme } from "../theme";
import NameManagerDialog from "./NameManagerDialog";
import NameManagerDialog from "./NameManagerDialog";
import BorderPicker from "./borderPicker";
import ColorPicker from "./colorPicker";
import { TOOLBAR_HEIGHT } from "./constants";
import { TOOLBAR_HEIGH } from "./constants";
import FormatMenu from "./formatMenu";
import {
NumberFormats,
@@ -76,14 +72,12 @@ type ToolbarProperties = {
numFmt: string;
showGridLines: boolean;
onToggleShowGridLines: (show: boolean) => void;
model: Model;
};
function Toolbar(properties: ToolbarProperties) {
const [fontColorPickerOpen, setFontColorPickerOpen] = useState(false);
const [fillColorPickerOpen, setFillColorPickerOpen] = useState(false);
const [borderPickerOpen, setBorderPickerOpen] = useState(false);
const [nameManagerDialogOpen, setNameManagerDialogOpen] = useState(false);
const fontColorButton = useRef(null);
const fillColorButton = useRef(null);
@@ -120,7 +114,7 @@ function Toolbar(properties: ToolbarProperties) {
onClick={properties.onCopyStyles}
title={t("toolbar.copy_styles")}
>
<PaintRoller />
<Paintbrush2 />
</StyledButton>
<Divider />
<StyledButton
@@ -189,7 +183,8 @@ function Toolbar(properties: ToolbarProperties) {
title={t("toolbar.format_number")}
sx={{
width: "40px", // Keep in sync with anchorOrigin in FormatMenu above
padding: "0px 4px",
fontSize: "13px",
fontWeight: 400,
}}
>
{"123"}
@@ -256,16 +251,6 @@ function Toolbar(properties: ToolbarProperties) {
>
<PaintBucket />
</StyledButton>
<StyledButton
type="button"
$pressed={false}
onClick={() => setBorderPickerOpen(true)}
ref={borderButton}
disabled={!canEdit}
title={t("toolbar.borders.title")}
>
<Grid2X2 />
</StyledButton>
<Divider />
<StyledButton
type="button"
@@ -333,7 +318,17 @@ function Toolbar(properties: ToolbarProperties) {
>
<ArrowDownToLine />
</StyledButton>
<Divider />
<StyledButton
type="button"
$pressed={false}
onClick={() => setBorderPickerOpen(true)}
ref={borderButton}
disabled={!canEdit}
title={t("toolbar.borders.title")}
>
<Grid2X2 />
</StyledButton>
<Divider />
<StyledButton
type="button"
@@ -346,18 +341,6 @@ function Toolbar(properties: ToolbarProperties) {
>
{properties.showGridLines ? <Grid2x2Check /> : <Grid2x2X />}
</StyledButton>
<Divider />
<StyledButton
type="button"
$pressed={false}
onClick={() => {
setNameManagerDialogOpen(true);
}}
disabled={!canEdit}
title={t("toolbar.name_manager")}
>
<Tags />
</StyledButton>
<ColorPicker
color={properties.fontColor}
@@ -393,13 +376,6 @@ function Toolbar(properties: ToolbarProperties) {
anchorEl={borderButton}
open={borderPickerOpen}
/>
<NameManagerDialog
open={nameManagerDialogOpen}
onClose={() => {
setNameManagerDialogOpen(false);
}}
model={properties.model}
/>
</ToolbarContainer>
);
}
@@ -409,15 +385,13 @@ const ToolbarContainer = styled("div")`
flex-shrink: 0;
align-items: center;
background: ${({ theme }) => theme.palette.background.paper};
height: ${TOOLBAR_HEIGHT}px;
line-height: ${TOOLBAR_HEIGHT}px;
height: ${TOOLBAR_HEIGH}px;
line-height: ${TOOLBAR_HEIGH}px;
border-bottom: 1px solid ${({ theme }) => theme.palette.grey["300"]};
font-family: Inter;
border-radius: 4px 4px 0px 0px;
overflow-x: auto;
padding: 0px 12px;
gap: 4px;
scrollbar-width: none;
padding-left: 11px;
`;
type TypeButtonProperties = { $pressed: boolean; $underlinedColor?: string };
@@ -425,16 +399,15 @@ export const StyledButton = styled("button")<TypeButtonProperties>(
({ disabled, $pressed, $underlinedColor }) => {
const result = {
width: "24px",
minWidth: "24px",
height: "24px",
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
fontSize: "12px",
border: `0px solid ${theme.palette.common.white}`,
borderRadius: "4px",
fontSize: "26px",
border: "0px solid #fff",
borderRadius: "2px",
marginRight: "5px",
transition: "all 0.2s",
outline: `1px solid ${theme.palette.common.white}`,
cursor: "pointer",
backgroundColor: "white",
padding: "0px",
@@ -446,28 +419,19 @@ export const StyledButton = styled("button")<TypeButtonProperties>(
if (disabled) {
return {
...result,
color: theme.palette.grey["400"],
color: theme.palette.grey["600"],
cursor: "default",
};
}
return {
...result,
borderTop: $underlinedColor
? `3px solid ${theme.palette.common.white}`
: "none",
borderTop: $underlinedColor ? "3px solid #FFF" : "none",
borderBottom: $underlinedColor ? `3px solid ${$underlinedColor}` : "none",
color: theme.palette.grey["900"],
backgroundColor: $pressed
? theme.palette.grey["300"]
: theme.palette.common.white,
color: "#21243A",
backgroundColor: $pressed ? "#EEE" : "#FFF",
"&:hover": {
transition: "all 0.2s",
outline: `1px solid ${theme.palette.grey["200"]}`,
borderTopColor: theme.palette.common.white,
},
"&:active": {
backgroundColor: theme.palette.grey["300"],
outline: `1px solid ${theme.palette.grey["300"]}`,
backgroundColor: "#F1F2F8",
borderTopColor: "#F1F2F8",
},
};
},
@@ -475,9 +439,10 @@ export const StyledButton = styled("button")<TypeButtonProperties>(
const Divider = styled("div")({
width: "0px",
height: "12px",
borderLeft: `1px solid ${theme.palette.grey["300"]}`,
margin: "0px 12px",
height: "10px",
borderLeft: "1px solid #E0E0E0",
marginLeft: "5px",
marginRight: "10px",
});
export default Toolbar;

View File

@@ -1,10 +1,6 @@
import type { Area, Cell } from "./types";
import {
type SelectedView,
type WorksheetProperties,
columnNameFromNumber,
} from "@ironcalc/wasm";
import { columnNameFromNumber } from "@ironcalc/wasm";
/**
* Returns true if the keypress should start editing
@@ -61,24 +57,7 @@ export function rangeToStr(
if (rowStart === rowEnd && columnStart === columnEnd) {
return `${sheetName}${columnNameFromNumber(columnStart)}${rowStart}`;
}
return `${sheetName}${columnNameFromNumber(columnStart)}${rowStart}:${columnNameFromNumber(
columnEnd,
)}${rowEnd}`;
}
export function getFullRangeToString(
selectedView: SelectedView,
worksheets: WorksheetProperties[], // solo pasar names
): string {
// order of values is confusing compared to rangeToStr range type, needs refactoring for consistency
const [rowStart, columnStart, rowEnd, columnEnd] = selectedView.range;
const sheetNames = worksheets.map((s) => s.name);
const sheetName = `${sheetNames[selectedView.sheet]}!`;
if (rowStart === rowEnd && columnStart === columnEnd) {
return `${sheetName}${columnNameFromNumber(columnStart)}${rowStart}`;
}
return `${sheetName}${columnNameFromNumber(columnStart)}${rowStart}:${columnNameFromNumber(
columnEnd,
)}${rowEnd}`;
return `${sheetName}${columnNameFromNumber(
columnStart,
)}${rowStart}:${columnNameFromNumber(columnEnd)}${rowEnd}`;
}

View File

@@ -5,10 +5,7 @@ import type {
WorksheetProperties,
} from "@ironcalc/wasm";
import { styled } from "@mui/material/styles";
import { PaintRoller } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import ReactDOMServer from "react-dom/server";
import SheetTabBar from "./SheetTabBar/SheetTabBar";
import {
COLUMN_WIDTH_SCALE,
LAST_COLUMN,
@@ -19,6 +16,7 @@ import {
getNewClipboardId,
} from "./clipboard";
import FormulaBar from "./formulabar";
import Navigation from "./navigation/navigation";
import Toolbar from "./toolbar";
import useKeyboardNavigation from "./useKeyboardNavigation";
import { type NavigationKey, getCellAddress } from "./util";
@@ -34,8 +32,8 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
const setRedrawId = useState(0)[1];
const info = model
.getWorksheetsProperties()
.map(({ name, color, sheet_id, state }: WorksheetProperties) => {
return { name, color: color ? color : "#FFF", sheetId: sheet_id, state };
.map(({ name, color, sheet_id }: WorksheetProperties) => {
return { name, color: color ? color : "#FFF", sheetId: sheet_id };
});
const focusWorkbook = useCallback(() => {
if (rootRef.current) {
@@ -115,10 +113,6 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
updateRangeStyle("num_fmt", numberFmt);
};
const onNamedRangesUpdate = () => {
// update named ranges in model
};
const onCopyStyles = () => {
const {
sheet,
@@ -142,15 +136,7 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
const el = rootRef.current?.getElementsByClassName("sheet-container")[0];
if (el) {
(el as HTMLElement).style.cursor =
`url('data:image/svg+xml;utf8,${encodeURIComponent(
ReactDOMServer.renderToString(
<PaintRoller
width={24}
height={24}
style={{ transform: "rotate(-8deg)" }}
/>,
),
)}'), auto`;
`url('data:image/svg+xml;utf8,<svg data-v-56bd7dfc="" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-paintbrush-vertical"><path d="M10 2v2"></path><path d="M14 2v4"></path><path d="M17 2a1 1 0 0 1 1 1v9H6V3a1 1 0 0 1 1-1z"></path><path d="M6 12a1 1 0 0 0-1 1v1a2 2 0 0 0 2 2h2a1 1 0 0 1 1 1v2.9a2 2 0 1 0 4 0V17a1 1 0 0 1 1-1h2a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1"></path></svg>'), auto`;
}
};
@@ -404,12 +390,7 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
}
data.set(Number.parseInt(row, 10), rowMap);
}
model.pasteFromClipboard(
source.sheet,
source.area,
data,
source.type === "cut",
);
model.pasteFromClipboard(source.area, data, source.type === "cut");
setRedrawId((id) => id + 1);
} else if (mimeType === "text/plain") {
const {
@@ -435,7 +416,6 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
}}
onCopy={(event: React.ClipboardEvent) => {
const data = model.copyToClipboard();
const sheet = model.getSelectedSheet();
// '2024-10-18T14:07:37.599Z'
let clipboardId = sessionStorage.getItem(
@@ -463,7 +443,6 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
type: "copy",
area: data.range,
sheetData,
sheet,
clipboardId,
});
event.clipboardData.setData("text/plain", data.csv);
@@ -473,7 +452,6 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
}}
onCut={(event: React.ClipboardEvent) => {
const data = model.copyToClipboard();
const sheet = model.getSelectedSheet();
// '2024-10-18T14:07:37.599Z'
let clipboardId = sessionStorage.getItem(
@@ -501,7 +479,6 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
type: "cut",
area: data.range,
sheetData,
sheet,
clipboardId,
});
event.clipboardData.setData("text/plain", data.csv);
@@ -553,7 +530,7 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
);
setRedrawId((id) => id + 1);
}}
fillColor={style.fill.fg_color || "#FFFFFF"}
fillColor={style.fill.fg_color || "#FFF"}
fontColor={style.font.color}
bold={style.font.b}
underline={style.font.u}
@@ -573,7 +550,6 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
model.setShowGridLines(sheet, show);
setRedrawId((id) => id + 1);
}}
model={model}
/>
<FormulaBar
cellAddress={cellAddress()}
@@ -596,14 +572,11 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
}}
/>
<SheetTabBar
<Navigation
sheets={info}
selectedIndex={model.getSelectedSheet()}
workbookState={workbookState}
onSheetSelected={(sheet: number): void => {
if (info[sheet].state !== "visible") {
model.unhideSheet(sheet);
}
model.setSelectedSheet(sheet);
setRedrawId((value) => value + 1);
}}
@@ -634,11 +607,6 @@ const Workbook = (props: { model: Model; workbookState: WorkbookState }) => {
model.deleteSheet(selectedSheet);
setRedrawId((value) => value + 1);
}}
onHideSheet={(): void => {
const selectedSheet = model.getSelectedSheet();
model.hideSheet(selectedSheet);
setRedrawId((value) => value + 1);
}}
/>
</Container>
);

View File

@@ -9,9 +9,9 @@ import {
} from "./WorksheetCanvas/constants";
import WorksheetCanvas from "./WorksheetCanvas/worksheetCanvas";
import {
FORMULA_BAR_HEIGHT,
NAVIGATION_HEIGHT,
TOOLBAR_HEIGHT,
FORMULA_BAR_HEIGH,
NAVIGATION_HEIGH,
TOOLBAR_HEIGH,
} from "./constants";
import Editor from "./editor/editor";
import type { Cell } from "./types";
@@ -104,16 +104,10 @@ function Worksheet(props: {
editor: editor,
},
onColumnWidthChanges(sheet, column, width) {
if (width < 0) {
return;
}
model.setColumnWidth(sheet, column, width);
worksheetCanvas.current?.renderSheet();
},
onRowHeightChanges(sheet, row, height) {
if (height < 0) {
return;
}
model.setRowHeight(sheet, row, height);
worksheetCanvas.current?.renderSheet();
},
@@ -439,10 +433,10 @@ const SheetContainer = styled("div")`
const Wrapper = styled("div")({
position: "absolute",
overflow: "scroll",
top: TOOLBAR_HEIGHT + FORMULA_BAR_HEIGHT + 1,
top: TOOLBAR_HEIGH + FORMULA_BAR_HEIGH + 1,
left: 0,
right: 0,
bottom: NAVIGATION_HEIGHT + 1,
bottom: NAVIGATION_HEIGH + 1,
overscrollBehavior: "none",
});

View File

@@ -1,3 +1,7 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M3 8H2M14 8H13M7 8H5M11 8H9M14 4H2M2.01 12H2M4.01 12H4M6.01 12H6M8.01 12H8M10.01 12H10M12.01 12H12M14.01 12H14" stroke="#333333" stroke-linecap="round" stroke-linejoin="round"/>
<line x1="0" y1="2" x2="16" y2="2" stroke="#000"/>
<!-- Dashes and gaps of the same size -->
<line x1="0" y1="8" x2="16" y2="8" stroke-dasharray="2.28 2.28" stroke="#000"/>
<!-- Dashes and gaps of different sizes -->
<line x1="0" y1="14" x2="16" y2="14" stroke-dasharray="1 2" stroke="#000"/>
</svg>

Before

Width:  |  Height:  |  Size: 290 B

After

Width:  |  Height:  |  Size: 400 B

View File

@@ -1,93 +1,77 @@
{
"toolbar": {
"redo": "Redo",
"undo": "Undo",
"copy_styles": "Copy styles",
"euro": "Format as Euro",
"percentage": "Format as Percentage",
"bold": "Bold",
"italic": "Italic",
"underline": "Underline",
"strike_through": "Strikethrough",
"align_left": "Align left",
"align_right": "Align right",
"align_center": "Align center",
"format_number": "Format number",
"font_color": "Font color",
"fill_color": "Fill color",
"decimal_places_increase": "Increase decimal places",
"decimal_places_decrease": "Decrease decimal places",
"show_hide_grid_lines": "Show/hide grid lines",
"name_manager": "Name manager",
"name_manager": "Name manager",
"vertical_align_bottom": "Align bottom",
"vertical_align_middle": " Align middle",
"vertical_align_top": "Align top",
"format_menu": {
"auto": "Auto",
"number": "Number",
"percentage": "Percentage",
"currency_eur": "Euro (EUR)",
"currency_usd": "Dollar (USD)",
"currency_gbp": "British Pound (GBD)",
"date_short": "Short date",
"date_long": "Long date",
"custom": "Custom",
"number_example": "1,000.00",
"percentage_example": "10%",
"currency_eur_example": "",
"currency_usd_example": "$",
"currency_gbp_example": "£",
"date_short_example": "09/24/2024",
"date_long_example": "Tuesday, September 24, 2024"
},
"borders": {
"title": "Borders",
"all": "All borders",
"inner": "Inner borders",
"outer": "Outer borders",
"top": "Top borders",
"bottom": "Bottom borders",
"clear": "Clear borders",
"left": "Left borders",
"right": "Right borders",
"horizontal": "Horizontal borders",
"vertical": "Vertical borders",
"color": "Border color",
"style": "Border style"
}
},
"num_fmt": {
"title": "Custom number format",
"label": "Number format",
"close": "Close dialog",
"save": "Save"
},
"sheet_rename": {
"rename": "Save",
"label": "New name",
"title": "Rename Sheet",
"close": "Close dialog"
},
"formula_input": {
"update": "Update",
"label": "Formula",
"title": "Update formula"
},
"navigation": {
"add_sheet": "Add sheet",
"sheet_list": "Sheet list"
},
"name_manager_dialog": {
"help": "Learn more about Named Ranges",
"name": "Name",
"range": "Scope",
"scope": "Range"
},
"name_manager_dialog": {
"help": "Learn more about Named Ranges",
"name": "Name",
"range": "Scope",
"scope": "Range"
}
"toolbar": {
"redo": "Redo",
"undo": "Undo",
"copy_styles": "Copy styles",
"euro": "Format as Euro",
"percentage": "Format as Percentage",
"bold": "Bold",
"italic": "Italic",
"underline": "Underline",
"strike_through": "Strikethrough",
"align_left": "Align left",
"align_right": "Align right",
"align_center": "Align center",
"format_number": "Format number",
"font_color": "Font color",
"fill_color": "Fill color",
"decimal_places_increase": "Increase decimal places",
"decimal_places_decrease": "Decrease decimal places",
"show_hide_grid_lines": "Show/hide grid lines",
"vertical_align_bottom": "Align bottom",
"vertical_align_middle": " Align middle",
"vertical_align_top": "Align top",
"format_menu": {
"auto": "Auto",
"number": "Number",
"percentage": "Percentage",
"currency_eur": "Euro (EUR)",
"currency_usd": "Dollar (USD)",
"currency_gbp": "British Pound (GBD)",
"date_short": "Short date",
"date_long": "Long date",
"custom": "Custom",
"number_example": "1,000.00",
"percentage_example": "10%",
"currency_eur_example": "",
"currency_usd_example": "$",
"currency_gbp_example": "£",
"date_short_example": "09/24/2024",
"date_long_example": "Tuesday, September 24, 2024"
},
"borders": {
"title": "Borders",
"all": "All borders",
"inner": "Inner borders",
"outer": "Outer borders",
"top": "Top borders",
"bottom": "Bottom borders",
"clear": "Clear borders",
"left": "Left borders",
"right": "Right borders",
"horizontal": "Horizontal borders",
"vertical": "Vertical borders",
"color": "Border color",
"style": "Border style"
}
},
"num_fmt": {
"title": "Custom number format",
"label": "Number format",
"save": "Save"
},
"sheet_rename": {
"rename": "Save",
"label": "New name",
"title": "Rename Sheet"
},
"formula_input": {
"update": "Update",
"label": "Formula",
"title": "Update formula"
},
"navigation": {
"add_sheet": "Add sheet",
"sheet_list": "Sheet list"
}
}

View File

@@ -246,8 +246,18 @@ pub(crate) fn get_worksheet_xml(
}
let sheet_data = sheet_data_str.join("");
for merge_cell_ref in &worksheet.merge_cells {
merged_cells_str.push(format!("<mergeCell ref=\"{merge_cell_ref}\"/>"))
for merged_cells_ref in &worksheet.merged_cells_list {
let merged_cells_range_str_ref: String = match merged_cells_ref.get_merged_cells_str_ref() {
Ok(merged_cells_ref) => merged_cells_ref,
Err(err) => {
// ATTENTION : This should not happen. There should not be error while exporting
// already imported/created Mergedcells structure
// Currently, this function does not return any error. so logging the error and skipping this errored one
println!("{}", err);
continue;
}
};
merged_cells_str.push(format!("<mergeCell ref=\"{merged_cells_range_str_ref}\"/>"))
}
let merged_cells_count = merged_cells_str.len();

View File

@@ -10,7 +10,7 @@ use ironcalc_base::{
utils::{column_to_number, parse_reference_a1},
},
types::{
Cell, Col, Comment, DefinedName, Row, SheetData, SheetState, Table, Worksheet,
Cell, Col, Comment, DefinedName, MergedCells, Row, SheetData, SheetState, Table, Worksheet,
WorksheetView,
},
};
@@ -41,30 +41,6 @@ pub(crate) struct Relationship {
pub(crate) rel_type: String,
}
impl WorkbookXML {
fn get_defined_names_with_scope(&self) -> Vec<(String, Option<u32>)> {
let sheet_id_index: Vec<u32> = self.worksheets.iter().map(|s| s.sheet_id).collect();
let defined_names = self
.defined_names
.iter()
.map(|dn| {
let index = dn
.sheet_id
.and_then(|sheet_id| {
// returns an Option<usize>
sheet_id_index.iter().position(|&x| x == sheet_id)
})
// convert Option<usize> to Option<u32>
.map(|pos| pos as u32);
(dn.name.clone(), index)
})
.collect::<Vec<_>>();
defined_names
}
}
fn get_column_from_ref(s: &str) -> String {
let cs = s.chars();
let mut column = Vec::<char>::new();
@@ -172,12 +148,12 @@ fn load_columns(ws: Node) -> Result<Vec<Col>, XlsxError> {
Ok(cols)
}
fn load_merge_cells(ws: Node) -> Result<Vec<String>, XlsxError> {
fn load_merge_cells_nodes(ws: Node) -> Result<Vec<MergedCells>, XlsxError> {
// 18.3.1.55 Merge Cells
// <mergeCells count="1">
// <mergeCell ref="K7:L10"/>
// </mergeCells>
let mut merge_cells = Vec::new();
let mut merged_cells_list: Vec<MergedCells> = Vec::new();
let merge_cells_nodes = ws
.children()
.filter(|n| n.has_tag_name("mergeCells"))
@@ -185,10 +161,18 @@ fn load_merge_cells(ws: Node) -> Result<Vec<String>, XlsxError> {
if merge_cells_nodes.len() == 1 {
for merge_cell in merge_cells_nodes[0].children() {
let reference = get_attribute(&merge_cell, "ref")?.to_string();
merge_cells.push(reference);
match parse_range(&reference) {
Ok(parsed_merge_cell_range) => {
let merge_cell_node = MergedCells::new(parsed_merge_cell_range);
merged_cells_list.push(merge_cell_node);
}
Err(err) => {
println!("encountered error while parsing merge cell ref : {}", err);
}
}
}
}
Ok(merge_cells)
Ok(merged_cells_list)
}
fn load_sheet_color(ws: Node) -> Result<Option<String>, XlsxError> {
@@ -304,12 +288,11 @@ fn from_a1_to_rc(
worksheets: &[String],
context: String,
tables: HashMap<String, Table>,
defined_names: Vec<(String, Option<u32>)>,
) -> Result<String, XlsxError> {
let mut parser = Parser::new(worksheets.to_owned(), defined_names, tables);
let mut parser = Parser::new(worksheets.to_owned(), tables);
let cell_reference =
parse_reference(&context).map_err(|error| XlsxError::Xml(error.to_string()))?;
let t = parser.parse(&formula, &cell_reference);
let t = parser.parse(&formula, &Some(cell_reference));
Ok(to_rc_format(&t))
}
@@ -706,7 +689,6 @@ pub(super) fn load_sheet<R: Read + std::io::Seek>(
worksheets: &[String],
tables: &HashMap<String, Table>,
shared_strings: &mut Vec<String>,
defined_names: Vec<(String, Option<u32>)>,
) -> Result<(Worksheet, bool), XlsxError> {
let sheet_name = &settings.name;
let sheet_id = settings.id;
@@ -881,13 +863,8 @@ pub(super) fn load_sheet<R: Read + std::io::Seek>(
// It's the mother cell. We do not use the ref attribute in IronCalc
let formula = fs[0].text().unwrap_or("").to_string();
let context = format!("{}!{}", sheet_name, cell_ref);
let formula = from_a1_to_rc(
formula,
worksheets,
context,
tables.clone(),
defined_names.clone(),
)?;
let formula =
from_a1_to_rc(formula, worksheets, context, tables.clone())?;
match index_map.get(&si) {
Some(index) => {
// The index for that formula already exists meaning we bumped into a daughter cell first
@@ -941,13 +918,7 @@ pub(super) fn load_sheet<R: Read + std::io::Seek>(
// Its a cell with a simple formula
let formula = fs[0].text().unwrap_or("").to_string();
let context = format!("{}!{}", sheet_name, cell_ref);
let formula = from_a1_to_rc(
formula,
worksheets,
context,
tables.clone(),
defined_names.clone(),
)?;
let formula = from_a1_to_rc(formula, worksheets, context, tables.clone())?;
match get_formula_index(&formula, &shared_formulas) {
Some(index) => formula_index = index,
@@ -980,7 +951,7 @@ pub(super) fn load_sheet<R: Read + std::io::Seek>(
sheet_data.insert(row_index, data_row);
}
let merge_cells = load_merge_cells(ws)?;
let merge_cells_nodes = load_merge_cells_nodes(ws)?;
// Conditional Formatting
// <conditionalFormatting sqref="B1:B9">
@@ -1019,7 +990,7 @@ pub(super) fn load_sheet<R: Read + std::io::Seek>(
sheet_id,
state: state.to_owned(),
color,
merge_cells,
merged_cells_list: merge_cells_nodes,
comments: settings.comments,
frozen_rows: sheet_view.frozen_rows,
frozen_columns: sheet_view.frozen_columns,
@@ -1060,9 +1031,6 @@ pub(super) fn load_sheets<R: Read + std::io::Seek>(
let mut sheets = Vec::new();
let mut selected_sheet = 0;
let mut sheet_index = 0;
let defined_names = workbook.get_defined_names_with_scope();
for sheet in &workbook.worksheets {
let sheet_name = &sheet.name;
let rel_id = &sheet.id;
@@ -1084,15 +1052,8 @@ pub(super) fn load_sheets<R: Read + std::io::Seek>(
.ok_or_else(|| XlsxError::Xml("Corrupt XML structure".to_string()))?
.to_vec(),
};
let (s, is_selected) = load_sheet(
archive,
&path,
settings,
worksheets,
tables,
shared_strings,
defined_names.clone(),
)?;
let (s, is_selected) =
load_sheet(archive, &path, settings, worksheets, tables, shared_strings)?;
if is_selected {
selected_sheet = sheet_index;
}

Some files were not shown because too many files have changed in this diff Show More