diff --git a/blocksuite/crates/editor/src/overlays/toolbar_chrome/hover.rs b/blocksuite/crates/editor/src/overlays/toolbar_chrome/hover.rs index dcea3a4f26..3f7b951f82 100644 --- a/blocksuite/crates/editor/src/overlays/toolbar_chrome/hover.rs +++ b/blocksuite/crates/editor/src/overlays/toolbar_chrome/hover.rs @@ -7,12 +7,21 @@ use crate::{ overlays::{OverlayScene, Overlays, TableAddDragKind, TableHoverState}, }; -fn table_add_zone( +struct TableAddZones { + left: f32, + right: f32, + bottom: f32, + vis_top: f32, + vis_bottom: f32, + right_fits: bool, + bottom_fits: bool, +} + +fn table_add_zones( block: &FlowBlock, scroll_x: f32, scene: &OverlayScene<'_>, - pointer: (f32, f32), -) -> Option { +) -> Option { let (min_x, min_y, max_r, max_b) = block.body.table_cells.iter().fold( (f32::INFINITY, f32::INFINITY, 0.0_f32, 0.0_f32), |(lx, ty, mr, mb), c| { @@ -38,36 +47,39 @@ fn table_add_zone( if table_screen_bottom < 0.0 || table_screen_top > viewport_height { return None; } - let vis_top = table_screen_top.max(0.0).ceil(); - let vis_bottom = table_screen_bottom.min(viewport_height).floor(); - let table_vis_h = (vis_bottom - vis_top).max(0.0); - let table_vis_w = (table_screen_right - table_screen_left).max(0.0); + Some(TableAddZones { + left: table_screen_left, + right: table_screen_right, + bottom: table_screen_bottom, + vis_top: table_screen_top.max(0.0).ceil(), + vis_bottom: table_screen_bottom.min(viewport_height).floor(), + right_fits: table_screen_right + 18.0 <= viewport_width, + bottom_fits: table_screen_bottom + 18.0 <= viewport_height, + }) +} - let (x, y) = pointer; - let near_right = (table_screen_right - 12.0..=table_screen_right + 20.0).contains(&x); - let near_bottom = (table_screen_bottom - 12.0..=table_screen_bottom + 20.0).contains(&y); - match (near_right, near_bottom) { - (true, true) - if table_screen_right + 18.0 <= viewport_width - && table_screen_bottom + 18.0 <= viewport_height => - { - Some(TableAddDragKind::Both) +impl TableAddZones { + fn at(&self, (x, y): (f32, f32)) -> Option { + let near_right = (self.right - 12.0..=self.right + 20.0).contains(&x); + let near_bottom = (self.bottom - 12.0..=self.bottom + 20.0).contains(&y); + match (near_right, near_bottom) { + (true, true) if self.right_fits && self.bottom_fits => Some(TableAddDragKind::Both), + (true, false) + if self.vis_bottom > self.vis_top + && (self.vis_top..=self.vis_bottom).contains(&y) + && self.right_fits => + { + Some(TableAddDragKind::Column) + } + (false, true) + if self.right > self.left + && (self.left..=self.right).contains(&x) + && self.bottom_fits => + { + Some(TableAddDragKind::Row) + } + _ => None, } - (true, false) - if (vis_top..=vis_bottom).contains(&y) - && table_vis_h > 0.0 - && table_screen_right + 18.0 <= viewport_width => - { - Some(TableAddDragKind::Column) - } - (false, true) - if (table_screen_left..=table_screen_right).contains(&x) - && table_vis_w > 0.0 - && table_screen_bottom + 18.0 <= viewport_height => - { - Some(TableAddDragKind::Row) - } - _ => None, } } @@ -348,12 +360,13 @@ impl Overlays { da.total_cmp(&dc) }) }); - let new_zone = table_add_zone(b, scroll_x, scene, pointer); + let zones = table_add_zones(b, scroll_x, scene); + let new_zone = zones.as_ref().and_then(|zones| zones.at(pointer)); let prev_zone = if self.table_hover.block_id.as_deref() == Some(b.block_id.as_str()) { self.table_hover .pointer - .and_then(|prev| table_add_zone(b, scroll_x, scene, prev)) + .and_then(|prev| zones.as_ref()?.at(prev)) } else { None }; @@ -502,20 +515,38 @@ mod tests { topbar_height: 52.0, }; let mut overlays = Overlays::default(); - // Enter table cell r1/c1 center (screen x=200, y=180 -> cell y=28). - assert!(overlays.sync_hover_affordances(&scene, 200.0, 180.0, 100.0)); - // Move inside the same cell center: zero redraws. - for dx in [1.0_f32, 5.0, 15.0] { - assert!( - !overlays.sync_hover_affordances(&scene, 200.0 + dx, 180.0, 110.0), - "moving inside cell center must not trigger redraw" + use TableAddDragKind::{Both, Column, Row}; + + let zones = table_add_zones(&layout.blocks[0], 0.0, &scene).expect("table bounds"); + for (x, y, zone, redraw) in [ + (200.0, 180.0, None, true), + (201.0, 180.0, None, false), + (215.0, 180.0, None, false), + (295.0, 180.0, Some(Column), true), + (298.0, 182.0, Some(Column), false), + (298.0, 270.0, Some(Both), true), + (296.0, 271.0, Some(Both), false), + (200.0, 270.0, Some(Row), true), + (205.0, 271.0, Some(Row), false), + (200.0, 250.0, None, true), + (205.0, 249.0, None, false), + ] { + assert_eq!( + zones.at((x, y - scene.topbar_height)), + zone, + "at ({x}, {y})" + ); + assert_eq!( + overlays.sync_hover_affordances(&scene, x, y, 100.0), + redraw, + "at ({x}, {y})", ); } - // Enter right edge add-column zone (table_screen_right = 300.0, near_right = 288..=320). - assert!(overlays.sync_hover_affordances(&scene, 295.0, 180.0, 120.0)); - // Move within the same add-column zone in the same cell: zero redraws. - assert!(!overlays.sync_hover_affordances(&scene, 298.0, 182.0, 130.0)); - // Move to corner add-both zone (table_screen_bottom = 220.0, near_bottom = 208..=240). - assert!(overlays.sync_hover_affordances(&scene, 298.0, 270.0, 140.0)); + assert!(overlays.sync_hover_affordances(&scene, 700.0, 500.0, 120.0)); + assert_eq!(overlays.table_hover.block_id, None); + assert_eq!(overlays.table_hover.row_id, None); + assert_eq!(overlays.table_hover.column_id, None); + assert_eq!(overlays.table_hover.pointer, None); + assert!(!overlays.sync_hover_affordances(&scene, 701.0, 500.0, 130.0)); } } diff --git a/blocksuite/crates/playground/src/overlays/view_table_cell/paint.rs b/blocksuite/crates/playground/src/overlays/view_table_cell/paint/mod.rs similarity index 60% rename from blocksuite/crates/playground/src/overlays/view_table_cell/paint.rs rename to blocksuite/crates/playground/src/overlays/view_table_cell/paint/mod.rs index e3496e9aa0..f0403fdbae 100644 --- a/blocksuite/crates/playground/src/overlays/view_table_cell/paint.rs +++ b/blocksuite/crates/playground/src/overlays/view_table_cell/paint/mod.rs @@ -1,4 +1,4 @@ -//! Table cell preedit snapshot patching, focus/caret/selection painting, axis previews, and the +//! Table cell preedit snapshot patching, focus/caret/selection painting and the //! Active Note table controls. use blocksuite_playground_doc::{ @@ -8,6 +8,8 @@ use blocksuite_playground_doc::{ use ui::{div, prelude::*, px}; use y_octo::{TextDeltaOp, TextInsert}; +mod preview; + use super::TablePaintFrame; use crate::{ PlaygroundView, @@ -44,131 +46,6 @@ impl PlaygroundView { ) } - /// Axis highlight and add/trim preview of `block`, clipped to the `width` × `height` layer. - pub(super) fn table_axis_preview_in( - &self, - block: &crate::block_flow::FlowBlock, - frame: TablePaintFrame, - width: f32, - height: f32, - palette: &Palette, - ) -> Option { - use blocksuite_editor::overlays::TableAxisMenu; - - let drag = self - .overlays - .table_hover - .add_drag - .as_ref() - .filter(|d| d.moved && d.block_id == block.block_id); - let axis = self - .table_cell - .as_ref() - .filter(|c| c.block_id == block.block_id) - .and_then(|c| c.axis_menu.map(|axis| (c, axis))); - if drag.is_none() && axis.is_none() { - return None; - } - let cells = &block.body.table_cells; - let scroll_x = (!cells.is_empty()).then(|| self.overlays.code_scroll_x(&block.block_id))?; - let dashed = - axis.is_none() && drag.is_some_and(|d| d.preview_rows >= 0 && d.preview_cols >= 0); - let body = frame.map(FlowRect::new(block.x, block.y, block.body.width, 0.0)); - let (left, right) = ( - body.x.max(0.0), - if dashed { - width - } else { - width.min(body.right()) - }, - ); - if left >= right || height <= 0.0 { - return None; - } - let (origin, bounds) = ((block.x - scroll_x, block.y), (left, right, height)); - let mut rects = Vec::new(); - let mut preview_kind: u8 = 0; - if let Some((cell, axis)) = axis { - for hit in cells.iter().filter(|h| match axis { - TableAxisMenu::Row => h.row_id == cell.row_id, - TableAxisMenu::Column => h.column_id == cell.column_id, - }) { - rects.extend(clip_rect(frame, origin, bounds, hit.rect)); - } - } else if let Some(drag) = drag { - let (rows, cols) = (drag.preview_rows, drag.preview_cols); - if rows < 0 || cols < 0 { - preview_kind = 1; - let BlockContent::Table(t) = - &self.snapshot.as_ref()?.block(&block.block_id)?.content - else { - return None; - }; - let tr = &t.rows[t.rows.len().saturating_sub(rows.unsigned_abs())..]; - let tc = &t.columns[t.columns.len().saturating_sub(cols.unsigned_abs())..]; - for c in cells.iter().filter(|c| { - tr.iter().any(|r| r.row_id == c.row_id) - || tc.iter().any(|k| k.column_id == c.column_id) - }) { - rects.extend(clip_rect(frame, origin, bounds, c.rect)); - } - } else { - preview_kind = 2; - let rtl = self.active_overlay_target()?.1.direction == ui::Direction::Rtl; - collect_grow_preview_rects( - cells, rows, cols, rtl, frame, origin, bounds, &mut rects, - ); - } - } - let first = rects.first()?; - let (x, y, r, b) = rects.iter().fold( - (first.x, first.y, first.right(), first.bottom()), - |(x, y, r, b), c| (x.min(c.x), y.min(c.y), r.max(c.right()), b.max(c.bottom())), - ); - let (ink, ew, style) = ( - palette.brand, - if dashed { 1.0 } else { 0.0 }, - if dashed { - ui::BorderStyle::Dashed - } else { - ui::BorderStyle::Solid - }, - ); - let box_el = div() - .absolute() - .left(px(x)) - .top(px(y)) - .w(px(r - x)) - .h(px(b - y)); - let box_el = match preview_kind { - 0 => box_el.snapshot("overlay.table_toolbar.axis_selection", Some("root.canvas")), - 1 => box_el.snapshot("overlay.table_hover.trim_preview", Some("root.canvas")), - _ => box_el.snapshot("overlay.table_hover.grow_preview", Some("root.canvas")), - }; - Some( - box_el - .child( - ui::canvas( - |_, _, _| (), - move |bounds, _, window, _| { - for cell in &rects { - window.paint_quad(ui::quad( - cell.translated(-x, -y).bounds(bounds.origin), - ui::Corners::all(px(0.0)), - ink.opacity(0.12), - ui::Edges::all(px(ew)), - ink.opacity(0.6), - style, - )); - } - }, - ) - .size_full(), - ) - .into_any_element(), - ) - } - /// Mount the axis menu when editing a table cell inside an Edgeless Note. pub(crate) fn render_edgeless_table_toolbar( &self, @@ -701,279 +578,3 @@ impl PlaygroundView { out } } - -fn clip_rect( - frame: TablePaintFrame, - origin: (f32, f32), - bounds: (f32, f32, f32), - rect: FlowRect, -) -> Option { - let m = frame.map(rect.translated(origin.0, origin.1)); - let (x, y) = (m.x.max(bounds.0), m.y.max(0.0)); - let (w, h) = (m.right().min(bounds.1) - x, m.bottom().min(bounds.2) - y); - (w > 0.0 && h > 0.0).then(|| FlowRect::new(x, y, w, h)) -} - -#[allow(clippy::too_many_arguments)] -fn collect_grow_preview_rects( - cells: &[crate::block_flow::TableCellHit], - rows: isize, - cols: isize, - rtl: bool, - frame: TablePaintFrame, - origin: (f32, f32), - bounds: (f32, f32, f32), - rects: &mut Vec, -) { - let (Some(first), Some(last)) = (cells.first(), cells.last()) else { - return; - }; - let vis = |r: FlowRect| { - let m = frame.map(r.translated(origin.0, origin.1)); - m.right() > bounds.0 && m.x < bounds.1 && m.bottom() > 0.0 && m.y < bounds.2 - }; - let added_w = cols as f32 * 120.0; - let (offset, start) = ( - if rtl { added_w } else { 0.0 }, - if rtl { first.rect.x } else { last.rect.right() }, - ); - let existing_h = (last.rect.bottom() - first.rect.y).max(0.0); - let vis_cols: Vec = (0..cols) - .filter(|_| existing_h > 0.0) - .map(|c| start + c as f32 * 120.0) - .filter(|&x| vis(FlowRect::new(x, first.rect.y, 120.0, existing_h))) - .collect(); - let first_cols = cells - .iter() - .take_while(|c| c.row_id == first.row_id) - .count(); - let push = |out: &mut Vec, r| out.extend(clip_rect(frame, origin, bounds, r)); - if !vis_cols.is_empty() { - let uniform = first_cols > 0 && cells.len().is_multiple_of(first_cols); - let vis_rows: Vec<(f32, f32)> = cells - .iter() - .step_by(if uniform { first_cols } else { 1 }) - .filter(|c| { - (uniform || c.column_id == first.column_id) - && vis(FlowRect::new(start, c.rect.y, added_w, c.rect.h)) - }) - .map(|c| (c.rect.y, c.rect.h)) - .collect(); - rects.reserve(vis_cols.len() * vis_rows.len()); - for &x in &vis_cols { - for &(y, h) in &vis_rows { - push(rects, FlowRect::new(x, y, 120.0, h)); - } - } - } - if rows <= 0 { - return; - } - let (added_top, added_h) = (last.rect.bottom(), rows as f32 * 36.0); - let cols_xy: Vec<(f32, f32)> = cells[..first_cols] - .iter() - .map(|c| (c.rect.x + offset, c.rect.w)) - .chain((0..cols).map(|c| (start + c as f32 * 120.0, 120.0))) - .filter(|&(x, w)| vis(FlowRect::new(x, added_top, w, added_h))) - .collect(); - if cols_xy.is_empty() { - return; - } - let (min_x, max_r) = cols_xy - .iter() - .fold((f32::INFINITY, f32::NEG_INFINITY), |(mn, mx), &(x, w)| { - (mn.min(x), mx.max(x + w)) - }); - rects.reserve(cols_xy.len() * rows as usize); - for row in 0..rows { - let y = added_top + row as f32 * 36.0; - if vis(FlowRect::new(min_x, y, (max_r - min_x).max(0.0), 36.0)) { - for &(x, w) in &cols_xy { - push(rects, FlowRect::new(x, y, w, 36.0)); - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::block_flow::TableCellHit; - use blocksuite_editor::{ - block_flow::{FlowTextLayout, InlineAlign, InlineBaseline, InlineStyle, layout_inline}, - overlays::OverlayScreenTransform, - theme::FONT_SANS, - }; - use std::rc::Rc; - use ui::{AppContext, Application, HeadlessPlatform, WindowOptions}; - - fn make_cells(rows: usize, cols: usize) -> Vec { - let platform = HeadlessPlatform::new(1280, 800, 1.0); - let app = Application::with_platform(platform).run_embedded(|_| {}); - let win = app - .update(|cx| { - cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| ui::EmptyView)) - }) - .expect("open window"); - let empty_text = app.update(|cx| { - win.update(cx, |_, window, _| { - let style = InlineStyle::new(FONT_SANS, 14.0, 400.0, ui::black()); - FlowTextLayout::Plain(Rc::new(layout_inline( - "", - &style, - 100.0, - 20.0, - InlineBaseline::At(15.0), - InlineAlign::Left, - window, - ))) - }) - .expect("window") - }); - let mut out = Vec::with_capacity(rows * cols); - for r in 0..rows { - for c in 0..cols { - out.push(TableCellHit { - row_id: format!("r{r}"), - column_id: format!("c{c}"), - rect: FlowRect::new(c as f32 * 100.0, r as f32 * 36.0, 100.0, 36.0), - text_origin: (0.0, 0.0), - text: empty_text.clone(), - }); - } - } - out - } - - fn reference_grow_preview( - cells: &[TableCellHit], - first: &TableCellHit, - last: &TableCellHit, - rows: isize, - cols: isize, - rtl: bool, - frame: TablePaintFrame, - origin: (f32, f32), - left: f32, - right: f32, - height: f32, - ) -> Vec { - let mut out = Vec::new(); - let offset = if rtl { cols as f32 * 120.0 } else { 0.0 }; - let start = if rtl { first.rect.x } else { last.rect.right() }; - for col in 0..cols { - let x = start + col as f32 * 120.0; - for c in cells.iter().filter(|c| c.column_id == first.column_id) { - out.push(FlowRect::new(x, c.rect.y, 120.0, c.rect.h)); - } - } - if rows > 0 { - let mut columns: Vec<(f32, f32)> = cells - .iter() - .take_while(|c| c.row_id == first.row_id) - .map(|c| (c.rect.x + offset, c.rect.w)) - .collect(); - for col in 0..cols { - columns.push((start + col as f32 * 120.0, 120.0)); - } - for row in 0..rows { - let y = last.rect.bottom() + row as f32 * 36.0; - for &(x, w) in &columns { - out.push(FlowRect::new(x, y, w, 36.0)); - } - } - } - out.into_iter() - .filter_map(|r| clip_rect(frame, origin, (left, right, height), r)) - .collect() - } - - #[test] - fn grow_preview_clipped_matches_reference_across_frames() { - struct Case { - name: &'static str, - rows: isize, - cols: isize, - rtl: bool, - origin: (f32, f32), - left: f32, - right: f32, - height: f32, - frame: TablePaintFrame, - } - let cells = make_cells(40, 4); - let first = cells.first().expect("first"); - let last = cells.last().expect("last"); - let cases = [ - Case { - name: "ltr_page_scrolled", - rows: 3, - cols: 5, - rtl: false, - origin: (-80.0, 20.0), - left: 50.0, - right: 760.0, - height: 620.0, - frame: TablePaintFrame::Page(PageViewport { - column_x: 40.0, - scroll_y: 420.0, - height: 620.0, - }), - }, - Case { - name: "rtl_page_scrolled", - rows: 2, - cols: 4, - rtl: true, - origin: (-40.0, 10.0), - left: 0.0, - right: 900.0, - height: 500.0, - frame: TablePaintFrame::Page(PageViewport { - column_x: 20.0, - scroll_y: 300.0, - height: 500.0, - }), - }, - Case { - name: "rotated_active_note", - rows: 4, - cols: 3, - rtl: false, - origin: (10.0, 15.0), - left: 20.0, - right: 880.0, - height: 700.0, - frame: TablePaintFrame::Note { - transform: OverlayScreenTransform { - origin: (60.0, 80.0), - pivot: (300.0, 400.0), - scale: 1.25, - rotate_deg: 17.5, - }, - vp_origin: (10.0, 15.0), - width: 880.0, - height: 700.0, - }, - }, - ]; - for c in cases { - let mut got = Vec::new(); - collect_grow_preview_rects( - &cells, - c.rows, - c.cols, - c.rtl, - c.frame, - c.origin, - (c.left, c.right, c.height), - &mut got, - ); - let want = reference_grow_preview( - &cells, first, last, c.rows, c.cols, c.rtl, c.frame, c.origin, c.left, c.right, - c.height, - ); - assert_eq!(got, want, "case {} mismatch", c.name); - } - } -} diff --git a/blocksuite/crates/playground/src/overlays/view_table_cell/paint/preview.rs b/blocksuite/crates/playground/src/overlays/view_table_cell/paint/preview.rs new file mode 100644 index 0000000000..72272493ad --- /dev/null +++ b/blocksuite/crates/playground/src/overlays/view_table_cell/paint/preview.rs @@ -0,0 +1,584 @@ +//! Table axis highlights and clipped grow and trim previews. + +use std::collections::HashSet; + +use blocksuite_playground_doc::read::{BlockContent, TableData}; +use ui::{div, prelude::*, px}; + +use super::TablePaintFrame; +use crate::{ + PlaygroundView, + block_flow::{FlowBlock, FlowRect, TableCellHit}, + theme::Palette, +}; + +impl PlaygroundView { + /// Axis highlight and add/trim preview of `block`, clipped to the `width` × `height` layer. + pub(super) fn table_axis_preview_in( + &self, + block: &FlowBlock, + frame: TablePaintFrame, + width: f32, + height: f32, + palette: &Palette, + ) -> Option { + use blocksuite_editor::overlays::TableAxisMenu; + + let drag = self + .overlays + .table_hover + .add_drag + .as_ref() + .filter(|d| d.moved && d.block_id == block.block_id); + let axis = self + .table_cell + .as_ref() + .filter(|c| c.block_id == block.block_id) + .and_then(|c| c.axis_menu.map(|axis| (c, axis))); + if drag.is_none() && axis.is_none() { + return None; + } + let cells = &block.body.table_cells; + let scroll_x = (!cells.is_empty()).then(|| self.overlays.code_scroll_x(&block.block_id))?; + let dashed = + axis.is_none() && drag.is_some_and(|d| d.preview_rows >= 0 && d.preview_cols >= 0); + let body = frame.map(FlowRect::new(block.x, block.y, block.body.width, 0.0)); + let (left, right) = ( + body.x.max(0.0), + if dashed { + width + } else { + width.min(body.right()) + }, + ); + if left >= right || height <= 0.0 { + return None; + } + let (origin, bounds) = ((block.x - scroll_x, block.y), (left, right, height)); + let mut rects = Vec::new(); + let mut preview_kind: u8 = 0; + if let Some((cell, axis)) = axis { + for hit in cells.iter().filter(|h| match axis { + TableAxisMenu::Row => h.row_id == cell.row_id, + TableAxisMenu::Column => h.column_id == cell.column_id, + }) { + rects.extend(clip_rect(frame, origin, bounds, hit.rect)); + } + } else if let Some(drag) = drag { + let (rows, cols) = (drag.preview_rows, drag.preview_cols); + if rows < 0 || cols < 0 { + preview_kind = 1; + let BlockContent::Table(t) = + &self.snapshot.as_ref()?.block(&block.block_id)?.content + else { + return None; + }; + rects = collect_trim_preview_rects( + cells, + t, + rows.unsigned_abs(), + cols.unsigned_abs(), + frame, + origin, + bounds, + ); + } else { + preview_kind = 2; + let rtl = self.active_overlay_target()?.1.direction == ui::Direction::Rtl; + collect_grow_preview_rects( + cells, rows, cols, rtl, frame, origin, bounds, &mut rects, + ); + } + } + let first = rects.first()?; + let (x, y, r, b) = rects.iter().fold( + (first.x, first.y, first.right(), first.bottom()), + |(x, y, r, b), c| (x.min(c.x), y.min(c.y), r.max(c.right()), b.max(c.bottom())), + ); + let (ink, ew, style) = ( + palette.brand, + if dashed { 1.0 } else { 0.0 }, + if dashed { + ui::BorderStyle::Dashed + } else { + ui::BorderStyle::Solid + }, + ); + let box_el = div() + .absolute() + .left(px(x)) + .top(px(y)) + .w(px(r - x)) + .h(px(b - y)); + let box_el = match preview_kind { + 0 => box_el.snapshot("overlay.table_toolbar.axis_selection", Some("root.canvas")), + 1 => box_el.snapshot("overlay.table_hover.trim_preview", Some("root.canvas")), + _ => box_el.snapshot("overlay.table_hover.grow_preview", Some("root.canvas")), + }; + Some( + box_el + .child( + ui::canvas( + |_, _, _| (), + move |bounds, _, window, _| { + for cell in &rects { + window.paint_quad(ui::quad( + cell.translated(-x, -y).bounds(bounds.origin), + ui::Corners::all(px(0.0)), + ink.opacity(0.12), + ui::Edges::all(px(ew)), + ink.opacity(0.6), + style, + )); + } + }, + ) + .size_full(), + ) + .into_any_element(), + ) + } +} + +fn collect_trim_preview_rects( + cells: &[TableCellHit], + table: &TableData, + rows: usize, + cols: usize, + frame: TablePaintFrame, + origin: (f32, f32), + bounds: (f32, f32, f32), +) -> Vec { + let Some(first) = cells.first() else { + return Vec::new(); + }; + // The table layout emits one cell for each column in every row. + let row_width = cells + .iter() + .take_while(|cell| cell.row_id == first.row_id) + .count(); + let rows = &table.rows[table.rows.len().saturating_sub(rows)..]; + let cols = &table.columns[table.columns.len().saturating_sub(cols)..]; + let row_ids = (rows.len() > 4).then(|| { + rows.iter() + .map(|row| row.row_id.as_str()) + .collect::>() + }); + let col_ids = (cols.len() > 4).then(|| { + cols.iter() + .map(|col| col.column_id.as_str()) + .collect::>() + }); + + let col_ids = col_ids.as_ref(); + cells + .chunks(row_width) + .flat_map(|row| { + let row_id = row[0].row_id.as_str(); + let row_matches = row_ids.as_ref().map_or_else( + || rows.iter().any(|row| row.row_id == row_id), + |ids| ids.contains(row_id), + ); + let cells = if row_matches || !cols.is_empty() { + row + } else { + &[] + }; + cells.iter().filter(move |cell| { + row_matches + || col_ids.map_or_else( + || cols.iter().any(|col| col.column_id == cell.column_id), + |ids| ids.contains(cell.column_id.as_str()), + ) + }) + }) + .filter_map(|cell| clip_rect(frame, origin, bounds, cell.rect)) + .collect() +} + +fn clip_rect( + frame: TablePaintFrame, + origin: (f32, f32), + bounds: (f32, f32, f32), + rect: FlowRect, +) -> Option { + let m = frame.map(rect.translated(origin.0, origin.1)); + let (x, y) = (m.x.max(bounds.0), m.y.max(0.0)); + let (w, h) = (m.right().min(bounds.1) - x, m.bottom().min(bounds.2) - y); + (w > 0.0 && h > 0.0).then(|| FlowRect::new(x, y, w, h)) +} + +#[allow(clippy::too_many_arguments)] +fn collect_grow_preview_rects( + cells: &[TableCellHit], + rows: isize, + cols: isize, + rtl: bool, + frame: TablePaintFrame, + origin: (f32, f32), + bounds: (f32, f32, f32), + rects: &mut Vec, +) { + let (Some(first), Some(last)) = (cells.first(), cells.last()) else { + return; + }; + let vis = |r: FlowRect| { + let m = frame.map(r.translated(origin.0, origin.1)); + m.right() > bounds.0 && m.x < bounds.1 && m.bottom() > 0.0 && m.y < bounds.2 + }; + let added_w = cols as f32 * 120.0; + let (offset, start) = ( + if rtl { added_w } else { 0.0 }, + if rtl { first.rect.x } else { last.rect.right() }, + ); + let existing_h = (last.rect.bottom() - first.rect.y).max(0.0); + let vis_cols: Vec = (0..cols) + .filter(|_| existing_h > 0.0) + .map(|c| start + c as f32 * 120.0) + .filter(|&x| vis(FlowRect::new(x, first.rect.y, 120.0, existing_h))) + .collect(); + let first_cols = cells + .iter() + .take_while(|c| c.row_id == first.row_id) + .count(); + let push = |out: &mut Vec, r| out.extend(clip_rect(frame, origin, bounds, r)); + if !vis_cols.is_empty() { + let uniform = first_cols > 0 && cells.len().is_multiple_of(first_cols); + let vis_rows: Vec<(f32, f32)> = cells + .iter() + .step_by(if uniform { first_cols } else { 1 }) + .filter(|c| { + (uniform || c.column_id == first.column_id) + && vis(FlowRect::new(start, c.rect.y, added_w, c.rect.h)) + }) + .map(|c| (c.rect.y, c.rect.h)) + .collect(); + rects.reserve(vis_cols.len() * vis_rows.len()); + for &x in &vis_cols { + for &(y, h) in &vis_rows { + push(rects, FlowRect::new(x, y, 120.0, h)); + } + } + } + if rows <= 0 { + return; + } + let (added_top, added_h) = (last.rect.bottom(), rows as f32 * 36.0); + let cols_xy: Vec<(f32, f32)> = cells[..first_cols] + .iter() + .map(|c| (c.rect.x + offset, c.rect.w)) + .chain((0..cols).map(|c| (start + c as f32 * 120.0, 120.0))) + .filter(|&(x, w)| vis(FlowRect::new(x, added_top, w, added_h))) + .collect(); + if cols_xy.is_empty() { + return; + } + let (min_x, max_r) = cols_xy + .iter() + .fold((f32::INFINITY, f32::NEG_INFINITY), |(mn, mx), &(x, w)| { + (mn.min(x), mx.max(x + w)) + }); + rects.reserve(cols_xy.len() * rows as usize); + for row in 0..rows { + let y = added_top + row as f32 * 36.0; + if vis(FlowRect::new(min_x, y, (max_r - min_x).max(0.0), 36.0)) { + for &(x, w) in &cols_xy { + push(rects, FlowRect::new(x, y, w, 36.0)); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::block_flow::PageViewport; + use blocksuite_editor::{ + block_flow::{FlowTextLayout, InlineAlign, InlineBaseline, InlineStyle, layout_inline}, + overlays::OverlayScreenTransform, + theme::FONT_SANS, + }; + use std::rc::Rc; + use ui::{AppContext, Application, HeadlessPlatform, WindowOptions}; + + fn make_cells(rows: usize, cols: usize) -> Vec { + let platform = HeadlessPlatform::new(1280, 800, 1.0); + let app = Application::with_platform(platform).run_embedded(|_| {}); + let win = app + .update(|cx| { + cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| ui::EmptyView)) + }) + .expect("open window"); + let empty_text = app.update(|cx| { + win.update(cx, |_, window, _| { + let style = InlineStyle::new(FONT_SANS, 14.0, 400.0, ui::black()); + FlowTextLayout::Plain(Rc::new(layout_inline( + "", + &style, + 100.0, + 20.0, + InlineBaseline::At(15.0), + InlineAlign::Left, + window, + ))) + }) + .expect("window") + }); + let mut out = Vec::with_capacity(rows * cols); + for r in 0..rows { + for c in 0..cols { + out.push(TableCellHit { + row_id: format!("r{r}"), + column_id: format!("c{c}"), + rect: FlowRect::new(c as f32 * 100.0, r as f32 * 36.0, 100.0, 36.0), + text_origin: (0.0, 0.0), + text: empty_text.clone(), + }); + } + } + out + } + + #[test] + fn trim_preview_clipped_matches_reference_across_frames() { + use blocksuite_playground_doc::read::{TableColumn, TableRow}; + + let (row_count, col_count) = (600, 8); + let cells = make_cells(row_count, col_count); + let table = TableData { + rows: (0..row_count) + .map(|r| TableRow { + row_id: format!("r{r}"), + order: String::new(), + background_color: None, + }) + .collect(), + columns: (0..col_count) + .map(|c| TableColumn { + column_id: format!("c{c}"), + order: String::new(), + width: None, + background_color: None, + }) + .collect(), + ..TableData::default() + }; + let origin = (-80.0, 12.0); + let bounds = (50.0, 860.0, 560.0); + for (rows, cols) in [(1, 0), (20, 0), (100, 0), (500, 0), (0, 3), (20, 3)] { + let first_trimmed_row = row_count - rows.max(1); + let scroll_y = first_trimmed_row as f32 * 36.0 + origin.1 - 50.0; + let frames = [ + ( + "page", + TablePaintFrame::Page(PageViewport { + column_x: 40.0, + scroll_y, + height: bounds.2, + }), + ), + ( + "zoomed Active Note", + TablePaintFrame::Note { + transform: OverlayScreenTransform { + origin: (60.0, 15.0 - scroll_y * 1.25), + pivot: (0.0, 0.0), + scale: 1.25, + rotate_deg: 0.0, + }, + vp_origin: (10.0, 15.0), + width: 880.0, + height: bounds.2, + }, + ), + ]; + for (name, frame) in frames { + let expected: Vec<_> = cells + .iter() + .enumerate() + .filter(|(index, _)| { + index / col_count >= row_count - rows + || index % col_count >= col_count - cols + }) + .filter_map(|(_, cell)| clip_rect(frame, origin, bounds, cell.rect)) + .collect(); + + assert!(!expected.is_empty(), "{name}, {rows} rows, {cols} columns"); + assert_eq!( + collect_trim_preview_rects(&cells, &table, rows, cols, frame, origin, bounds), + expected, + "{name}, {rows} rows, {cols} columns", + ); + } + } + } + + fn reference_grow_preview( + cells: &[TableCellHit], + first: &TableCellHit, + last: &TableCellHit, + rows: isize, + cols: isize, + rtl: bool, + frame: TablePaintFrame, + origin: (f32, f32), + left: f32, + right: f32, + height: f32, + ) -> Vec { + let mut out = Vec::new(); + let offset = if rtl { cols as f32 * 120.0 } else { 0.0 }; + let start = if rtl { first.rect.x } else { last.rect.right() }; + for col in 0..cols { + let x = start + col as f32 * 120.0; + for c in cells.iter().filter(|c| c.column_id == first.column_id) { + out.push(FlowRect::new(x, c.rect.y, 120.0, c.rect.h)); + } + } + if rows > 0 { + let mut columns: Vec<(f32, f32)> = cells + .iter() + .take_while(|c| c.row_id == first.row_id) + .map(|c| (c.rect.x + offset, c.rect.w)) + .collect(); + for col in 0..cols { + columns.push((start + col as f32 * 120.0, 120.0)); + } + for row in 0..rows { + let y = last.rect.bottom() + row as f32 * 36.0; + for &(x, w) in &columns { + out.push(FlowRect::new(x, y, w, 36.0)); + } + } + } + out.into_iter() + .filter_map(|r| clip_rect(frame, origin, (left, right, height), r)) + .collect() + } + + #[test] + fn grow_preview_clipped_matches_reference_across_frames() { + struct Case { + name: &'static str, + rows: isize, + cols: isize, + rtl: bool, + origin: (f32, f32), + left: f32, + right: f32, + height: f32, + frame: TablePaintFrame, + } + let cells = make_cells(40, 4); + let first = cells.first().expect("first"); + let last = cells.last().expect("last"); + let cases = [ + Case { + name: "ltr_page_scrolled", + rows: 3, + cols: 5, + rtl: false, + origin: (-80.0, 20.0), + left: 50.0, + right: 760.0, + height: 620.0, + frame: TablePaintFrame::Page(PageViewport { + column_x: 40.0, + scroll_y: 420.0, + height: 620.0, + }), + }, + Case { + name: "rtl_page_scrolled", + rows: 2, + cols: 4, + rtl: true, + origin: (-40.0, 10.0), + left: 0.0, + right: 900.0, + height: 500.0, + frame: TablePaintFrame::Page(PageViewport { + column_x: 20.0, + scroll_y: 300.0, + height: 500.0, + }), + }, + Case { + name: "page_row_growth", + rows: 3, + cols: 0, + rtl: false, + origin: (-30.0, 12.0), + left: 30.0, + right: 460.0, + height: 150.0, + frame: TablePaintFrame::Page(PageViewport { + column_x: 40.0, + scroll_y: 1380.0, + height: 150.0, + }), + }, + Case { + name: "zoomed_active_note_growth", + rows: 3, + cols: 2, + rtl: false, + origin: (-30.0, 12.0), + left: 40.0, + right: 600.0, + height: 170.0, + frame: TablePaintFrame::Note { + transform: OverlayScreenTransform { + origin: (60.0, -1700.0), + pivot: (0.0, 0.0), + scale: 1.25, + rotate_deg: 0.0, + }, + vp_origin: (10.0, 15.0), + width: 600.0, + height: 170.0, + }, + }, + Case { + name: "rotated_active_note", + rows: 4, + cols: 3, + rtl: false, + origin: (10.0, 15.0), + left: 20.0, + right: 880.0, + height: 700.0, + frame: TablePaintFrame::Note { + transform: OverlayScreenTransform { + origin: (60.0, 80.0), + pivot: (300.0, 400.0), + scale: 1.25, + rotate_deg: 17.5, + }, + vp_origin: (10.0, 15.0), + width: 880.0, + height: 700.0, + }, + }, + ]; + for c in cases { + let mut got = Vec::new(); + collect_grow_preview_rects( + &cells, + c.rows, + c.cols, + c.rtl, + c.frame, + c.origin, + (c.left, c.right, c.height), + &mut got, + ); + let want = reference_grow_preview( + &cells, first, last, c.rows, c.cols, c.rtl, c.frame, c.origin, c.left, c.right, + c.height, + ); + assert!(!want.is_empty(), "case {} must show a preview", c.name); + assert_eq!(got, want, "case {} mismatch", c.name); + } + } +}