CellGrid: a pinch or Cmd/Ctrl+wheel zooms about the pointer; the zoom and the scroll live in GridState

This commit is contained in:
aiongg
2026-11-12 14:32:46 +00:00
parent 5e7d2c9943
commit 210bea1bdf
3 changed files with 81 additions and 13 deletions
+46 -6
View File
@@ -6,7 +6,7 @@
//! parts and paint.
pub use craft_behavior::{CellAdvance, CellAt, CellDirection, CellRange, CellSelection, CellSpace, LineIndex, Positions, SHEET_ZOOM};
use craft_behavior::{DisplayOrder, ItemSource, Metrics, SheetLayout};
use craft_behavior::{DisplayOrder, EditEvent, ItemSource, Metrics, Mixed, ScrollPos, SheetLayout};
use craft_ui::contract::{
Bind, BindMut, Collection, CollectionEvent, CollectionProps, CollectionResponse, Common, ContainerProps, ContextMenuRequest, Cx, Outcome,
PaintUi, Props as _, Remember as _, Role, SelectMode, Sizing,
@@ -151,7 +151,8 @@ pub struct CellGridStyle {
/// - The editor: typing opens the active cell in Enter mode (the arrows move to another cell and commit), F2 in Edit
/// mode (the arrows move the caret), `=` and an operator in point mode (the arrows move a reference cursor).
///
/// The scroll lives in the collection.
/// A pinch or Cmd/Ctrl+wheel over the grid zooms it within [`SHEET_ZOOM`] about the pointer, keeping the cell under
/// the pointer in place. The zoom and the scroll live in the [`GridState`].
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
#[component(collection)]
pub struct CellGrid<'a> {
@@ -174,7 +175,11 @@ pub struct CellGrid<'a> {
selection: Bind<'a, CellSelection<u32>>,
/// The selection as the app held it when the pass began, for the parts that declare before the item step runs.
snapshot: CellSelection<u32>,
/// The zoom this pass shows, clamped from the state's.
zoom: f32,
/// The state's zoom, which a pinch writes for the next pass.
zoom_kept: &'a mut f32,
scroll: Bind<'a, ScrollPos>,
/// The ranges the copy marks surround.
#[prop]
copy_mark: &'a [CellRange<u32>],
@@ -195,8 +200,8 @@ pub struct CellGrid<'a> {
impl<'a> CellGrid<'a> {
/// A grid named `label` over `model` that keeps its selection and zoom in `state`.
pub fn new(label: impl Into<Label>, model: &'a dyn GridModel, state: &'a mut GridState) -> Self {
let GridState { selection, zoom } = state;
let zoom = if zoom.is_finite() { zoom.clamp(*SHEET_ZOOM.start(), *SHEET_ZOOM.end()) } else { 1.0 };
let GridState { selection, zoom: zoom_kept, scroll } = state;
let zoom = if zoom_kept.is_finite() { zoom_kept.clamp(*SHEET_ZOOM.start(), *SHEET_ZOOM.end()) } else { 1.0 };
let digits = digits_of(model.last_used().row.saturating_add(ROW_HEADER_LOOKAHEAD as u32)) as u8;
CellGrid {
common: Common::new(),
@@ -210,6 +215,8 @@ impl<'a> CellGrid<'a> {
snapshot: selection.clone(),
selection: Bind::bound(selection),
zoom,
zoom_kept,
scroll: Bind::bound(scroll),
copy_mark: &[],
filters: &[],
error_tag: None,
@@ -268,10 +275,14 @@ impl craft_ui::contract::Component for CellGrid<'_> {
self.paint_sheet(ui, cx);
}
fn finish(self, mut cx: Cx<'_, Self>) -> GridOutput {
fn scroll(&mut self) -> Option<BindMut<'_, ScrollPos>> {
Some(self.scroll.reborrow())
}
fn finish(mut self, mut cx: Cx<'_, Self>) -> GridOutput {
let mut collection = cx.collection_response();
let geometry = self.frame.as_ref().map(|frame| frame.geometry.clone());
let mut pass = self.pass;
let mut pass = std::mem::take(&mut self.pass);
if collection.events.iter().any(|event| matches!(event, CollectionEvent::Activate(_)))
&& let Some(cell) = cx.collection_selection().and_then(|selection| selection.active().copied())
{
@@ -296,6 +307,14 @@ impl craft_ui::contract::Component for CellGrid<'_> {
}
}
collection.events.retain(|event| !matches!(event, CollectionEvent::ContextMenu(_)));
if let Some(geometry) = &geometry {
for event in &collection.events {
if let CollectionEvent::Zoom { factor, about, .. } = event {
self.zoom_about(geometry, *factor, *about, cx.resolved.label);
}
}
}
collection.events.retain(|event| !matches!(event, CollectionEvent::Zoom { .. }));
let geometry = geometry.unwrap_or_else(|| {
let layout = GridLayout::new(cx.rect, self.model.rows().clone(), self.model.columns().clone()).bands(cx.style.bands);
SheetGeometry::new(layout, cx.style.sheet)
@@ -333,6 +352,10 @@ impl Collection for CellGrid<'_> {
self.reveal.as_ref()
}
fn zooms(&self) -> bool {
true
}
fn cell_space<'s>(&'s self, space: CellSpace<'s, u32>) -> CellSpace<'s, u32> {
space.merges(self.model.merges()).selectable(&*self.selectable)
}
@@ -343,6 +366,23 @@ impl Collection for CellGrid<'_> {
}
impl CellGrid<'_> {
/// Zooms by `factor` within [`SHEET_ZOOM`] about the screen point `about`: the state's zoom changes, and its scroll
/// moves so the content under `about` stays there on the next pass (the offset is in points at the zoom).
fn zoom_about(&mut self, geometry: &SheetGeometry, factor: f32, about: egui::Pos2, label: &str) {
let (from, to) = (self.zoom, (self.zoom * factor).clamp(*SHEET_ZOOM.start(), *SHEET_ZOOM.end()));
if !to.is_finite() || to == from {
return;
}
(self.zoom, *self.zoom_kept) = (to, to);
let Some(Mixed::Same(before)) = self.scroll.reborrow().get() else { return };
// The pointer from where the scrolling cells begin; over the frozen panes or the headers the scroll stays.
let past = (geometry.mirror_pos(about) - geometry.split()).max(Vec2::ZERO);
let ratio = f64::from(to) / f64::from(from);
let keep = |offset: f64, past: f32| ((offset + f64::from(past)) * ratio - f64::from(past)).max(0.0);
let after = ScrollPos { x: keep(before.x, past.x), y: keep(before.y, past.y) };
self.scroll.reborrow().apply(&EditEvent::set(Mixed::Same(before), after, std::sync::Arc::from(label), None));
}
/// The layout of the sheet: its frozen lines say where Ctrl+Home lands.
fn sheet_layout(&self) -> SheetLayout {
let (rows, columns) = self.model.frozen();
+6 -4
View File
@@ -1,7 +1,7 @@
//! The model and edit vocabulary: [`GridModel`], [`GridState`], edits, filters and cell problems.
use super::column_letters;
use craft_behavior::{CellAt, CellDirection, CellRange, CellSelection, EditEvent, LineIndex};
use craft_behavior::{CellAt, CellDirection, CellRange, CellSelection, EditEvent, LineIndex, ScrollPos};
use craft_ui::contract::PaintUi;
use craft_ui::runtime::env::Label;
use egui::{Pos2, Rect};
@@ -74,19 +74,21 @@ pub struct GridState {
pub selection: CellSelection<u32>,
/// The zoom, within [`SHEET_ZOOM`]; 1.0 for a new sheet.
pub zoom: f32,
/// How far the cells are scrolled, in points at the zoom; a pinch keeps the cell under the pointer by moving it.
pub scroll: ScrollPos,
}
impl GridState {
/// A sheet view with `selection` at `zoom`.
/// A sheet view with `selection` at `zoom`, scrolled to the first cell.
pub fn new(selection: CellSelection<u32>, zoom: f32) -> Self {
GridState { selection, zoom }
GridState { selection, zoom, scroll: ScrollPos::default() }
}
}
impl Default for GridState {
/// A1 selected at 100 %.
fn default() -> Self {
Self { selection: CellSelection::cell(CellAt::new(0, 0)), zoom: 1.0 }
Self { selection: CellSelection::cell(CellAt::new(0, 0)), zoom: 1.0, scroll: ScrollPos::default() }
}
}
+29 -3
View File
@@ -5,11 +5,11 @@ use std::collections::{BTreeMap, BTreeSet};
use std::rc::Rc;
use craft_behavior::{CellSelection, EditEvent, PartKey, PartRef};
use craft_table::ui::{CellAt, CellEdit, CellGrid, CellRange, GridEdit, GridModel, GridState, LineIndex, SHEET_COLUMNS, SHEET_ROWS};
use craft_table::ui::{CellAt, CellEdit, CellGrid, CellRange, GridEdit, GridModel, GridState, LineIndex, SHEET_COLUMNS, SHEET_ROWS, SheetGeometry};
use craft_ui::contract::PaintUi;
use craft_ui::primitives::TextRun;
use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::{Fixture, trial};
use craft_ui::testing::{Fixture, pointer, trial};
use egui::{Key, Modifiers, Rect, Vec2};
/// The default line sizes of the test sheet, points at 100 %.
@@ -58,6 +58,7 @@ struct Rig {
edits: Rc<RefCell<Vec<GridEdit>>>,
committed: Rc<RefCell<Vec<CellEdit>>>,
grid: Rc<Cell<Option<egui::Id>>>,
geometry: Rc<RefCell<Option<SheetGeometry>>>,
}
fn rig(hidden_column: Option<u32>, selection: CellSelection<u32>, zoom: f32) -> Rig {
@@ -69,11 +70,14 @@ fn rig(hidden_column: Option<u32>, selection: CellSelection<u32>, zoom: f32) ->
let shown_committed = committed.clone();
let grid = Rc::new(Cell::new(None));
let shown_grid = grid.clone();
let geometry = Rc::new(RefCell::new(None));
let shown_geometry = geometry.clone();
let mut fixture = Fixture::new(move |ui| {
let model = Sheet::new(hidden_column, shown_zoom.clone());
let mut state = shown_state.borrow().clone();
let out = CellGrid::new("Sheet", &model, &mut state).show_sheet(ui);
shown_grid.set(Some(out.collection.response.id));
*shown_geometry.borrow_mut() = Some(out.geometry);
*shown_state.borrow_mut() = state;
shown_edits.borrow_mut().extend(out.edits);
shown_committed.borrow_mut().extend(out.committed);
@@ -82,7 +86,7 @@ fn rig(hidden_column: Option<u32>, selection: CellSelection<u32>, zoom: f32) ->
let target = fixture.node_of(grid.get().expect("the grid showed")).expect("the grid has a node");
fixture.access(AccessActionKind::Focus, &target);
fixture.settle();
Rig { fixture, state, edits, committed, grid }
Rig { fixture, state, edits, committed, grid, geometry }
}
impl Rig {
@@ -111,6 +115,13 @@ impl Rig {
self.fixture.hold(modifiers).click_at(at).hold(Modifiers::NONE).idle(2);
}
/// The cell under the screen point `at` in the last pass's geometry.
fn cell_under(&self, at: egui::Pos2) -> CellAt<u32> {
let geometry = self.geometry.borrow();
let geometry = geometry.as_ref().expect("the grid showed");
geometry.cell_at(geometry.mirror_pos(at))
}
fn drag_part(&mut self, part: impl Into<PartRef>, by: Vec2) {
let from = self.part_rect(part).center();
self.fixture.drag_at(from, by);
@@ -261,3 +272,18 @@ fn header_shift_click_extends_and_cmd_click_adds_a_whole_line() {
assert_eq!((ranges[0].rows(), ranges[0].column_span()), whole, "the first range stays");
assert_eq!((ranges[1].rows(), ranges[1].column_span()), (0..=SHEET_ROWS - 1, 5..=5), "the new range is all of column F");
}
/// A pinch (Cmd/Ctrl with the wheel) over the grid zooms it about the pointer: the cell under the pointer stays there.
#[trial]
fn a_pinch_zooms_about_the_pointer() {
let mut rig = rig(None, a1(), 1.0);
let target = rig.fixture.node_of(rig.grid.get().expect("the grid showed")).expect("the grid has a node");
let at = target.rect.center();
let before = rig.cell_under(at);
rig.fixture.frame(vec![pointer::moved(at)]);
rig.fixture.frame(vec![pointer::zoom_wheel(40.0)]);
rig.fixture.idle(3);
let zoom = rig.state.borrow().zoom;
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");
}