Skip to content

Commit

Permalink
overhaul: fix inserting lines and add handling pattern fill
Browse files Browse the repository at this point in the history
  • Loading branch information
ImJeremyHe committed Jan 21, 2025
1 parent 4169af6 commit cff0a12
Show file tree
Hide file tree
Showing 17 changed files with 455 additions and 70 deletions.
5 changes: 0 additions & 5 deletions crates/controller/src/calc_engine/calculator/calc_vertex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,3 @@ pub struct RowRange {
pub start: usize,
pub end: usize,
}
#[derive(Debug, Clone)]
pub struct Range {
pub start: Addr,
pub end: Addr,
}
6 changes: 3 additions & 3 deletions crates/controller/src/controller/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ impl<'a> Executor<'a> {
result.status.sheet_pos_manager = sheet_pos_manager;

let old_navigator = result.status.navigator.clone();
let nav_executor = result.execute_navigator(payload.clone())?;
let (nav_executor, nav_updated) = result.execute_navigator(payload.clone())?;

let range_executor = result.execute_range(payload.clone())?;
let cube_executor = result.execute_cube(payload.clone())?;
Expand All @@ -115,7 +115,7 @@ impl<'a> Executor<'a> {
let formula_executor =
result.execute_formula(payload, &old_navigator, dirty_ranges, dirty_cubes)?;

let cell_updated = if updated {
let cell_updated = if updated || nav_updated {
true
} else {
result.updated_cells.len() > 0
Expand Down Expand Up @@ -213,7 +213,7 @@ impl<'a> Executor<'a> {
executor.execute(&ctx, payload)
}

fn execute_navigator(&mut self, payload: EditPayload) -> Result<NavExecutor, Error> {
fn execute_navigator(&mut self, payload: EditPayload) -> Result<(NavExecutor, bool), Error> {
let ctx = NavigatorConnector {
sheet_pos_manager: &self.status.sheet_pos_manager,
};
Expand Down
42 changes: 40 additions & 2 deletions crates/controller/src/controller/style.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ impl<'a> StyleConverter<'a> {
}

// Convert ARGB hex str and apply the tint to it.
fn from_hex_str(argb: String, tint: f64) -> Color {
pub fn from_hex_str(argb: String, tint: f64) -> Color {
use colorsys::{Hsl, Rgb};
if argb.len() < 8 {
return Color {
Expand Down Expand Up @@ -375,9 +375,32 @@ fn from_hex_str(argb: String, tint: f64) -> Color {
}
}

#[inline]
fn bound(upper: u8, lower: u8, v: f64) -> u8 {
let v = v.round();
let result = upper.min(v as u8) as u8;
let result = result.max(lower);
result
}

pub fn color_to_ct_color(c: Color) -> CtColor {
let r = bound(255, 0, c.red.unwrap_or(0.));
let g = bound(255, 0, c.green.unwrap_or(0.));
let b = bound(255, 0, c.blue.unwrap_or(0.));
let a = bound(255, 0, c.alpha.unwrap_or(255.));
let argb = format!("{:02X}{:02X}{:02X}{:02X}", a, r, g, b);
CtColor {
auto: None,
indexed: None,
rgb: Some(argb),
theme: None,
tint: 0.,
}
}

#[cfg(test)]
mod tests {
use super::from_hex_str;
use super::{color_to_ct_color, from_hex_str, Color};

#[test]
fn test_from_hex_str() {
Expand All @@ -386,4 +409,19 @@ mod tests {
let color = from_hex_str(argb, tint);
println!("{:?}", color);
}

#[test]
fn test_color_to_ct_color() {
let color = Color {
red: Some(12.),
green: Some(28.),
blue: Some(100.),
alpha: Some(241.),
};
let result = color_to_ct_color(color);
if result.rgb.is_none() {
panic!("should not be none")
}
println!("{:?}", result.rgb.unwrap())
}
}
34 changes: 19 additions & 15 deletions crates/controller/src/navigator/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ impl NavExecutor {
NavExecutor { nav }
}

pub fn execute<C: NavExecCtx>(mut self, ctx: &C, payload: EditPayload) -> Result<Self, Error> {
pub fn execute<C: NavExecCtx>(
mut self,
ctx: &C,
payload: EditPayload,
) -> Result<(Self, bool), Error> {
match payload {
EditPayload::MoveBlock(move_block) => {
let sheet_id = ctx
Expand All @@ -34,14 +38,14 @@ impl NavExecutor {
move_block.new_master_row,
move_block.new_master_col,
);
Ok(self)
Ok((self, true))
}
EditPayload::RemoveBlock(remove_block) => {
let sheet_id = ctx
.fetch_sheet_id_by_index(remove_block.sheet_idx)
.map_err(|l| BasicError::SheetIdxExceed(l))?;
self.nav.remove_block(&sheet_id, &remove_block.id);
Ok(self)
Ok((self, true))
}
EditPayload::CreateBlock(create_block) => {
let sheet_id = ctx
Expand All @@ -68,21 +72,21 @@ impl NavExecutor {
let block_id = create_block.id;
sheet_nav.data.blocks.insert(block_id, block_place);
sheet_nav.cache = Default::default();
Ok(self)
Ok((self, true))
}
EditPayload::CreateSheet(p) => {
let sheet_id = ctx
.fetch_sheet_id_by_index(p.idx)
.map_err(|l| BasicError::SheetIdxExceed(l))?;
self.nav.create_sheet(sheet_id);
Ok(self)
Ok((self, true))
}
EditPayload::DeleteSheet(delete_sheet) => {
let sheet_id = ctx
.fetch_sheet_id_by_index(delete_sheet.idx)
.map_err(|l| BasicError::SheetIdxExceed(l))?;
self.nav.delete_sheet(&sheet_id);
Ok(self)
Ok((self, true))
}
EditPayload::InsertCols(insert_cols) => {
let sheet_id = ctx
Expand All @@ -95,7 +99,7 @@ impl NavExecutor {
let res = NavExecutor {
nav: Navigator { sheet_navs },
};
Ok(res)
Ok((res, true))
}
EditPayload::DeleteCols(p) => {
let sheet_id = ctx
Expand All @@ -107,7 +111,7 @@ impl NavExecutor {
let res = NavExecutor {
nav: Navigator { sheet_navs },
};
Ok(res)
Ok((res, true))
}
EditPayload::InsertRows(insert_rows) => {
let sheet_id = ctx
Expand All @@ -120,7 +124,7 @@ impl NavExecutor {
let res = NavExecutor {
nav: Navigator { sheet_navs },
};
Ok(res)
Ok((res, true))
}
EditPayload::DeleteRows(p) => {
let sheet_id = ctx
Expand All @@ -132,7 +136,7 @@ impl NavExecutor {
let res = NavExecutor {
nav: Navigator { sheet_navs },
};
Ok(res)
Ok((res, true))
}
EditPayload::InsertColsInBlock(p) => {
let sheet_id = ctx
Expand All @@ -142,7 +146,7 @@ impl NavExecutor {
let new_bp = bp.add_new_cols(p.start, p.cnt as u32);
let nav = self.nav.add_block_place(sheet_id, p.block_id, new_bp);
let result = NavExecutor { nav };
Ok(result)
Ok((result, true))
}
EditPayload::DeleteColsInBlock(p) => {
let sheet_id = ctx
Expand All @@ -152,7 +156,7 @@ impl NavExecutor {
let new_bp = bp.delete_cols(p.start, p.cnt as u32);
let nav = self.nav.add_block_place(sheet_id, p.block_id, new_bp);
let result = NavExecutor { nav };
Ok(result)
Ok((result, true))
}
EditPayload::InsertRowsInBlock(p) => {
let sheet_id = ctx
Expand All @@ -162,7 +166,7 @@ impl NavExecutor {
let new_bp = bp.add_new_rows(p.start, p.cnt as u32);
let nav = self.nav.add_block_place(sheet_id, p.block_id, new_bp);
let result = NavExecutor { nav };
Ok(result)
Ok((result, true))
}
EditPayload::DeleteRowsInBlock(p) => {
let sheet_id = ctx
Expand All @@ -172,9 +176,9 @@ impl NavExecutor {
let new_bp = bp.delete_rows(p.start, p.cnt as u32);
let nav = self.nav.add_block_place(sheet_id, p.block_id, new_bp);
let result = NavExecutor { nav };
Ok(result)
Ok((result, true))
}
_ => Ok(self),
_ => Ok((self, false)),
}
}
}
Expand Down
25 changes: 22 additions & 3 deletions crates/controller/src/style_manager/fill_manager.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::controller::style::color_to_ct_color;
use crate::edit_action::StyleUpdateType;

use super::defaults::get_init_fill;
Expand All @@ -17,14 +18,32 @@ impl Default for FillManager {
}

impl FillManager {
pub fn execute(&mut self, id: FillId, _update_type: &StyleUpdateType) -> Option<FillId> {
let fill = if let Some(fill) = self.get_item(id) {
pub fn execute(&mut self, id: FillId, update_type: &StyleUpdateType) -> Option<FillId> {
let update = update_type.set_pattern_fill.as_ref()?;
let mut fill = if let Some(fill) = self.get_item(id) {
fill.clone()
} else {
get_init_fill()
};
let new_fill = &mut fill;
match new_fill {
CtFill::PatternFill(ct_pattern_fill) => {
if let Some(p) = &update.pattern_type {
ct_pattern_fill.pattern_type = Some(p.clone())
}
if let Some(p) = &update.fg_color {
let color = color_to_ct_color(p.clone());
ct_pattern_fill.fg_color = Some(color);
}
if let Some(p) = &update.bg_color {
let color = color_to_ct_color(p.clone());
ct_pattern_fill.bg_color = Some(color);
}
}
CtFill::GradientFill(_) => return None,
};
// todo
let new_id = self.get_id(&fill);
let new_id = self.get_id(&new_fill);
if id != new_id {
Some(new_id)
} else {
Expand Down
77 changes: 76 additions & 1 deletion crates/wasms/server/src/controller.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use logisheets_controller::controller::display::{CellPosition, DisplaySheetRequest};
use logisheets_controller::controller::style::{from_hex_str, PatternFill};
use logisheets_controller::edit_action::{
Alignment, AsyncFuncResult, BlockInput, CellClear, CellInput, CellStyleUpdate, CreateBlock,
CreateSheet, DeleteCols, DeleteColsInBlock, DeleteRows, DeleteRowsInBlock, DeleteSheet,
Expand All @@ -8,7 +9,7 @@ use logisheets_controller::edit_action::{
};
use logisheets_controller::{AsyncCalcResult, AsyncErr, RowInfo, SaveFileResult, Workbook};
use logisheets_controller::{ColInfo, ErrorMessage};
use logisheets_workbook::prelude::{StBorderStyle, StUnderlineValues};
use logisheets_workbook::prelude::{StBorderStyle, StPatternType, StUnderlineValues};
use singlyton::{Singleton, SingletonUninit};
use wasm_bindgen::prelude::*;
use xmlserde::XmlValue;
Expand Down Expand Up @@ -629,6 +630,80 @@ pub fn set_border(
MANAGER.get_mut().add_payload(id, p);
}

#[wasm_bindgen]
pub fn set_line_pattern_fill(
id: usize,
sheet_idx: usize,
row: bool,
from: usize,
to: usize,
fg_color: Option<String>,
bg_color: Option<String>,
pattern: Option<String>,
) {
init();
let update = build_pattern_fill_style_update(fg_color, bg_color, pattern);
let payload = EditPayload::LineStyleUpdate(LineStyleUpdate {
sheet_idx,
from,
to,
row,
ty: update,
});
MANAGER.get_mut().add_payload(id, payload);
}

fn build_pattern_fill_style_update(
fg_color: Option<String>,
bg_color: Option<String>,
pattern: Option<String>,
) -> StyleUpdateType {
let fg = if let Some(f) = fg_color {
Some(from_hex_str(f, 0.))
} else {
None
};
let bg = if let Some(b) = bg_color {
Some(from_hex_str(b, 0.))
} else {
None
};
let pattern: Option<StPatternType> = if let Some(p) = pattern {
serde_json::from_str(&format!("\"{}\"", p)).unwrap()
} else {
None
};
let pattern_fill = PatternFill {
fg_color: fg,
bg_color: bg,
pattern_type: pattern,
};
let mut style_update = StyleUpdateType::default();
style_update.set_pattern_fill = Some(pattern_fill);
style_update
}

#[wasm_bindgen]
pub fn set_cell_pattern_fill(
id: usize,
sheet_idx: usize,
row: usize,
col: usize,
fg_color: Option<String>,
bg_color: Option<String>,
pattern: Option<String>,
) {
init();
let style_update = build_pattern_fill_style_update(fg_color, bg_color, pattern);
let payload = EditPayload::CellStyleUpdate(CellStyleUpdate {
sheet_idx,
row,
col,
ty: style_update,
});
MANAGER.get_mut().add_payload(id, payload);
}

#[wasm_bindgen]
pub fn cell_input(id: usize, sheet_idx: usize, row: usize, col: usize, content: String) {
init();
Expand Down
2 changes: 1 addition & 1 deletion packages/web/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ export * from './worksheet'
export {CalcException, CustomFunc, Calculator} from './calculator'
export type {Executor} from './calculator'
export * from './cell'
export {isErrorMessage} from './utils'
export {isErrorMessage, getPatternFill} from './utils'
export type {Result} from './utils'
6 changes: 6 additions & 0 deletions packages/web/src/api/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {Fill, PatternFill} from '../bindings'
import {ErrorMessage} from '../bindings/error_message'

// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand All @@ -6,3 +7,8 @@ export function isErrorMessage(v: any): v is ErrorMessage {
}

export type Result<V> = V | ErrorMessage

export function getPatternFill(v: Fill): PatternFill | null {
if ('patternFill' in v) return v.patternFill
return null
}
Loading

0 comments on commit cff0a12

Please sign in to comment.