diff --git a/crates/table/src/ui/grid.rs b/crates/table/src/ui/grid.rs index b51122cca..be1be5bfa 100644 --- a/crates/table/src/ui/grid.rs +++ b/crates/table/src/ui/grid.rs @@ -124,7 +124,8 @@ pub struct CellGridStyle { /// The thickness of the accent bar on a selected line's header edge. pub(crate) accent_bar: f32, pub(crate) preview: StyleColor, - pub(crate) selection: StyleColor, + /// The tint of a merged cell by its flags, the look a row tints its cells with. + pub(crate) tint: Stateful, pub(crate) handle_fill: StyleColor, pub(crate) handle_ring: StyleColor, pub(crate) edit_fill: StyleColor, diff --git a/crates/table/src/ui/grid/paint.rs b/crates/table/src/ui/grid/paint.rs index 16b23560d..838720d57 100644 --- a/crates/table/src/ui/grid/paint.rs +++ b/crates/table/src/ui/grid/paint.rs @@ -1,17 +1,18 @@ //! The grid's style, its own parts, and the paint over the rows: headers, the range outline, the fill handle, the copy //! marks, the in-cell editor and the chrome that sits on the sheet. -use craft_behavior::{CursorIcon, HitLevel, HitPriority, Metrics, PartKey, ScrollPos, Sense, TextPos}; +use craft_behavior::{CursorIcon, HitLevel, HitPriority, Metrics, PartKey, Positions, RowAt, ScrollPos, SelectionModel as _, Sense, TextPos}; use craft_ui::contract::{Access, Cx, Focus as _, Name, PaintUi, PartsCx, Remember as _, Role, Styled as _}; use craft_ui::primitives::{ Dashes, Draw, EditorLine, EditorPurpose, EditorRun, EditorState, HAlign, PaintShape, RectSide, RuleKind, StrokeWidth, TextRun, }; use craft_ui::runtime::env::Label; use craft_ui::runtime::motion::Animate as _; -use craft_ui::style::{Flags, Stateful, StyleCx, TypeRole}; +use craft_ui::style::{Flags, State, StateMix, StateSet, Stateful, StyleCx, TypeRole}; use egui::{CornerRadius, Pos2, Rect, Vec2}; use super::editor::{EditState, Mode}; +use super::row::CellPaint; use super::{CellAt, CellGrid, CellGridStyle, CellGridStyleKey, CellGridWords, CellRange, CellSelection, GridLayout, SheetGeometry, SheetMetrics}; use super::{edges, header_insets}; use crate::ui::error_tag::ErrorTag; @@ -57,7 +58,7 @@ pub(super) fn style(cx: &StyleCx<'_>, key: CellGridStyleKey) -> CellGridStyle { accent: cx.color(c.accent.solid), accent_bar: cx.tokens.stroke.thick, preview: cx.color(c.text.muted), - selection: cx.color(c.state.text_selection), + tint: super::row::cell_tint(cx), handle_fill: cx.color(c.accent.solid), handle_ring: cx.color(c.surface.background), edit_fill: cx.color(c.surface.raised), @@ -266,6 +267,7 @@ impl CellGrid<'_> { let editing = cx.recall::(); let open = editing.mode != Mode::Ready; let preview = cx.recall::(); + self.paint_merges(ui, geometry, &selection, cx); { let draw = ui.draw(); let rect = |shape: Rect| PaintShape::Rect(shape, CornerRadius::ZERO); @@ -322,6 +324,32 @@ impl CellGrid<'_> { self.place_chrome(ui, &frame, style, cx.env.words::().outline.clone()); } + /// Paints the merged cells in view, each whole over the rows it spans and cut to each pane it shows in, as a row + /// paints its cells. A merged cell takes the flags the item step gives a row's cells: selected when the selection + /// holds its first cell, lead when it holds the active cell while the grid has focus. + fn paint_merges(&self, ui: &mut PaintUi<'_>, geometry: &SheetGeometry, selection: &CellSelection, cx: &Cx<'_, Self>) { + let cells = + CellPaint { model: self.model, background: cx.style.background, tint: &cx.style.tint, zoom: self.zoom, rtl: geometry.right_to_left() }; + let focused = cx.is_focused(); + let order = Positions::new(self.model.rows().count()); + let shown = geometry.mirror_rect(geometry.cells()); + for merge in self.model.merges() { + let rect = geometry.mirror_rect(geometry.range_rect(merge)); + if !rect.intersects(shown) { + continue; + } + let (top, bottom, left, right) = edges(merge); + let held = |cell: &CellAt| (top..=bottom).contains(&cell.row) && (left..=right).contains(&cell.column); + let mut flags = Flags::empty(); + flags.set(Flags::SELECTED, selection.contains_cell(RowAt::new(&top, top as usize, &order), left)); + flags.set(Flags::LEAD, focused && selection.active().is_some_and(held)); + let state = StateSet::new(State::Rest, flags, StateMix::REST); + for pane in geometry.range_panes(merge) { + ui.clipped(geometry.mirror_rect(pane), |ui| cells.paint(ui, CellAt::new(top, left), rect, &state)); + } + } + } + fn paint_headers(&self, draw: &Draw<'_>, frame: &Frame, selection: &CellSelection, cx: &Cx<'_, Self>) { let style = cx.style; let geometry = &frame.geometry; diff --git a/crates/table/src/ui/grid/row.rs b/crates/table/src/ui/grid/row.rs index 688b4c05d..d84fa29ca 100644 --- a/crates/table/src/ui/grid/row.rs +++ b/crates/table/src/ui/grid/row.rs @@ -1,10 +1,10 @@ //! One row of the grid: its cells as parts, the gridlines, the selection tint and the app's cell paint. use craft_behavior::{ColumnKey, Metrics, PartKey, Sense}; -use craft_ui::contract::{Access, Component, Cx, MeasureCx, Name, PaintUi, PartsCx, Role, Styled as _}; +use craft_ui::contract::{Access, Component, Cx, MeasureCx, Name, PaintUi, PartsCx, Role}; use craft_ui::primitives::{PaintShape, RectSide, RuleKind}; -use craft_ui::style::{ComponentStyle, Flags, Stateful, StyleColor, StyleCx}; -use egui::{CornerRadius, Pos2, Rect, Response, Vec2}; +use craft_ui::style::{ComponentStyle, Flags, StateSet, Stateful, StyleColor, StyleCx}; +use egui::{CornerRadius, Rect, Response, Vec2}; use super::{CellAt, GridModel, edges}; @@ -18,8 +18,41 @@ pub struct GridRowStyle { tint: Stateful, } +/// The tint of a cell by its flags: the selection's tint on a selected cell, clear on the lead cell. A row's cells and +/// the grid's merged cells resolve this one look. +pub(super) fn cell_tint(cx: &StyleCx<'_>) -> Stateful { + let clear = cx.color(craft_theme::Rgba::TRANSPARENT); + Stateful::new(clear).when(Flags::LEAD, clear).when(Flags::SELECTED, cx.color(cx.tokens.color.state.text_selection)) +} + +/// How a cell paints, the same for a row's cells and the grid's merged cells. +pub(super) struct CellPaint<'p> { + pub(super) model: &'p dyn GridModel, + pub(super) background: StyleColor, + pub(super) tint: &'p Stateful, + pub(super) zoom: f32, + pub(super) rtl: bool, +} + +impl CellPaint<'_> { + /// Paints `cell` over `rect` in `state`: the sheet's background, the tint of `state`, the gridlines along its + /// bottom and end edges when the model shows them, then the app's paint of the cell. + pub(super) fn paint(&self, ui: &mut PaintUi<'_>, cell: CellAt, rect: Rect, state: &StateSet) { + { + let draw = ui.draw(); + draw.fill(&PaintShape::Rect(rect, CornerRadius::ZERO), self.background); + draw.fill(&PaintShape::Rect(rect, CornerRadius::ZERO), state.resolve(self.tint)); + if self.model.show_gridlines() { + draw.edge_rule(RuleKind::Divider, rect, RectSide::Bottom); + draw.edge_rule(RuleKind::Divider, rect, RectSide::end(self.rtl)); + } + } + self.model.paint_cell(ui, rect, cell, self.zoom); + } +} + /// One row of the sheet: a cell part per shown column. The app paints each cell through [`GridModel::paint_cell`]; the -/// row draws the gridlines (none inside a merged cell) and the selection tint. +/// row draws the gridlines and the selection tint. A merged cell spans rows, so the grid paints it, not its rows. #[derive(craft_ui::contract::Component)] pub struct GridRow<'r> { #[common] @@ -36,22 +69,13 @@ impl<'r> GridRow<'r> { GridRow { common: craft_ui::contract::Common::new(), model, row, zoom, cells } } - /// The merged cell holding `cell`, if any. - fn merge_of(&self, cell: CellAt) -> Option<(u32, u32, u32, u32)> { + /// Whether `cell` lies in a merged cell. + fn merged(&self, cell: CellAt) -> bool { self.model .merges() .iter() .map(edges) - .find(|&(top, bottom, left, right)| (top..=bottom).contains(&cell.row) && (left..=right).contains(&cell.column)) - } - - /// The rect of the merge anchored at `cell` whose first cell has `rect`, extended along the reading direction. - fn merged_rect(&self, rect: Rect, (top, bottom, left, right): (u32, u32, u32, u32), rtl: bool) -> Rect { - let (rows, columns) = (self.model.rows(), self.model.columns()); - let height = ((rows.start(bottom + 1) - rows.start(top)) * f64::from(self.zoom)) as f32; - let width = ((columns.start(right + 1) - columns.start(left)) * f64::from(self.zoom)) as f32; - let min_x = if rtl { rect.right() - width } else { rect.left() }; - Rect::from_min_size(Pos2::new(min_x, rect.top()), Vec2::new(width, height)) + .any(|(top, bottom, left, right)| (top..=bottom).contains(&cell.row) && (left..=right).contains(&cell.column)) } } @@ -63,12 +87,7 @@ impl Component for GridRow<'_> { type Output = Response; fn style(cx: &StyleCx<'_>, _: GridRowStyleKey) -> GridRowStyle { - let clear = cx.color(craft_theme::Rgba::TRANSPARENT); - GridRowStyle { - metrics: Metrics::new(), - background: cx.color(cx.tokens.color.surface.background), - tint: Stateful::new(clear).when(Flags::LEAD, clear).when(Flags::SELECTED, cx.color(cx.tokens.color.state.text_selection)), - } + GridRowStyle { metrics: Metrics::new(), background: cx.color(cx.tokens.color.surface.background), tint: cell_tint(cx) } } fn sense(&self) -> Sense { @@ -97,28 +116,14 @@ impl Component for GridRow<'_> { } fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { - let rtl = cx.env.direction().is_rtl(); - let gridlines = self.model.show_gridlines(); - let columns = self.cells.clone(); - for (key, rect) in &columns { + let cells = + CellPaint { model: self.model, background: cx.style.background, tint: &cx.style.tint, zoom: self.zoom, rtl: cx.env.direction().is_rtl() }; + for (key, rect) in &self.cells { let Some(column) = key.position() else { continue }; let cell = CellAt::new(self.row, column); - let merge = self.merge_of(cell); - let anchored = merge.is_none_or(|(top, _, left, _)| top == self.row && left == column); - if !anchored { - continue; + if !self.merged(cell) { + cells.paint(ui, cell, *rect, &cx.part_state(PartKey::CELL.at(u64::from(column)))); } - let shape = merge.map_or(*rect, |merge| self.merged_rect(*rect, merge, rtl)); - { - let draw = ui.draw(); - draw.fill(&PaintShape::Rect(shape, CornerRadius::ZERO), cx.style.background); - draw.fill(&PaintShape::Rect(shape, CornerRadius::ZERO), cx.resolve_part(PartKey::CELL.at(u64::from(column)), &cx.style.tint)); - if gridlines { - draw.edge_rule(RuleKind::Divider, shape, RectSide::Bottom); - draw.edge_rule(RuleKind::Divider, shape, RectSide::end(rtl)); - } - } - self.model.paint_cell(ui, shape, cell, self.zoom); } } diff --git a/crates/table/tests/it/grid.rs b/crates/table/tests/it/grid.rs index 143fbb5f6..7a6e3576f 100644 --- a/crates/table/tests/it/grid.rs +++ b/crates/table/tests/it/grid.rs @@ -287,3 +287,62 @@ fn a_pinch_zooms_about_the_pointer() { assert!(zoom > 1.0 && zoom <= 4.0, "the zoom grew within the sheet's range: {zoom}"); assert_eq!(rig.cell_under(at), before, "the cell under the pointer stays under it"); } + +/// The test sheet with cells B3:C4 merged and the first row and column frozen, recording each cell it paints. +struct Merged { + sheet: Sheet, + merges: [CellRange; 1], + painted: Rc, Rect)>>>, +} + +impl GridModel for Merged { + fn rows(&self) -> &LineIndex { + self.sheet.rows() + } + + fn columns(&self) -> &LineIndex { + self.sheet.columns() + } + + fn frozen(&self) -> (u32, u32) { + (1, 1) + } + + fn merges(&self) -> &[CellRange] { + &self.merges + } + + fn paint_cell(&self, ui: &mut PaintUi<'_>, rect: Rect, cell: CellAt, zoom: f32) { + self.painted.borrow_mut().push((cell, rect)); + self.sheet.paint_cell(ui, rect, cell, zoom); + } + + fn cell_text(&self, cell: CellAt) -> String { + self.sheet.cell_text(cell) + } +} + +/// A merged cell paints once, over the whole of the rows and columns it spans, and none of the cells it covers paints. +#[trial] +fn a_merged_cell_paints_once_over_all_its_rows() { + let painted = Rc::new(RefCell::new(Vec::new())); + let seen = painted.clone(); + let state = RefCell::new(GridState::new(a1(), 1.0)); + let mut fixture = Fixture::new(move |ui| { + let merges = [CellRange::cells(CellAt::new(2, 1), CellAt::new(3, 2))]; + let model = Merged { sheet: Sheet::new(None, Rc::new(Cell::new(1.0))), merges, painted: seen.clone() }; + let mut shown = state.borrow().clone(); + CellGrid::new("Sheet", &model, &mut shown).show_sheet(ui); + *state.borrow_mut() = shown; + }); + fixture.room(Vec2::new(400.0, 300.0)).settle(); + painted.borrow_mut().clear(); + fixture.idle(1); + let painted = painted.borrow(); + let merged: Vec = painted.iter().filter(|(cell, _)| *cell == CellAt::new(2, 1)).map(|(_, rect)| *rect).collect(); + let [rect] = merged.as_slice() else { panic!("the merged cell painted once, not {} times", merged.len()) }; + let one = painted.iter().find(|(cell, _)| *cell == CellAt::new(1, 1)).map(|(_, rect)| *rect).expect("B2 painted"); + assert!(rect.height() > one.height() * 1.5 && rect.width() > one.width() * 1.5, "the merged cell spans two rows and two columns"); + let covered = [CellAt::new(2, 2), CellAt::new(3, 1), CellAt::new(3, 2)]; + assert!(painted.iter().all(|(cell, _)| !covered.contains(cell)), "a covered cell painted: {painted:?}"); +} diff --git a/crates/ui-contract/src/contract/paint_ui.rs b/crates/ui-contract/src/contract/paint_ui.rs index da728a694..ffc3982d3 100644 --- a/crates/ui-contract/src/contract/paint_ui.rs +++ b/crates/ui-contract/src/contract/paint_ui.rs @@ -121,6 +121,25 @@ impl PaintUi<'_> { self.draw().for_part(inactive) } + /// Runs `paint` with this `PaintUi` cut to `rect` (inside the clip already in force), as `Draw::clipped` does for a + /// `Draw`: content painted whole over one pane of the component, such as a sheet's merged cell under a frozen row. + /// The children shown inside take the cut too; the clip is restored afterwards. + pub fn clipped(&mut self, rect: Rect, paint: impl FnOnce(&mut Self) -> R) -> R { + let kept = self.ui.clip_rect(); + let kids_kept = self.kids.as_ref().map(Ui::clip_rect); + self.ui.set_clip_rect(rect.intersect(kept)); + if let Some(kids) = &mut self.kids { + kids.set_clip_rect(rect.intersect(kids.clip_rect())); + } + let out = paint(self); + self.ui.set_clip_rect(kept); + if let Some(kids) = &mut self.kids { + // Children first shown inside `paint` built their Ui under the cut; they get the clip it had before. + kids.set_clip_rect(kids_kept.unwrap_or(kept)); + } + out + } + /// Runs `f` with the style context of this component's env, so app hooks called from `paint` pick colours and /// sizes through tokens as `style` does. pub fn with_style(&self, variant: Variant, f: impl FnOnce(&StyleCx<'_>) -> R) -> R {