mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-18 16:14:57 +00:00
Merge pull request #2298 from dfendr/fix/table-style-looks
Tables: Give each style row its own look
This commit is contained in:
8 files changed
+556
-118
No files matched your search
+11
-2
@@ -4,7 +4,9 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use gridcraft_core::{CellRef, RangeRef, Value, compare};
|
||||
use gridcraft_model::{CfOperator, CfRule, CfValueKind, Color, CondFormat, PatternType, Sheet, Style, Underline, Workbook, default_icon_thresholds};
|
||||
use gridcraft_model::{
|
||||
CfOperator, CfRule, CfValueKind, Color, CondFormat, PatternType, Sheet, Style, Table, Underline, Workbook, default_icon_thresholds,
|
||||
};
|
||||
|
||||
/// The conditional look of one cell.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
@@ -20,10 +22,12 @@ pub struct CfLook {
|
||||
pub hide_value: bool,
|
||||
}
|
||||
|
||||
/// Precomputed statistics per rule (min/max/percentiles/top-N thresholds/duplicates).
|
||||
/// Precomputed statistics per rule (min/max/percentiles/top-N thresholds/duplicates), and each
|
||||
/// table's visible edges. The grid and print keep one per paint.
|
||||
#[derive(Default)]
|
||||
pub struct CfCache {
|
||||
stats: HashMap<usize, RuleStats>,
|
||||
table_edges: HashMap<RangeRef, crate::tables::ShownEdges>,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
@@ -275,6 +279,11 @@ impl CfCache {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// [`crate::tables::shown_edges`] of `t`, found once per cache.
|
||||
pub fn table_edges(&mut self, sh: &Sheet, t: &Table) -> crate::tables::ShownEdges {
|
||||
*self.table_edges.entry(t.range).or_insert_with(|| crate::tables::shown_edges(sh, t))
|
||||
}
|
||||
|
||||
/// Conditional look of `c`, or `None` when no rule applies.
|
||||
pub fn look(&mut self, wb: &Workbook, sheet: usize, c: CellRef) -> Option<CfLook> {
|
||||
let sh = wb.sheet(sheet)?;
|
||||
|
||||
@@ -177,7 +177,7 @@ pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str
|
||||
let mut pics = PicCache::default();
|
||||
for lay in layouts {
|
||||
let Some(sh) = wb.sheet(lay.sheet) else { continue };
|
||||
let mut cf = if sh.cond_formats.is_empty() { None } else { Some(crate::cf::CfCache::new()) };
|
||||
let mut cf = crate::cf::CfCache::new();
|
||||
let k = lay.k();
|
||||
let (aw, ah) = lay.avail();
|
||||
for (pi, (ri, ci)) in lay.pages.iter().enumerate() {
|
||||
|
||||
@@ -25,12 +25,12 @@ pub(super) struct Look {
|
||||
pub(super) cf: Option<crate::cf::CfLook>,
|
||||
}
|
||||
|
||||
fn cell_look(wb: &Workbook, si: usize, sh: &Sheet, c: CellRef, cf: &mut Option<crate::cf::CfCache>) -> Look {
|
||||
fn cell_look(wb: &Workbook, si: usize, sh: &Sheet, c: CellRef, cf: &mut crate::cf::CfCache) -> Look {
|
||||
let mut style = match sh.table_at(c) {
|
||||
Some(t) => crate::tables::table_cell_style(wb, si, t, c),
|
||||
Some(t) => crate::tables::table_cell_shown_style(wb, si, t, cf.table_edges(sh, t), c),
|
||||
None => wb.styles.get(sh.style_id(c)).clone(),
|
||||
};
|
||||
let cfl = cf.as_mut().and_then(|cache| cache.look(wb, si, c));
|
||||
let cfl = cf.look(wb, si, c);
|
||||
if let Some(st) = cfl.as_ref().and_then(|l| l.style.as_ref()) {
|
||||
if st.align.reading_order.is_some() {
|
||||
style.align.reading_order = st.align.reading_order;
|
||||
@@ -319,7 +319,7 @@ impl<'a> Covered<'a> {
|
||||
}
|
||||
|
||||
/// Draws the cells of a block: fills, gridlines, data bars, borders and text.
|
||||
pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut Option<crate::cf::CfCache>) {
|
||||
pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut crate::cf::CfCache) {
|
||||
let (bx, by) = (b.xs.first().copied().unwrap_or(0.0), b.ys.first().copied().unwrap_or(0.0));
|
||||
let (bw, bh) = (b.xs.last().copied().unwrap_or(bx) - bx, b.ys.last().copied().unwrap_or(by) - by);
|
||||
if bw <= 0.0 || bh <= 0.0 {
|
||||
|
||||
+252
-86
@@ -2,7 +2,7 @@
|
||||
//! `TableStyleLight1…21 / Medium1…28 / Dark1…11` names so files round-trip).
|
||||
|
||||
use gridcraft_core::{CellRef, RangeRef};
|
||||
use gridcraft_model::{BorderLine, BorderStyle, Cell, Color, Fill, Formula, PatternType, Style, Table, Workbook};
|
||||
use gridcraft_model::{BorderLine, BorderStyle, Borders, Cell, Color, Fill, Formula, PatternType, Sheet, Style, Table, Workbook};
|
||||
|
||||
/// (family, number) from a style name, e.g. `TableStyleMedium2` → ("Medium", 2).
|
||||
pub fn parse_style_name(name: &str) -> (&'static str, u32) {
|
||||
@@ -22,113 +22,279 @@ fn accent_for(n: u32) -> Option<u8> {
|
||||
if k == 0 { None } else { Some(3 + k as u8) }
|
||||
}
|
||||
|
||||
/// Header/band/body colours for a table style.
|
||||
/// Fills, text colours and thin lines of a table style, per part of the table (the recipes in
|
||||
/// plan/excel/table-style-spec.json). Band 1 is the first data row; unbanded rows use band 2.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct TableLook {
|
||||
pub header_fill: Option<Color>,
|
||||
pub header_font: Color,
|
||||
pub header_bold: bool,
|
||||
pub band_fill: Option<Color>,
|
||||
pub body_fill: Option<Color>,
|
||||
pub line: Option<Color>,
|
||||
pub total_top: Option<Color>,
|
||||
pub band1: Option<Color>,
|
||||
pub band2: Option<Color>,
|
||||
pub body_font: Color,
|
||||
pub top: Option<Color>,
|
||||
pub header_bottom: Option<Color>,
|
||||
pub inner_h: Option<Color>,
|
||||
pub inner_v: Option<Color>,
|
||||
pub sides: Option<Color>,
|
||||
pub bottom: Option<Color>,
|
||||
/// The totals row's double top rule (the gallery doesn't show totals).
|
||||
pub total_top: Color,
|
||||
}
|
||||
|
||||
pub fn look(style: &str) -> TableLook {
|
||||
let (fam, n) = parse_style_name(style);
|
||||
let acc = accent_for(n);
|
||||
let base = |tint: i16| match acc {
|
||||
Some(a) => Color::Theme(a, tint),
|
||||
None => Color::Theme(1, if tint == 0 { 0 } else { tint.clamp(-1000, 1000) }),
|
||||
// An accent tint, or the neutral column's colour.
|
||||
let a = |tint: i16, neutral: Color| acc.map_or(neutral, |a| Color::Theme(a, tint));
|
||||
let (black, white) = (Color::Theme(1, 0), Color::Theme(0, 0));
|
||||
let (grey, mid_grey) = (Color::Theme(0, -150), Color::Theme(0, -350));
|
||||
let main = a(0, black);
|
||||
let plain = TableLook {
|
||||
header_fill: None,
|
||||
header_font: black,
|
||||
band1: None,
|
||||
band2: None,
|
||||
body_font: black,
|
||||
top: None,
|
||||
header_bottom: None,
|
||||
inner_h: None,
|
||||
inner_v: None,
|
||||
sides: None,
|
||||
bottom: None,
|
||||
total_top: main,
|
||||
};
|
||||
let neutral_light = |tint: i16| match acc {
|
||||
Some(a) => Color::Theme(a, tint),
|
||||
None => Color::Theme(0, -((1000 - tint).clamp(0, 1000) / 6)),
|
||||
};
|
||||
match fam {
|
||||
"Light" => {
|
||||
let group = (n - 1) / 7; // 0: lines only, 1: banded header line, 2: grid
|
||||
match (fam, n.saturating_sub(1) / 7) {
|
||||
("Light", 0) => {
|
||||
let text = a(-250, black);
|
||||
let line = Some(main);
|
||||
TableLook { header_font: text, body_font: text, band1: Some(a(800, grey)), top: line, header_bottom: line, bottom: line, ..plain }
|
||||
}
|
||||
("Light", 1) => {
|
||||
let line = Some(main);
|
||||
TableLook { header_fill: line, header_font: white, top: line, inner_h: line, sides: line, bottom: line, ..plain }
|
||||
}
|
||||
("Light", _) => {
|
||||
let line = Some(main);
|
||||
TableLook { band1: Some(a(800, grey)), top: line, header_bottom: line, inner_v: line, sides: line, bottom: line, ..plain }
|
||||
}
|
||||
("Medium", 0) => {
|
||||
let line = Some(a(400, black));
|
||||
TableLook { header_fill: Some(main), header_font: white, band1: Some(a(800, grey)), top: line, sides: line, bottom: line, ..plain }
|
||||
}
|
||||
("Medium", 1) => TableLook {
|
||||
header_fill: Some(main),
|
||||
header_font: white,
|
||||
band1: Some(a(600, mid_grey)),
|
||||
band2: Some(a(800, grey)),
|
||||
header_bottom: Some(white),
|
||||
inner_v: Some(white),
|
||||
..plain
|
||||
},
|
||||
("Medium", 2) => {
|
||||
// Accent header over neutral grey bands and black rules; the neutral style adds a grid.
|
||||
let line = Some(black);
|
||||
let grid = if acc.is_none() { line } else { None };
|
||||
let header_fill = Some(main);
|
||||
TableLook {
|
||||
header_fill: None,
|
||||
header_font: if group == 0 { base(-250) } else { Color::Auto },
|
||||
header_bold: true,
|
||||
band_fill: Some(neutral_light(800)),
|
||||
body_fill: None,
|
||||
line: Some(base(0)),
|
||||
total_top: Some(base(0)),
|
||||
header_fill,
|
||||
header_font: white,
|
||||
band1: Some(grey),
|
||||
top: line,
|
||||
header_bottom: line,
|
||||
inner_v: grid,
|
||||
sides: grid,
|
||||
bottom: line,
|
||||
total_top: black,
|
||||
..plain
|
||||
}
|
||||
}
|
||||
"Dark" => TableLook {
|
||||
header_fill: Some(Color::Theme(1, 0)),
|
||||
header_font: Color::Theme(0, 0),
|
||||
header_bold: true,
|
||||
band_fill: Some(base(-250)),
|
||||
body_fill: Some(base(0)),
|
||||
line: None,
|
||||
total_top: Some(Color::Theme(0, 0)),
|
||||
},
|
||||
_ => TableLook {
|
||||
header_fill: Some(base(0)),
|
||||
header_font: Color::Theme(0, 0),
|
||||
header_bold: true,
|
||||
band_fill: Some(neutral_light(800)),
|
||||
body_fill: None,
|
||||
line: if (n - 1) / 7 == 0 { None } else { Some(base(400)) },
|
||||
total_top: Some(base(0)),
|
||||
("Medium", _) => {
|
||||
let line = Some(a(400, black));
|
||||
let pale = Some(a(800, grey));
|
||||
TableLook { header_fill: pale, band1: Some(a(600, mid_grey)), band2: pale, top: line, inner_v: line, sides: line, bottom: line, ..plain }
|
||||
}
|
||||
("Dark", 0) => TableLook {
|
||||
header_fill: Some(black),
|
||||
header_font: white,
|
||||
band1: Some(a(-250, Color::Theme(1, 250))),
|
||||
band2: Some(a(0, Color::Theme(1, 450))),
|
||||
body_font: white,
|
||||
header_bottom: Some(white),
|
||||
total_top: white,
|
||||
..plain
|
||||
},
|
||||
_ if n == 8 => TableLook { header_fill: Some(black), header_font: white, band1: Some(mid_grey), band2: Some(grey), ..plain },
|
||||
_ => {
|
||||
// Dark 9-11 pair accents 1+2, 3+4 and 5+6: the header takes the even one.
|
||||
let k = n.clamp(9, 11) as u8 - 8;
|
||||
let (head, body) = (Color::Theme(3 + 2 * k, 0), 2 + 2 * k);
|
||||
let band1 = Some(Color::Theme(body, 600));
|
||||
TableLook { header_fill: Some(head), header_font: white, band1, band2: Some(Color::Theme(body, 800)), total_top: head, ..plain }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The style a table gives a cell (merged over the cell's own style: explicit fills/fonts win).
|
||||
/// Which parts of a table are on (the Table Style Options checkboxes).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct TableParts {
|
||||
pub header_row: bool,
|
||||
pub totals_row: bool,
|
||||
pub banded_rows: bool,
|
||||
pub banded_cols: bool,
|
||||
pub first_col: bool,
|
||||
pub last_col: bool,
|
||||
}
|
||||
|
||||
impl TableParts {
|
||||
pub fn of(t: &Table) -> TableParts {
|
||||
TableParts {
|
||||
header_row: t.header_row,
|
||||
totals_row: t.totals_row,
|
||||
banded_rows: t.banded_rows,
|
||||
banded_cols: t.banded_cols,
|
||||
first_col: t.first_col,
|
||||
last_col: t.last_col,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a table style paints on one cell of a `rows` x `cols` table (`row`, `col` from its
|
||||
/// top-left). Each line has one owner: a horizontal line is a cell's bottom (top only on the
|
||||
/// first row and the totals row), a vertical one a cell's right (left only on the first column).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct CellLook {
|
||||
pub fill: Option<Color>,
|
||||
pub font: Color,
|
||||
pub bold: bool,
|
||||
pub borders: Borders,
|
||||
}
|
||||
|
||||
pub fn cell_look(lk: &TableLook, p: TableParts, row: u32, col: u32, rows: u32, cols: u32) -> CellLook {
|
||||
let last_row = rows.saturating_sub(1);
|
||||
let last_col = cols.saturating_sub(1);
|
||||
let is_header = p.header_row && row == 0;
|
||||
let is_total = p.totals_row && row == last_row && !is_header;
|
||||
let thin = |c: Option<Color>| c.map(|color| BorderLine { style: BorderStyle::Thin, color }).unwrap_or_default();
|
||||
let mut b = Borders::default();
|
||||
if row == 0 {
|
||||
b.top = thin(lk.top);
|
||||
}
|
||||
b.bottom = thin(if row == last_row {
|
||||
lk.bottom
|
||||
} else if is_header {
|
||||
lk.header_bottom
|
||||
} else if p.totals_row && row.saturating_add(1) == last_row {
|
||||
None // the totals row draws its own top rule
|
||||
} else {
|
||||
lk.inner_h
|
||||
});
|
||||
if col == 0 {
|
||||
b.left = thin(lk.sides);
|
||||
}
|
||||
b.right = thin(if col == last_col { lk.sides } else { lk.inner_v });
|
||||
let mut out = CellLook { borders: b, font: lk.body_font, ..Default::default() };
|
||||
if is_header {
|
||||
out.fill = lk.header_fill;
|
||||
out.font = lk.header_font;
|
||||
out.bold = true;
|
||||
} else if is_total {
|
||||
out.fill = lk.band2;
|
||||
out.bold = true;
|
||||
out.borders.top = BorderLine { style: BorderStyle::Double, color: lk.total_top };
|
||||
} else {
|
||||
let data_row = row.saturating_sub(p.header_row as u32);
|
||||
let band1 = (p.banded_rows && data_row.is_multiple_of(2)) || (p.banded_cols && col.is_multiple_of(2));
|
||||
out.fill = if band1 { lk.band1 } else { lk.band2 };
|
||||
}
|
||||
if (p.first_col && col == 0) || (p.last_col && col == last_col) {
|
||||
out.bold = true;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The style a table gives a cell (merged over the cell's own style: explicit fills, fonts and
|
||||
/// borders win).
|
||||
pub fn table_cell_style(wb: &Workbook, sheet: usize, t: &Table, c: CellRef) -> Style {
|
||||
let own = wb.sheet(sheet).map(|sh| wb.styles.get(sh.style_id(c)).clone()).unwrap_or_default();
|
||||
let (start, end) = (t.range.start, t.range.end);
|
||||
let rows = end.row.saturating_sub(start.row).saturating_add(1);
|
||||
let cols = end.col.saturating_sub(start.col).saturating_add(1);
|
||||
let lk = cell_look(&look(&t.style), TableParts::of(t), c.row.saturating_sub(start.row), c.col.saturating_sub(start.col), rows, cols);
|
||||
let mut s = own.clone();
|
||||
let lk = look(&t.style);
|
||||
let is_header = t.header_row && c.row == t.range.start.row;
|
||||
let is_total = t.totals_row && c.row == t.range.end.row;
|
||||
let data_row = c.row.saturating_sub(t.range.start.row + t.header_row as u32);
|
||||
let data_col = c.col - t.range.start.col;
|
||||
let explicit_fill = own.fill.pattern != PatternType::None;
|
||||
if is_header {
|
||||
if let Some(f) = lk.header_fill
|
||||
&& !explicit_fill
|
||||
{
|
||||
s.fill = Fill::solid(f);
|
||||
}
|
||||
if own.font.color == Color::Auto {
|
||||
s.font.color = lk.header_font;
|
||||
}
|
||||
s.font.bold = s.font.bold || lk.header_bold;
|
||||
if let Some(l) = lk.line {
|
||||
s.borders.bottom = BorderLine { style: BorderStyle::Thin, color: l };
|
||||
}
|
||||
} else if is_total {
|
||||
s.font.bold = true;
|
||||
if let Some(l) = lk.total_top {
|
||||
s.borders.top = BorderLine { style: BorderStyle::Double, color: l };
|
||||
}
|
||||
} else {
|
||||
let band = (t.banded_rows && data_row.is_multiple_of(2)) || (t.banded_cols && data_col.is_multiple_of(2));
|
||||
if !explicit_fill {
|
||||
if band {
|
||||
if let Some(f) = lk.band_fill {
|
||||
s.fill = Fill::solid(f);
|
||||
}
|
||||
} else if let Some(f) = lk.body_fill {
|
||||
s.fill = Fill::solid(f);
|
||||
}
|
||||
}
|
||||
if let Some(l) = lk.line
|
||||
&& t.style.contains("Light")
|
||||
&& c.row == t.range.end.row
|
||||
{
|
||||
s.borders.bottom = BorderLine { style: BorderStyle::Thin, color: l };
|
||||
if let Some(f) = lk.fill
|
||||
&& own.fill.pattern == PatternType::None
|
||||
{
|
||||
s.fill = Fill::solid(f);
|
||||
}
|
||||
if own.font.color == Color::Auto {
|
||||
s.font.color = lk.font;
|
||||
}
|
||||
s.font.bold = s.font.bold || lk.bold;
|
||||
for (side, line) in [
|
||||
(&mut s.borders.top, lk.borders.top),
|
||||
(&mut s.borders.bottom, lk.borders.bottom),
|
||||
(&mut s.borders.left, lk.borders.left),
|
||||
(&mut s.borders.right, lk.borders.right),
|
||||
] {
|
||||
if side.is_none() {
|
||||
*side = line;
|
||||
}
|
||||
}
|
||||
if (t.first_col && c.col == t.range.start.col) || (t.last_col && c.col == t.range.end.col) {
|
||||
s.font.bold = true;
|
||||
s
|
||||
}
|
||||
|
||||
/// A table's first and last visible row and column (hidden or filtered lines skipped).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct ShownEdges {
|
||||
pub top: u32,
|
||||
pub bottom: u32,
|
||||
pub left: u32,
|
||||
pub right: u32,
|
||||
}
|
||||
|
||||
/// Finds [`ShownEdges`]. It scans the hidden lines at each edge, so the grid and print call it
|
||||
/// once per table per paint (through [`crate::cf::CfCache::table_edges`]), not once per cell.
|
||||
pub fn shown_edges(sh: &Sheet, t: &Table) -> ShownEdges {
|
||||
let (start, end) = (t.range.start, t.range.end);
|
||||
let row_shown = |r: &u32| sh.row_height(*r) > 0.0;
|
||||
let col_shown = |k: &u32| sh.col_width(*k) > 0.0;
|
||||
// With every row (or column) hidden, each cell takes both edges' lines; nothing is drawn.
|
||||
ShownEdges {
|
||||
top: (start.row..=end.row).find(row_shown).unwrap_or(end.row),
|
||||
bottom: (start.row..=end.row).rev().find(row_shown).unwrap_or(start.row),
|
||||
left: (start.col..=end.col).find(col_shown).unwrap_or(end.col),
|
||||
right: (start.col..=end.col).rev().find(col_shown).unwrap_or(start.col),
|
||||
}
|
||||
if t.style.starts_with("TableStyleDark") && !is_header && own.font.color == Color::Auto {
|
||||
s.font.color = Color::Theme(0, 0);
|
||||
}
|
||||
|
||||
/// The style the grid and print draw for a table cell. Like [`table_cell_style`], but the
|
||||
/// table's outer frame follows hidden rows and columns: the last visible row takes the table's
|
||||
/// bottom line, the last visible column its right side, and the first visible row and column its
|
||||
/// top line and left side. (Each frame line is owned by the edge cell, which is never drawn while
|
||||
/// it is hidden or filtered out.) Convert to Range uses [`table_cell_style`], the table as it is.
|
||||
pub fn table_cell_shown_style(wb: &Workbook, sheet: usize, t: &Table, e: ShownEdges, c: CellRef) -> Style {
|
||||
let mut s = table_cell_style(wb, sheet, t, c);
|
||||
let Some(sh) = wb.sheet(sheet) else { return s };
|
||||
let (start, end) = (t.range.start, t.range.end);
|
||||
let below = c.row < end.row && c.row >= e.bottom;
|
||||
let above = c.row > start.row && c.row <= e.top;
|
||||
let right = c.col < end.col && c.col >= e.right;
|
||||
let left = c.col > start.col && c.col <= e.left;
|
||||
if !(below || above || right || left) {
|
||||
return s;
|
||||
}
|
||||
let own = wb.styles.get(sh.style_id(c)).borders;
|
||||
if below && own.bottom.is_none() {
|
||||
s.borders.bottom = table_cell_style(wb, sheet, t, CellRef::new(end.row, c.col)).borders.bottom;
|
||||
}
|
||||
if above && own.top.is_none() {
|
||||
s.borders.top = table_cell_style(wb, sheet, t, CellRef::new(start.row, c.col)).borders.top;
|
||||
}
|
||||
if right && own.right.is_none() {
|
||||
s.borders.right = table_cell_style(wb, sheet, t, CellRef::new(c.row, end.col)).borders.right;
|
||||
}
|
||||
if left && own.left.is_none() {
|
||||
s.borders.left = table_cell_style(wb, sheet, t, CellRef::new(c.row, start.col)).borders.left;
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ mod sparse_clear_invalidation;
|
||||
mod stored_list_shape;
|
||||
mod structural_edit_rewrite;
|
||||
mod table_resize_overlap;
|
||||
mod table_style_looks;
|
||||
mod table_total_row_last_row;
|
||||
mod trace_error;
|
||||
mod workbook_author;
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
//! Table styles look like the Format as Table gallery: every row of the gallery (Light 1-7, 8-14,
|
||||
//! 15-21, Medium 1-7, …) has its own fills and lines, as recorded in plan/excel/table-style-spec.json.
|
||||
|
||||
use gridcraft_core::CellRef;
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_engine::model::*;
|
||||
use gridcraft_engine::tables::{ShownEdges, shown_edges, table_cell_shown_style, table_cell_style};
|
||||
use serde_json::json;
|
||||
|
||||
const ROWS: u32 = 6; // header + 5 data rows
|
||||
const COLS: u32 = 5;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["a", "b", "c", "d", "e"]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "A1:E6", "header": true})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The look of every cell of a 6x5 table (header on, banded rows) in `style`, row by row.
|
||||
fn grid_with(s: &Session, style: &str, edit: impl Fn(&mut Table)) -> Vec<Vec<Style>> {
|
||||
let wb = &s.doc().unwrap().wb;
|
||||
let mut t = wb.sheet(0).unwrap().tables[0].clone();
|
||||
t.style = format!("TableStyle{style}");
|
||||
edit(&mut t);
|
||||
(0..ROWS).map(|r| (0..COLS).map(|c| table_cell_style(wb, 0, &t, CellRef::new(r, c))).collect()).collect()
|
||||
}
|
||||
|
||||
fn grid(style: &str) -> Vec<Vec<Style>> {
|
||||
grid_with(&session(), style, |_| {})
|
||||
}
|
||||
|
||||
fn thin(color: Color) -> BorderLine {
|
||||
BorderLine { style: BorderStyle::Thin, color }
|
||||
}
|
||||
|
||||
const NONE: BorderLine = BorderLine { style: BorderStyle::None, color: Color::Auto };
|
||||
const BLACK: Color = Color::Theme(1, 0);
|
||||
const WHITE: Color = Color::Theme(0, 0);
|
||||
|
||||
#[test]
|
||||
fn each_row_of_the_gallery_has_its_own_look() {
|
||||
// Same accent (or neutral) across the gallery's rows, so only the row-group differs.
|
||||
for set in [
|
||||
&["Light1", "Light8", "Light15", "Medium1", "Medium8", "Medium15", "Medium22", "Dark1", "Dark8"][..],
|
||||
&["Light2", "Light9", "Light16", "Medium2", "Medium9", "Medium16", "Medium23", "Dark2", "Dark9"][..],
|
||||
] {
|
||||
let looks: Vec<_> = set.iter().map(|s| grid(s)).collect();
|
||||
for (i, a) in looks.iter().enumerate() {
|
||||
for (j, b) in looks.iter().enumerate().skip(i + 1) {
|
||||
assert_ne!(a, b, "{} and {} look the same", set[i], set[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neutral_bands_are_visibly_grey() {
|
||||
let theme = Theme::default();
|
||||
let fill = |style: &str, row: usize| grid(style)[row][0].fill.fg.resolve(&theme).unwrap();
|
||||
// lt1 -150 (about #D9D9D9) and lt1 -350 (about #A6A6A6).
|
||||
for ch in fill("Light1", 1) {
|
||||
assert!((210..=225).contains(&ch), "Light1 band {:?}", fill("Light1", 1));
|
||||
}
|
||||
for ch in fill("Medium8", 1) {
|
||||
assert!((160..=172).contains(&ch), "Medium8 band1 {:?}", fill("Medium8", 1));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn light15_has_a_vertical_grid_and_no_row_lines() {
|
||||
let g = grid("Light15");
|
||||
assert_eq!(g[0][0].borders.top, thin(BLACK));
|
||||
assert_eq!(g[0][2].borders.bottom, thin(BLACK), "header bottom");
|
||||
assert_eq!(g[2][1].borders.right, thin(BLACK), "inner vertical");
|
||||
assert_eq!(g[0][1].borders.right, thin(BLACK), "inner vertical in the header");
|
||||
assert_eq!(g[2][0].borders.left, thin(BLACK), "left side");
|
||||
assert_eq!(g[2][4].borders.right, thin(BLACK), "right side");
|
||||
assert_eq!(g[5][2].borders.bottom, thin(BLACK), "bottom");
|
||||
assert_eq!(g[2][1].borders.bottom, NONE, "no inner horizontal");
|
||||
assert_eq!(g[2][1].borders.top, NONE, "no inner horizontal");
|
||||
assert_eq!(g[1][0].fill.fg, Color::Theme(0, -150));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn medium2_has_a_pale_accent_frame_and_no_row_lines() {
|
||||
let g = grid("Medium2");
|
||||
let line = thin(Color::Theme(4, 400));
|
||||
assert_eq!(g[0][0].fill.fg, Color::Theme(4, 0));
|
||||
assert_eq!(g[0][0].font.color, WHITE);
|
||||
assert_eq!(g[0][2].borders.top, line);
|
||||
assert_eq!(g[0][0].borders.left, line, "the sides run down the header too");
|
||||
assert_eq!(g[3][0].borders.left, line);
|
||||
assert_eq!(g[3][4].borders.right, line);
|
||||
assert_eq!(g[5][2].borders.bottom, line);
|
||||
assert_eq!(g[0][2].borders.bottom, NONE, "no header bottom");
|
||||
assert_eq!(g[2][2].borders.bottom, NONE, "no inner horizontal");
|
||||
assert_eq!(g[2][2].borders.right, NONE, "no inner vertical");
|
||||
assert_eq!(g[1][2].fill.fg, Color::Theme(4, 800));
|
||||
assert_eq!(g[2][2].fill.pattern, PatternType::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn medium9_has_white_verticals_and_header_bottom() {
|
||||
let g = grid("Medium9");
|
||||
assert_eq!(g[0][1].borders.bottom, thin(WHITE));
|
||||
assert_eq!(g[0][1].borders.right, thin(WHITE));
|
||||
assert_eq!(g[3][1].borders.right, thin(WHITE));
|
||||
assert_eq!(g[3][1].borders.bottom, NONE);
|
||||
assert_eq!(g[3][0].borders.left, NONE, "no frame");
|
||||
assert_eq!(g[5][4].borders.bottom, NONE, "no frame");
|
||||
assert_eq!(g[1][0].fill.fg, Color::Theme(4, 600));
|
||||
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 800));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dark2_bands_in_shaded_and_full_accent_under_a_black_header() {
|
||||
let g = grid("Dark2");
|
||||
assert_eq!(g[0][0].fill.fg, BLACK);
|
||||
assert_eq!(g[0][0].borders.bottom, thin(WHITE));
|
||||
assert_eq!(g[1][0].fill.fg, Color::Theme(4, -250));
|
||||
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 0));
|
||||
assert_eq!(g[2][0].font.color, WHITE);
|
||||
assert_eq!(g[2][0].borders, Borders::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dark9_pairs_two_accents() {
|
||||
let g = grid("Dark9");
|
||||
assert_eq!(g[0][0].fill.fg, Color::Theme(5, 0));
|
||||
assert_eq!(g[0][0].font.color, WHITE);
|
||||
assert_eq!(g[1][0].fill.fg, Color::Theme(4, 600));
|
||||
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 800));
|
||||
assert_eq!(g[2][0].font.color, BLACK);
|
||||
let g = grid("Dark11");
|
||||
assert_eq!(g[0][0].fill.fg, Color::Theme(9, 0));
|
||||
assert_eq!(g[1][0].fill.fg, Color::Theme(8, 600));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_options_change_the_look() {
|
||||
let s = session();
|
||||
// Banded rows off: every data row looks like the second band.
|
||||
let g = grid_with(&s, "Medium9", |t| t.banded_rows = false);
|
||||
assert_eq!(g[1][0].fill.fg, Color::Theme(4, 800));
|
||||
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 800));
|
||||
// Banded columns alternate by column.
|
||||
let g = grid_with(&s, "Medium9", |t| {
|
||||
t.banded_rows = false;
|
||||
t.banded_cols = true;
|
||||
});
|
||||
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 600));
|
||||
assert_eq!(g[2][1].fill.fg, Color::Theme(4, 800));
|
||||
// Header off: the top line moves to the first data row, and nothing is drawn as a header.
|
||||
let g = grid_with(&s, "Light15", |t| t.header_row = false);
|
||||
assert_eq!(g[0][2].borders.top, thin(BLACK));
|
||||
assert_eq!(g[0][2].borders.bottom, NONE);
|
||||
assert!(!g[0][2].font.bold);
|
||||
// Totals row: bold, double top rule, no banding.
|
||||
let g = grid_with(&s, "Medium2", |t| t.totals_row = true);
|
||||
assert!(g[5][1].font.bold);
|
||||
assert_eq!(g[5][1].borders.top, BorderLine { style: BorderStyle::Double, color: Color::Theme(4, 0) });
|
||||
assert_eq!(g[5][1].borders.bottom, thin(Color::Theme(4, 400)));
|
||||
// First and last column bold.
|
||||
let g = grid_with(&s, "Medium2", |t| {
|
||||
t.first_col = true;
|
||||
t.last_col = true;
|
||||
});
|
||||
assert!(g[2][0].font.bold && g[2][4].font.bold && !g[2][2].font.bold);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_formatting_wins() {
|
||||
let mut s = session();
|
||||
s.execute("home.fillColor", json!({"range": "B3", "color": "#FF0000"})).unwrap();
|
||||
s.execute("home.fontColor", json!({"range": "B3", "color": "#00FF00"})).unwrap();
|
||||
s.execute("home.borders", json!({"range": "B3", "preset": "bottom"})).unwrap();
|
||||
let g = grid_with(&s, "Dark2", |_| {});
|
||||
assert_eq!(g[2][1].fill, Fill::solid(Color::Rgb(0xFF0000)));
|
||||
assert_eq!(g[2][1].font.color, Color::Rgb(0x00FF00));
|
||||
assert_eq!(g[2][1].borders.bottom.style, BorderStyle::Thin);
|
||||
assert_eq!(g[2][1].borders.bottom.color, Color::Auto);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_style_name_is_safe() {
|
||||
for name in ["Light0", "Light99", "Medium0", "Medium4000000000", "Dark0", "Dark12", "Dark99", "Bogus"] {
|
||||
let _ = grid(name);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the grid and print draw: like `grid_with`, but through the hidden-row/column aware
|
||||
/// `table_cell_shown_style`.
|
||||
fn shown_with(s: &Session, style: &str, edit: impl Fn(&mut Table)) -> Vec<Vec<Style>> {
|
||||
let wb = &s.doc().unwrap().wb;
|
||||
let mut t = wb.sheet(0).unwrap().tables[0].clone();
|
||||
t.style = format!("TableStyle{style}");
|
||||
edit(&mut t);
|
||||
let e = shown_edges(wb.sheet(0).unwrap(), &t);
|
||||
(0..ROWS).map(|r| (0..COLS).map(|c| table_cell_shown_style(wb, 0, &t, e, CellRef::new(r, c))).collect()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_follows_the_last_visible_row_and_column() {
|
||||
let frame = thin(Color::Theme(4, 400));
|
||||
// Nothing hidden: the shown look is the table look.
|
||||
let s = session();
|
||||
assert_eq!(shown_with(&s, "Medium2", |_| {}), grid_with(&s, "Medium2", |_| {}));
|
||||
// Last data row (and the one before it) and last column hidden: the frame moves in.
|
||||
let mut s = session();
|
||||
s.execute("home.hideRows", json!({"rows": "5:6"})).unwrap();
|
||||
s.execute("home.hideColumns", json!({"cols": "E:E"})).unwrap();
|
||||
let t = &s.doc().unwrap().wb.sheet(0).unwrap().tables[0];
|
||||
assert_eq!(shown_edges(s.doc().unwrap().wb.sheet(0).unwrap(), t), ShownEdges { top: 0, bottom: 3, left: 0, right: 3 });
|
||||
let g = shown_with(&s, "Medium2", |_| {});
|
||||
for (c, cell) in g[3].iter().take(4).enumerate() {
|
||||
assert_eq!(cell.borders.bottom, frame, "bottom frame on row 4, col {c}");
|
||||
}
|
||||
for (r, row) in g.iter().take(4).enumerate() {
|
||||
assert_eq!(row[3].borders.right, frame, "right frame on col D, row {r}");
|
||||
}
|
||||
// Rows above the last visible one keep their inner look (Medium 2 has no row lines).
|
||||
assert_eq!(g[2][1].borders.bottom, NONE);
|
||||
// Convert to Range and friends still see the table as it is.
|
||||
assert_eq!(grid_with(&s, "Medium2", |_| {})[3][1].borders.bottom, NONE);
|
||||
// Header off and the first data row filtered out: the top line moves down.
|
||||
let mut s = session();
|
||||
s.execute("home.hideRows", json!({"rows": "1:1"})).unwrap();
|
||||
s.execute("home.hideColumns", json!({"cols": "A:A"})).unwrap();
|
||||
let g = shown_with(&s, "Light15", |t| t.header_row = false);
|
||||
assert_eq!(g[1][2].borders.top, thin(BLACK));
|
||||
assert_eq!(g[2][1].borders.left, thin(BLACK));
|
||||
// Explicit borders still win.
|
||||
let mut s = session();
|
||||
s.execute("home.borders", json!({"range": "B5", "preset": "none"})).unwrap();
|
||||
s.execute("home.fillColor", json!({"range": "B5", "color": "#FF0000"})).unwrap();
|
||||
s.execute("home.borders", json!({"range": "C5", "preset": "bottom"})).unwrap();
|
||||
s.execute("home.hideRows", json!({"rows": "6:6"})).unwrap();
|
||||
let g = shown_with(&s, "Medium2", |_| {});
|
||||
assert_eq!(g[4][1].borders.bottom, frame);
|
||||
assert_eq!(g[4][2].borders.bottom.color, Color::Auto);
|
||||
}
|
||||
@@ -31,7 +31,7 @@ pub(super) fn center_across_end(start: u32, limit: u32, continues: impl Fn(u32)
|
||||
pub(super) fn look(wb: &Workbook, si: usize, sh: &Sheet, c: CellRef, cf: &mut CfCache) -> (Look, Option<CfLook>) {
|
||||
let mut style = wb.styles.get(sh.style_id(c)).clone();
|
||||
if let Some(t) = sh.table_at(c) {
|
||||
style = gridcraft_engine::tables::table_cell_style(wb, si, t, c);
|
||||
style = gridcraft_engine::tables::table_cell_shown_style(wb, si, t, cf.table_edges(sh, t), c);
|
||||
}
|
||||
let cfl = cf.look(wb, si, c);
|
||||
if let Some(l) = &cfl
|
||||
|
||||
@@ -27,36 +27,55 @@ pub(super) fn table_gallery(app: &mut SheetApp, ui: &mut Ui, cmd: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A style's gallery thumbnail: a 5x5 table (header row, banded rows) painted cell by cell from
|
||||
/// the same look the grid uses.
|
||||
pub(super) fn paint_table_swatch(ui: &Ui, r: Rect, wb: &gridcraft_engine::model::Workbook, style: &str) {
|
||||
let lk = gridcraft_engine::tables::look(style);
|
||||
let res = |c: Option<gridcraft_engine::model::Color>| c.and_then(|c| c.resolve(&wb.theme)).map(theme::color32);
|
||||
use egui::emath::GuiRounding;
|
||||
use gridcraft_engine::tables::{TableParts, cell_look, look};
|
||||
let lk = look(style);
|
||||
let parts = TableParts { header_row: true, totals_row: false, banded_rows: true, banded_cols: false, first_col: false, last_col: false };
|
||||
let res = |c: gridcraft_engine::model::Color| c.resolve(&wb.theme).map(theme::color32);
|
||||
let p = ui.painter();
|
||||
let t = Tokens::get(ui.ctx());
|
||||
p.rect_filled(r, 0.0, t.grid_bg);
|
||||
let rows = 5;
|
||||
let rh = r.height() / rows as f32;
|
||||
for i in 0..rows {
|
||||
let rr = Rect::from_min_size(pos2(r.left(), r.top() + i as f32 * rh), vec2(r.width(), rh));
|
||||
let fill = if i == 0 {
|
||||
res(lk.header_fill)
|
||||
} else if i % 2 == 1 {
|
||||
res(lk.band_fill)
|
||||
} else {
|
||||
res(lk.body_fill)
|
||||
};
|
||||
if let Some(f) = fill {
|
||||
p.rect_filled(rr, 0.0, f);
|
||||
}
|
||||
if let Some(l) = res(lk.line) {
|
||||
p.line_segment([rr.left_bottom(), rr.right_bottom()], Stroke::new(1.0, l));
|
||||
}
|
||||
for k in 0..3 {
|
||||
let x = rr.left() + 4.0 + k as f32 * (r.width() - 8.0) / 3.0;
|
||||
let col = if i == 0 { res(Some(lk.header_font)).unwrap_or(t.cell_text) } else { t.sheet_control_border };
|
||||
p.line_segment([pos2(x, rr.center().y), pos2(x + 10.0, rr.center().y)], Stroke::new(1.0, col));
|
||||
let line = |l: gridcraft_engine::model::BorderLine| if l.is_none() { None } else { Some(res(l.color).unwrap_or(t.cell_text)) };
|
||||
let n = 5u32;
|
||||
let (cw, rh) = (r.width() / n as f32, r.height() / n as f32);
|
||||
// Cell edges on whole pixels keep the lines crisp and the rows evenly spaced.
|
||||
let ppp = ui.pixels_per_point();
|
||||
let at = |start: f32, size: f32, k: u32| (start + size * k as f32).round_to_pixels(ppp);
|
||||
for row in 0..n {
|
||||
for col in 0..n {
|
||||
let (x0, x1) = (at(r.left(), cw, col), at(r.left(), cw, col + 1));
|
||||
let cr = Rect::from_min_max(pos2(x0, at(r.top(), rh, row)), pos2(x1, at(r.top(), rh, row + 1)));
|
||||
let cl = cell_look(&lk, parts, row, col, n, n);
|
||||
if let Some(f) = cl.fill.and_then(res) {
|
||||
p.rect_filled(cr, 0.0, f);
|
||||
}
|
||||
let b = cl.borders;
|
||||
// Excel centres the dash in the space inside the cell's own lines, across about half of it.
|
||||
let inset = |l: gridcraft_engine::model::BorderLine| if l.is_none() { 0.0 } else { 1.0 };
|
||||
let inner = Rect::from_min_max(
|
||||
pos2(cr.left() + inset(b.left), cr.top() + inset(b.top)),
|
||||
pos2(cr.right() - inset(b.right), cr.bottom() - inset(b.bottom)),
|
||||
);
|
||||
// When the gap can't split evenly, Excel puts the spare pixel below the dash.
|
||||
let top = ((inner.center().y - 0.5) * ppp).floor() / ppp;
|
||||
let (mid, half) = (inner.center().x, cw * 0.26);
|
||||
let dash = Rect::from_min_max(pos2((mid - half).round_to_pixels(ppp), top), pos2((mid + half).round_to_pixels(ppp), top + 1.0));
|
||||
p.rect_filled(dash, 0.0, res(cl.font).unwrap_or(t.cell_text));
|
||||
for (side, edge) in [
|
||||
(b.top, Rect::from_min_max(cr.left_top(), pos2(cr.right(), cr.top() + 1.0))),
|
||||
(b.bottom, Rect::from_min_max(pos2(cr.left(), cr.bottom() - 1.0), cr.right_bottom())),
|
||||
(b.left, Rect::from_min_max(cr.left_top(), pos2(cr.left() + 1.0, cr.bottom()))),
|
||||
(b.right, Rect::from_min_max(pos2(cr.right() - 1.0, cr.top()), cr.right_bottom())),
|
||||
] {
|
||||
if let Some(c) = line(side) {
|
||||
p.rect_filled(edge, 0.0, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
p.rect_stroke(r, 0.0, Stroke::new(1.0, t.separator), StrokeKind::Inside);
|
||||
}
|
||||
|
||||
pub(super) fn cell_style_gallery(app: &mut SheetApp, ui: &mut Ui) {
|
||||
|
||||
Reference in new issue
Block a user