perf(editor): lay out one block when its database view state or table focus changes

Keep database view state and table focus out of the environment revision that each block hashes.
Before this change, a pointer move to another Calendar day or Kanban lane laid out the whole page again.

`DatabaseFlowState` records each block whose view state changed.
Its state map is private. Each change of one block goes through a method that marks that block dirty.
A tab strip scroll that only stops the reveal of the active tab also marks its block dirty.

`update_pointer_hover` sets the Calendar day hover and the Kanban lane hover in one call.
It replaces `set_calendar_hovered_day` and `set_kanban_hovered_lane`.
The call adds no empty state for a block that the pointer is not on.

`LayoutKey` is a struct with named fields in `layout_cache.rs`.
It holds the database revision, a hash of the focused table, and the inputs that every block reads.
A layout pass adds the changed database blocks and the two tables of a focus change to its changed blocks.
The pass reuses each other block.

Remove the environment revision increments from the entry points that change one database block.
These are view switches, Calendar month steps, tab strip scrolls, cell input, key input, drag moves, and commits.
A sideways scroll of a database, a table row drag, and a table column drag change no layout state.
They start no layout pass.
`set_database_mobile_readonly` keeps its increment because it changes each database block.

Find the outermost Callout of an indented block in one pass from the page root.
The pass only enters blocks with children.
Before this change, each pointer move did one whole-tree parent lookup for each ancestor level of the block.

Add tests on a page with 10,000 paragraphs, one database, and one table.
One test uses a touch swipe on the view tabs of a right-to-left phone page.
Add a test of the drag handle rect of each block in nested Callouts and in deep lists.
Hold the preview provider test lock in `editing_one_block_lays_out_only_that_block_again`.
A preview revision that a parallel test changed started a second layout pass in that test.
The comment on the lock tells which tests must hold it.
This commit is contained in:
DarkSky committed 2026-12-01 09:09:02 +09:00
1 parent 2b94d66b97
commit 0db16d17e2
15 files changed
+1039 -249

No files matched your search

+236 -50
View File
@@ -166,10 +166,14 @@ pub struct DatabaseUiState {
/// Host-injected view-layer state for all `affine:database` blocks inside a [`crate::block_flow::BlockFlow`].
#[derive(Clone, Debug, Default)]
pub struct DatabaseFlowState {
pub ui_states: HashMap<String, DatabaseUiState>,
/// Private, so each change of the state of one block goes through a method that marks
/// that block dirty.
ui_states: HashMap<String, DatabaseUiState>,
pub clock_ms: i64,
pub mobile_readonly: bool,
revision: u64,
/// Blocks whose view state changed since the host last took them for a layout pass.
dirty_blocks: BTreeSet<String>,
}
impl DatabaseFlowState {
@@ -181,6 +185,75 @@ impl DatabaseFlowState {
self.ui_states.get(block_id).cloned().unwrap_or_default()
}
/// Each block that has view state, with that state.
pub fn states(&self) -> impl Iterator<Item = (&String, &DatabaseUiState)> {
self.ui_states.iter()
}
/// Record a change of `block_id`, so the next layout pass lays that block out again and
/// reuses every other block. Every method that changes the view state of one block calls
/// this. The host calls it when the layout of a database block reads state the host owns.
pub fn mark_dirty(&mut self, block_id: &str) {
self.revision = self.revision.wrapping_add(1);
if !self.dirty_blocks.contains(block_id) {
self.dirty_blocks.insert(block_id.to_string());
}
}
/// The blocks whose view state changed since the last call. The host takes them before each
/// layout pass and adds them to the changed blocks of a pass that reuses unchanged blocks.
pub fn take_dirty_blocks(&mut self) -> BTreeSet<String> {
std::mem::take(&mut self.dirty_blocks)
}
/// Put the desktop pointer hover on one Calendar day or one Kanban lane and clear it on
/// every other block. Returns `true` only when a hover value changed. A block without view
/// state gets an entry only while the pointer is on it.
pub fn update_pointer_hover(
&mut self,
calendar: Option<(&str, i64)>,
kanban: Option<(&str, &str)>,
) -> bool {
let hover_of = |id: &str| {
(
calendar.and_then(|(hit, day)| (hit == id).then_some(day)),
kanban.and_then(|(hit, key)| (hit == id).then_some(key)),
)
};
let mut changed = false;
for (id, state) in &mut self.ui_states {
let (day, lane) = hover_of(id);
if state.calendar_hovered_day != day || state.kanban_hovered_lane.as_deref() != lane {
state.calendar_hovered_day = day;
state.kanban_hovered_lane = lane.map(str::to_string);
self.dirty_blocks.insert(id.clone());
changed = true;
}
}
for id in [calendar.map(|hit| hit.0), kanban.map(|hit| hit.0)]
.into_iter()
.flatten()
{
if !self.ui_states.contains_key(id) {
let (day, lane) = hover_of(id);
self.ui_states.insert(
id.to_string(),
DatabaseUiState {
calendar_hovered_day: day,
kanban_hovered_lane: lane.map(str::to_string),
..DatabaseUiState::default()
},
);
self.dirty_blocks.insert(id.to_string());
changed = true;
}
}
if changed {
self.revision = self.revision.wrapping_add(1);
}
changed
}
pub fn set_active_view(&mut self, block_id: &str, view_id: impl Into<String>) {
let entry = self.ui_states.entry(block_id.to_string()).or_default();
let next_id = view_id.into();
@@ -189,7 +262,7 @@ impl DatabaseFlowState {
entry.reveal_active_tab = true;
}
entry.more_views_open = false;
self.revision = self.revision.wrapping_add(1);
self.mark_dirty(block_id);
}
pub fn set_calendar_selected_day(&mut self, block_id: &str, day_index: Option<i64>) {
@@ -197,27 +270,7 @@ impl DatabaseFlowState {
.entry(block_id.to_string())
.or_default()
.calendar_selected_day = day_index;
self.revision = self.revision.wrapping_add(1);
}
pub fn set_calendar_hovered_day(&mut self, block_id: &str, day_index: Option<i64>) -> bool {
let entry = self.ui_states.entry(block_id.to_string()).or_default();
if entry.calendar_hovered_day == day_index {
return false;
}
entry.calendar_hovered_day = day_index;
self.revision = self.revision.wrapping_add(1);
true
}
pub fn set_kanban_hovered_lane(&mut self, block_id: &str, bucket_key: Option<String>) -> bool {
let entry = self.ui_states.entry(block_id.to_string()).or_default();
if entry.kanban_hovered_lane == bucket_key {
return false;
}
entry.kanban_hovered_lane = bucket_key;
self.revision = self.revision.wrapping_add(1);
true
self.mark_dirty(block_id);
}
pub fn toggle_more_views(&mut self, block_id: &str) {
@@ -226,7 +279,7 @@ impl DatabaseFlowState {
if entry.more_views_open {
entry.authoring.dismiss_popovers();
}
self.revision = self.revision.wrapping_add(1);
self.mark_dirty(block_id);
}
pub fn close_more_views(&mut self, block_id: &str) -> bool {
@@ -237,23 +290,23 @@ impl DatabaseFlowState {
return false;
}
entry.more_views_open = false;
self.revision = self.revision.wrapping_add(1);
self.mark_dirty(block_id);
true
}
/// Scroll the view tabs from their stored offset. See [`Self::scroll_view_tabs_from`].
pub fn scroll_view_tabs(&mut self, block_id: &str, delta_px: i32, max_px: i32) -> bool {
let entry = self.ui_states.entry(block_id.to_string()).or_default();
entry.reveal_active_tab = false;
let next = (entry.view_tabs_scroll_px - delta_px).clamp(0, max_px.max(0));
if next != entry.view_tabs_scroll_px {
entry.view_tabs_scroll_px = next;
self.revision = self.revision.wrapping_add(1);
true
} else {
false
}
let stored = self
.ui_states
.get(block_id)
.map_or(0, |state| state.view_tabs_scroll_px);
self.scroll_view_tabs_from(block_id, stored, delta_px, max_px)
}
/// Scroll the view tabs by `delta_px` and stop the reveal of the active tab. While the
/// reveal is on, the scroll starts from `base_scroll_px`, the offset that the layout shows.
/// Returns `true` when the offset or the reveal changed. A block without view state gets
/// an entry only when that happens.
pub fn scroll_view_tabs_from(
&mut self,
block_id: &str,
@@ -261,22 +314,22 @@ impl DatabaseFlowState {
delta_px: i32,
max_px: i32,
) -> bool {
let entry = self.ui_states.entry(block_id.to_string()).or_default();
let start = if entry.reveal_active_tab {
let state = self.ui_states.get(block_id);
let revealing = state.is_some_and(|state| state.reveal_active_tab);
let start = if revealing {
base_scroll_px
} else {
entry.view_tabs_scroll_px
state.map_or(0, |state| state.view_tabs_scroll_px)
};
let was_revealing = entry.reveal_active_tab;
entry.reveal_active_tab = false;
let next = (start - delta_px).clamp(0, max_px.max(0));
if next != start || was_revealing {
entry.view_tabs_scroll_px = next;
self.revision = self.revision.wrapping_add(1);
true
} else {
false
if next == start && !revealing {
return false;
}
let entry = self.ui_states.entry(block_id.to_string()).or_default();
entry.reveal_active_tab = false;
entry.view_tabs_scroll_px = next;
self.mark_dirty(block_id);
true
}
pub fn set_calendar_month(&mut self, block_id: &str, month: Option<(i32, u32)>) {
@@ -284,7 +337,7 @@ impl DatabaseFlowState {
.entry(block_id.to_string())
.or_default()
.calendar_month = month;
self.revision = self.revision.wrapping_add(1);
self.mark_dirty(block_id);
}
pub fn step_calendar_month(&mut self, block_id: &str, current: (i32, u32), delta_months: i32) {
@@ -299,7 +352,17 @@ impl DatabaseFlowState {
.entry(block_id.to_string())
.or_default()
.mobile_readonly_notice = visible;
self.revision = self.revision.wrapping_add(1);
self.mark_dirty(block_id);
}
/// Hide the mobile read-only notice on each block that shows it.
pub fn clear_mobile_readonly_notices(&mut self) {
for (id, state) in &mut self.ui_states {
if std::mem::take(&mut state.mobile_readonly_notice) {
self.dirty_blocks.insert(id.clone());
self.revision = self.revision.wrapping_add(1);
}
}
}
pub fn toggle_group(&mut self, block_id: &str, group_key: &str) {
@@ -307,11 +370,11 @@ impl DatabaseFlowState {
if !entry.collapsed_groups.remove(group_key) {
entry.collapsed_groups.insert(group_key.to_string());
}
self.revision = self.revision.wrapping_add(1);
self.mark_dirty(block_id);
}
pub fn authoring_mut(&mut self, block_id: &str) -> &mut DatabaseAuthoringState {
self.revision = self.revision.wrapping_add(1);
self.mark_dirty(block_id);
&mut self
.ui_states
.entry(block_id.to_string())
@@ -612,4 +675,127 @@ mod tests {
assert!(!inner.is_empty());
}
}
#[test]
fn pointer_hover_marks_only_blocks_whose_hover_changed_and_adds_no_empty_state() {
let mut state = DatabaseFlowState::default();
state.set_active_view("db-b", "v-kanban");
state.take_dirty_blocks();
// (calendar hover, kanban hover, blocks marked dirty, blocks with view state)
type Step<'a> = (
Option<(&'a str, i64)>,
Option<(&'a str, &'a str)>,
&'a [&'a str],
usize,
);
let steps: [Step<'_>; 7] = [
(None, None, &[], 1),
(Some(("db-a", 7)), None, &["db-a"], 2),
(Some(("db-a", 7)), None, &[], 2),
(Some(("db-a", 8)), None, &["db-a"], 2),
(None, Some(("db-b", "todo")), &["db-a", "db-b"], 2),
(None, Some(("db-b", "todo")), &[], 2),
(None, None, &["db-b"], 2),
];
for (step, (calendar, kanban, dirty, entries)) in steps.into_iter().enumerate() {
let revision = state.revision();
let changed = state.update_pointer_hover(calendar, kanban);
assert_eq!(changed, !dirty.is_empty(), "step {step}");
assert_eq!(state.revision() != revision, changed, "step {step}");
let expected: BTreeSet<String> = dirty.iter().map(|id| id.to_string()).collect();
assert_eq!(state.take_dirty_blocks(), expected, "step {step}");
assert_eq!(state.ui_states.len(), entries, "step {step}");
assert_eq!(
state.state_for("db-a").calendar_hovered_day,
calendar.map(|hit| hit.1),
"step {step}"
);
assert_eq!(
state.state_for("db-b").kanban_hovered_lane.as_deref(),
kanban.map(|hit| hit.1),
"step {step}"
);
}
}
#[test]
fn view_tabs_scroll_marks_dirty_when_offset_or_reveal_changes_and_adds_no_empty_state() {
let mut state = DatabaseFlowState::default();
// A scroll that stays at offset 0 on a block without view state changes nothing.
assert!(!state.scroll_view_tabs("db", 1, 40));
assert!(!state.scroll_view_tabs_from("db", 0, 1, 40));
assert_eq!((state.ui_states.len(), state.revision()), (0, 0));
// A view switch starts the reveal of the active tab. The stored offset stays 0.
state.set_active_view("db", "v-9");
state.take_dirty_blocks();
// (delta, changed, stored offset): the first scroll stays at 0 but stops the reveal.
for (step, (delta, changed, offset)) in [(1, true, 0), (1, false, 0), (-12, true, 12)]
.into_iter()
.enumerate()
{
assert_eq!(
state.scroll_view_tabs("db", delta, 40),
changed,
"step {step}"
);
let dirty = state.take_dirty_blocks();
assert_eq!(dirty.contains("db"), changed, "step {step}");
let ui = state.state_for("db");
assert_eq!(
(ui.reveal_active_tab, ui.view_tabs_scroll_px),
(false, offset),
"step {step}"
);
}
}
#[test]
fn each_block_view_state_change_marks_its_block_dirty() {
let changes: [(&str, fn(&mut DatabaseFlowState)); 12] = [
("set_active_view", |s| s.set_active_view("db", "v2")),
("set_calendar_selected_day", |s| {
s.set_calendar_selected_day("db", Some(3))
}),
("toggle_more_views", |s| s.toggle_more_views("db")),
("close_more_views", |s| {
s.toggle_more_views("db");
s.take_dirty_blocks();
s.close_more_views("db");
}),
("scroll_view_tabs", |s| {
s.scroll_view_tabs("db", -12, 40);
}),
("scroll_view_tabs_from", |s| {
s.scroll_view_tabs_from("db", 0, -12, 40);
}),
("step_calendar_month", |s| {
s.step_calendar_month("db", (2026, 12), 1)
}),
("set_mobile_readonly_notice", |s| {
s.set_mobile_readonly_notice("db", true)
}),
("clear_mobile_readonly_notices", |s| {
s.set_mobile_readonly_notice("db", true);
s.take_dirty_blocks();
s.clear_mobile_readonly_notices();
}),
("mark_dirty", |s| s.mark_dirty("db")),
("toggle_group", |s| s.toggle_group("db", "todo")),
("authoring_mut", |s| {
s.authoring_mut("db").dismiss_popovers();
}),
];
for (name, change) in changes {
let mut state = DatabaseFlowState::default();
change(&mut state);
assert_ne!(state.revision(), 0, "{name}");
assert_eq!(
state.take_dirty_blocks(),
BTreeSet::from(["db".to_string()]),
"{name}"
);
assert!(state.take_dirty_blocks().is_empty(), "{name}");
}
}
}
@@ -37,6 +37,32 @@ const TODO_PHASE2_OFFSETS: [(f32, f32); 6] = [
(-32.0, -16.0),
];
/// The outermost Callout that contains `block_id` under `node`: `None` when `node` does not
/// contain the block, `Some(None)` when no Callout contains it. One pass from the top that only
/// enters blocks with children and stops at the block.
fn outermost_callout_of<'a>(
node: &'a blocksuite_playground_doc::read::BlockNode,
block_id: &str,
outer: Option<&'a str>,
) -> Option<Option<&'a str>> {
let outer = outer.or_else(|| {
matches!(
node.content,
blocksuite_playground_doc::read::BlockContent::Callout { .. }
)
.then_some(node.id.as_str())
});
node.children.iter().find_map(|child| {
if child.id == block_id {
Some(outer)
} else if child.children.is_empty() {
None
} else {
outermost_callout_of(child, block_id, outer)
}
})
}
/// Compute a block's gutter handle rect in world space, shifting Callout child blocks outside
/// the Callout card's outer border so `+⋮⋮` never overlaps the Callout's `ⓘ` / emoji icon.
pub(crate) fn effective_drag_handle_rect(
@@ -52,29 +78,17 @@ pub(crate) fn effective_drag_handle_rect(
if block.x <= 0.5 {
return Some(base);
}
if let Some(root) = scene.snapshot.root.as_ref() {
let mut cur = block.block_id.as_str();
let mut outer_callout_id: Option<&str> = None;
while let Some((parent, _)) = find_parent(root, cur) {
if matches!(
parent.content,
blocksuite_playground_doc::read::BlockContent::Callout { .. }
) {
outer_callout_id = Some(parent.id.as_str());
}
cur = parent.id.as_str();
}
if let Some(callout_id) = outer_callout_id
&& let Some(callout_block) = scene.layout.block(callout_id)
&& let Some(callout_handle) = drag_handle_rect(
callout_block,
scene.geometry.column_x,
scene.window.0,
scene.direction,
)
{
base.x = callout_handle.x;
}
if let Some(root) = scene.snapshot.root.as_ref()
&& let Some(Some(callout_id)) = outermost_callout_of(root, &block.block_id, None)
&& let Some(callout_block) = scene.layout.block(callout_id)
&& let Some(callout_handle) = drag_handle_rect(
callout_block,
scene.geometry.column_x,
scene.window.0,
scene.direction,
)
{
base.x = callout_handle.x;
}
Some(base)
}
@@ -471,3 +485,210 @@ impl Overlays {
}
}
}
#[cfg(test)]
mod tests {
use std::collections::{BTreeMap, BTreeSet, HashMap};
use blocksuite_playground_doc::{
read::{BlockContent, BlockNode, NoteDisplayMode, PageSnapshot, RichText},
schema::{ListType, ParagraphType},
};
use ui::{AppContext, Application, Direction, HeadlessPlatform, WindowOptions};
use super::*;
use crate::block_flow::{BlockFlow, FlowBlock, FlowInput, FormFactor, page_geometry};
fn node(id: &str, content: BlockContent, children: Vec<BlockNode>) -> BlockNode {
BlockNode {
id: id.to_string(),
flavour: String::new(),
version: None,
content,
props: BTreeMap::new(),
children,
}
}
fn text(id: &str) -> RichText {
RichText {
plain: id.to_string(),
delta: vec![y_octo::TextDeltaOp::Insert {
insert: y_octo::TextInsert::Text(id.to_string()),
format: None,
}],
}
}
fn paragraph(id: &str, kind: ParagraphType, children: Vec<BlockNode>) -> BlockNode {
let content = BlockContent::Paragraph {
kind,
text: text(id),
collapsed: false,
text_align: None,
};
node(id, content, children)
}
fn list(id: &str, children: Vec<BlockNode>) -> BlockNode {
let content = BlockContent::List {
kind: ListType::Bulleted,
checked: false,
collapsed: false,
text: text(id),
order: None,
numbered_index: None,
text_align: None,
};
node(id, content, children)
}
fn callout(id: &str, children: Vec<BlockNode>) -> BlockNode {
let content = BlockContent::Callout {
icon: "💡".to_string(),
text: text(""),
background_color: None,
};
node(id, content, children)
}
#[test]
fn callout_blocks_use_outer_callout_drag_handle_and_other_blocks_keep_their_own() {
let text_paragraph = |id: &str, children| paragraph(id, ParagraphType::Text, children);
let mut blocks: Vec<BlockNode> = (0..300)
.map(|index| text_paragraph(&format!("flat-{index}"), vec![]))
.collect();
blocks.push(callout(
"outer",
vec![
text_paragraph("outer-p", vec![text_paragraph("outer-p-child", vec![])]),
list("outer-l", vec![list("outer-l-child", vec![])]),
callout(
"inner",
vec![
text_paragraph("inner-p", vec![]),
list("inner-l", vec![list("inner-l-child", vec![])]),
],
),
],
));
blocks.push(paragraph(
"quote",
ParagraphType::Quote,
vec![text_paragraph("quote-child", vec![])],
));
blocks.extend((0..12).rev().fold(Vec::new(), |children, depth| {
vec![list(&format!("deep-{depth}"), children)]
}));
let note = node(
"note",
BlockContent::Note {
display_mode: NoteDisplayMode::Both,
xywh: String::new(),
background: serde_json::Value::Null,
hidden: false,
},
blocks,
);
let snapshot = PageSnapshot {
doc_id: "doc:handle".to_string(),
root: Some(node(
"page",
BlockContent::Page {
title: text("Handles"),
},
vec![note],
)),
detached: vec![],
};
let platform = HeadlessPlatform::new(1280, 800, 1.0);
let app = Application::with_platform(platform).run_embedded(|cx| {
crate::register_bundled_fonts(cx).expect("register fonts");
});
let win = app
.update(|cx| {
cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| ui::EmptyView))
})
.expect("open window");
let (titles, images, local_collapsed) = (BTreeMap::new(), HashMap::new(), BTreeSet::new());
for direction in [Direction::Ltr, Direction::Rtl] {
for window_width in [1280.0_f32, 320.0] {
let geometry = page_geometry(window_width);
let input = FlowInput {
snapshot: &snapshot,
width: geometry.column_width,
theme: crate::theme::PlaygroundTheme::Light,
page_titles: &titles,
images: &images,
pdf_previews: None,
doc_directory: None,
equation_draft: None,
env_rev: 0,
direction,
form_factor: FormFactor::Desktop,
utc_offset_minutes: 0,
utc_offset_at: None,
};
let layout = app.update(|cx| {
win.update(cx, |_, window, _| BlockFlow::new().layout(&input, window))
.expect("layout")
});
let scene = OverlayScene {
snapshot: &snapshot,
layout: &layout,
geometry,
window: (window_width, 800.0),
bottom_inset: 0.0,
bottom_toolbar_inset: 0.0,
scroll_y: 0.0,
direction,
form_factor: FormFactor::Desktop,
is_touch: false,
focused_code_block: None,
selected_image_block: None,
selected_bookmark_block: None,
selected_callout_block: None,
selected_latex_block: None,
selection: None,
screen_transform: None,
suppress_floating_format_buttons: false,
page_readonly: false,
local_collapsed: &local_collapsed,
};
let case = format!("{direction:?} at {window_width} px");
assert_eq!(layout.blocks.len(), 1 + 300 + 9 + 2 + 12, "{case}");
let own_rect = |block: &FlowBlock| {
drag_handle_rect(block, geometry.column_x, window_width, direction)
};
let outer_x = own_rect(layout.block("outer").expect("outer Callout"))
.expect("handle of the outer Callout")
.x;
let bits =
|rect: Option<FlowRect>| rect.map(|r| [r.x, r.y, r.w, r.h].map(f32::to_bits));
let mut in_callout = 0;
for block in &layout.blocks {
// Each block in a Callout, also in a nested one, has the handle x of the
// outer Callout. Each other block keeps the handle of its own indent level.
let mut expected = own_rect(block);
if block.block_id.starts_with("outer-") || block.block_id.starts_with("inner") {
expected = expected.map(|rect| FlowRect { x: outer_x, ..rect });
in_callout += 1;
}
assert_eq!(
bits(effective_drag_handle_rect(&scene, block)),
bits(expected),
"{case}: block {}",
block.block_id
);
}
assert_eq!(in_callout, 8, "{case}");
if window_width > 1000.0 {
let x_of = |id: &str| own_rect(layout.block(id).expect("block")).map(|r| r.x);
assert_ne!(x_of("outer-l-child"), Some(outer_x), "{case}");
assert_ne!(x_of("deep-11"), x_of("deep-0"), "{case}");
}
}
}
}
}
@@ -540,7 +540,6 @@ impl PlaygroundView {
column_id,
target_bucket_key: next_key,
});
self.env_rev += 1;
cx.notify();
true
}
@@ -640,7 +639,6 @@ impl PlaygroundView {
self.sync_after_database_mutation(before_sv, cx);
return true;
}
self.env_rev += 1;
cx.notify();
true
}
@@ -693,7 +691,6 @@ impl PlaygroundView {
calendar_day_index: Some(origin_day),
});
self.editor_focus.focus(window, cx);
self.env_rev += 1;
cx.notify();
self.sync_database_authoring_input(Some(window), cx);
self.place_database_inline_caret_at_point(
@@ -775,7 +772,6 @@ impl PlaygroundView {
}
}
}
self.env_rev += 1;
cx.notify();
true
}
@@ -207,7 +207,6 @@ impl PlaygroundView {
if mutated {
self.sync_after_database_mutation(before_sv, cx);
} else {
self.env_rev += 1;
cx.notify();
}
true
@@ -248,7 +247,6 @@ impl PlaygroundView {
if mutated {
self.sync_after_database_mutation(before_sv, cx);
} else {
self.env_rev += 1;
cx.notify();
}
}
@@ -331,7 +331,6 @@ impl PlaygroundView {
start_y,
promoted: true,
});
self.env_rev += 1;
cx.notify();
true
}
@@ -464,7 +463,6 @@ impl PlaygroundView {
promoted: true,
pending_click: None,
});
self.env_rev += 1;
cx.notify();
true
}
@@ -527,7 +525,6 @@ impl PlaygroundView {
self.sync_after_database_mutation(before_sv, cx);
return true;
}
self.env_rev += 1;
cx.notify();
true
}
@@ -616,7 +613,6 @@ impl PlaygroundView {
self.sync_after_database_mutation(before_sv, cx);
return true;
}
self.env_rev += 1;
cx.notify();
true
}
@@ -578,7 +578,6 @@ impl PlaygroundView {
select_filter: String::new(),
calendar_day_index: None,
});
self.env_rev += 1;
let mut window = window;
if let Some(w) = window.as_deref_mut() {
self.editor_focus.focus(w, cx);
@@ -634,37 +633,12 @@ impl PlaygroundView {
}
}
}
let mut changed = false;
for (bid, st) in &mut self.flow.database_state.ui_states {
let desired_day = hit_target
if self.flow.database_state.update_pointer_hover(
hit_target.as_ref().map(|(id, day)| (id.as_str(), *day)),
kanban_target
.as_ref()
.and_then(|(hb, d)| (hb == bid).then_some(*d));
if st.calendar_hovered_day != desired_day {
st.calendar_hovered_day = desired_day;
changed = true;
}
let desired_lane = kanban_target
.as_ref()
.and_then(|(hb, k)| (hb == bid).then(|| k.clone()));
if st.kanban_hovered_lane != desired_lane {
st.kanban_hovered_lane = desired_lane;
changed = true;
}
}
if let Some((hb, d)) = hit_target {
changed |= self
.flow
.database_state
.set_calendar_hovered_day(&hb, Some(d));
}
if let Some((hb, k)) = kanban_target {
changed |= self
.flow
.database_state
.set_kanban_hovered_lane(&hb, Some(k));
}
if changed {
self.env_rev += 1;
.map(|(id, key)| (id.as_str(), key.as_str())),
) {
cx.notify();
}
}
@@ -176,14 +176,12 @@ impl PlaygroundView {
) {
f(self.flow.database_state.authoring_mut(block_id));
self.sync_database_authoring_input(None, cx);
self.env_rev += 1;
cx.notify();
}
/// Set the horizontal scroll offset of a wide `affine:database` block.
pub fn scroll_database_x(&mut self, block_id: &str, scroll_x: f32, cx: &mut Context<Self>) {
self.overlays.set_code_scroll_x(block_id, scroll_x);
self.env_rev += 1;
cx.notify();
}
@@ -220,7 +218,7 @@ impl PlaygroundView {
/// Block id of whichever `affine:database` block currently has an open authoring popover or
/// active inline editor.
pub(crate) fn active_database_authoring_block(&self) -> Option<String> {
for (block_id, st) in &self.flow.database_state.ui_states {
for (block_id, st) in self.flow.database_state.states() {
if st.more_views_open {
return Some(block_id.clone());
}
@@ -231,7 +229,7 @@ impl PlaygroundView {
if let Some(session) = &self.database_input {
return Some(session.target.block_id().to_string());
}
for (block_id, st) in &self.flow.database_state.ui_states {
for (block_id, st) in self.flow.database_state.states() {
let a = &st.authoring;
if a.column_menu.is_some() || a.active_cell.is_some() || a.toolbar_panel.is_some() {
return Some(block_id.clone());
@@ -246,7 +244,7 @@ impl PlaygroundView {
if self.is_database_write_readonly() {
return None;
}
for (block_id, st) in &self.flow.database_state.ui_states {
for (block_id, st) in self.flow.database_state.states() {
let a = &st.authoring;
if let Some(menu) = &a.column_menu {
return Some((
@@ -529,7 +527,6 @@ impl PlaygroundView {
}
self.reset_caret_blink(cx);
self.env_rev += 1;
window.notify_text_input_changed(&self.editor_focus);
window.notify_text_selection_changed(&self.editor_focus);
cx.notify();
@@ -672,7 +669,6 @@ impl PlaygroundView {
.database_state
.authoring_mut(&block_id)
.dismiss_popovers();
self.env_rev += 1;
true
}
}
@@ -36,7 +36,6 @@ impl PlaygroundView {
.database_state
.authoring_mut(&block_id)
.dismiss_popovers();
self.env_rev += 1;
return false;
}
if self
@@ -92,7 +91,6 @@ impl PlaygroundView {
if auth_key == DatabaseAuthoringKey::Escape
&& self.flow.database_state.close_more_views(&block_id)
{
self.env_rev += 1;
cx.notify();
return true;
}
@@ -159,7 +157,6 @@ impl PlaygroundView {
if res.doc_mutated {
self.sync_after_database_mutation(before_sv, cx);
} else {
self.env_rev += 1;
cx.notify();
}
true
@@ -171,7 +168,8 @@ impl PlaygroundView {
/// Reconcile open database authoring popovers and `self.database_input` after a snapshot
/// refresh (Undo/Redo or remote collaborator edit).
pub(crate) fn sync_database_authoring_from_snapshot(&mut self) {
let block_ids: Vec<String> = self.flow.database_state.ui_states.keys().cloned().collect();
let states = self.flow.database_state.states();
let block_ids: Vec<String> = states.map(|(id, _)| id.clone()).collect();
for bid in block_ids {
let db_opt = self
.snapshot
@@ -213,12 +211,14 @@ impl PlaygroundView {
let Some(mut session) = self.database_input.take() else {
return;
};
let Some((desired_target, _, _)) = self.desired_database_inline_target() else {
self.env_rev += 1;
return;
};
if !session.target.same_slot(&desired_target) {
self.env_rev += 1;
if !self
.desired_database_inline_target()
.is_some_and(|(desired, _, _)| session.target.same_slot(&desired))
{
// The layout of the session's block can show the preedit of the session.
self.flow
.database_state
.mark_dirty(session.target.block_id());
return;
}
if let DatabaseInlineTarget::LiveRichCell {
@@ -29,6 +29,8 @@ mod tests_inline_and_popovers;
mod tests_kanban_and_richtext;
#[cfg(test)]
mod tests_scalar_edgeless_calendar;
#[cfg(test)]
mod tests_view_state_layout_reuse;
pub(crate) use dnd::DatabaseDropSettle;
pub(crate) use dnd_table::TableHoverState;
@@ -148,8 +150,8 @@ impl PlaygroundView {
let ids: Vec<String> = self
.flow
.database_state
.ui_states
.keys()
.states()
.map(|(id, _)| id)
.filter(|id| keep_block != Some(id.as_str()))
.cloned()
.collect();
@@ -176,28 +178,21 @@ impl PlaygroundView {
}
}
if keep_block.is_none() {
if self.database_drag.take().is_some() {
changed = true;
}
if self.database_input.take().is_some() {
changed = true;
}
if self.database_settle.take().is_some() {
changed = true;
}
if self.database_hover_table.take().is_some() {
changed = true;
}
} else if self
changed |= self.database_drag.take().is_some();
changed |= self.database_settle.take().is_some();
changed |= self.database_hover_table.take().is_some();
}
if let Some(session) = self
.database_input
.as_ref()
.is_some_and(|d| Some(d.target.block_id()) != keep_block)
.take_if(|d| keep_block != Some(d.target.block_id()))
{
self.database_input = None;
// The layout of the session's block can show the preedit of the session.
self.flow
.database_state
.mark_dirty(session.target.block_id());
changed = true;
}
if changed {
self.env_rev += 1;
cx.notify();
}
}
@@ -240,7 +235,6 @@ impl PlaygroundView {
self.send_page_update(&page_id, diff);
}
self.refresh_document();
self.env_rev += 1;
cx.notify();
}
@@ -338,7 +332,6 @@ impl PlaygroundView {
.authoring_mut(block_id)
.dismiss_popovers();
self.sync_database_authoring_input(window, cx);
self.env_rev += 1;
cx.notify();
if dismissed_calendar_inline {
return true;
@@ -374,7 +367,6 @@ impl PlaygroundView {
column_id: column_id.clone(),
preview_width_px: *current_width_px,
});
self.env_rev += 1;
if let Some(w) = window {
self.editor_focus.focus(w, cx);
}
@@ -451,7 +443,6 @@ impl PlaygroundView {
column_id: column_id.clone(),
value,
});
self.env_rev += 1;
if let Some(w) = window {
self.editor_focus.focus(w, cx);
}
@@ -562,7 +553,6 @@ impl PlaygroundView {
if res.doc_mutated {
self.sync_after_database_mutation(before_sv, cx);
} else {
self.env_rev += 1;
cx.notify();
}
self.sync_database_authoring_input(window, cx);
@@ -619,7 +609,6 @@ impl PlaygroundView {
column_id,
preview_width_px: next_w,
});
self.env_rev += 1;
cx.notify();
true
}
@@ -652,7 +641,6 @@ impl PlaygroundView {
column_id,
value,
});
self.env_rev += 1;
cx.notify();
true
}
@@ -739,7 +727,6 @@ impl PlaygroundView {
origin_day,
target_day: next_day,
});
self.env_rev += 1;
}
cx.notify();
true
@@ -717,7 +717,6 @@ impl PlaygroundView {
if res.doc_mutated {
self.sync_after_database_mutation(before_sv, cx);
} else {
self.env_rev += 1;
cx.notify();
}
self.sync_database_authoring_input(Some(window), cx);
@@ -356,8 +356,7 @@ fn narrow_calendar_capsule_inline_edit_follows_caret_and_hides_day_plus_while_ed
v.flow
.database_state
.set_calendar_selected_day(&db_id, Some(capsule_day));
v.flow.database_state.set_calendar_hovered_day(&db_id, None);
v.env_rev += 1;
v.flow.database_state.update_pointer_hover(None, None);
cx.notify();
})
.unwrap();
@@ -0,0 +1,444 @@
//! Layout passes after a change of the view state of one block. On a page of 10,000 paragraphs,
//! one database and one table, a pass lays out only the changed block: a view switch, a sideways
//! scroll, a toolbar panel, cell input with a composition, the pointer hover on a Calendar day
//! or a Kanban lane, a Kanban card drag with its commit, the table focus, and a touch swipe on
//! the view tabs of a right-to-left page. A tab scroll that only stops the reveal of the active
//! tab must also reach the layout.
use std::rc::Rc;
use blocksuite_editor::database::{ActiveToolbarPanel, DatabaseAuthoringHitKind};
use blocksuite_playground_doc::schema::{BlockSpec, ParagraphType};
use ui::{
Direction, EntityInputHandler, PlatformInput, TouchEvent, TouchId, TouchPhase, point, px,
};
use crate::{
FormFactor, HOME_PAGE_ID, PlaygroundOptions, PlaygroundTheme, PlaygroundView,
overlays::InlineTargetEnd, room_client::DocState,
};
use super::{
tests_dnd_motion::{mouse_down, mouse_move, mouse_up},
tests_inline_and_overflow::build_roadmap_doc,
tests_inline_and_popovers::open_authoring_window,
};
const PARAGRAPHS: usize = 10_000;
/// Laid-out bodies that are not the changed block: the title, each paragraph, and whichever of
/// the database and the table did not change.
const OTHER_BODIES: usize = PARAGRAPHS + 2;
type View<'a> = &'a mut PlaygroundView;
type Cx<'a, 'b> = &'a mut ui::Context<'b, PlaygroundView>;
/// The layout work that one step is allowed to cause.
#[derive(Clone, Copy, Debug)]
enum Pass {
/// The page keeps its layout.
None,
/// One pass lays out one block and reuses each other block.
OneBlock,
/// No pass, or a pass that lays out at most one block.
AtMostOneBlock,
}
impl Pass {
/// Compare with `(laid_out, reused)` of the pass that a step caused, if it caused one.
fn check(self, pass: Option<(usize, usize)>, step: &str) {
let ok = match (self, pass) {
(Pass::None | Pass::AtMostOneBlock, None) => true,
(Pass::OneBlock, Some(pass)) => pass == (1, OTHER_BODIES),
(Pass::AtMostOneBlock, Some((laid_out, reused))) => {
laid_out <= 1 && laid_out + reused == OTHER_BODIES + 1
}
_ => false,
};
assert!(ok, "{step}: expected {self:?}, got {pass:?}");
}
}
/// Add one table and 10,000 paragraphs to the note in one transaction.
fn add_table_and_paragraphs(state: &mut DocState, note_id: &str) {
let page = state.workspace.ensure_page(HOME_PAGE_ID).unwrap();
page.inner_mut()
.begin_tx(y_octo::SessionTxOrigin::Untracked)
.unwrap();
let rows = vec![vec!["A".to_string(), "B".to_string()]];
page.add_block("tbl", BlockSpec::Table { rows }, Some(note_id), None, 6)
.unwrap();
for index in 0..PARAGRAPHS {
page.add_block(
format!("para-{index}"),
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "A paragraph the pointer never changes.".into(),
},
Some(note_id),
None,
7,
)
.unwrap();
}
page.inner_mut().commit_tx().unwrap();
}
/// A page whose database `db` has ten views, so its tab strip is wider than a phone.
fn page_with_ten_view_database() -> DocState {
let mut state = DocState::new("ten-view-tabs", 311).unwrap();
state
.workspace
.create_page(HOME_PAGE_ID, "Tabs", 1)
.unwrap();
let page = state.workspace.ensure_page(HOME_PAGE_ID).unwrap();
let title = "Tabs".into();
page.add_block("root", BlockSpec::Page { title }, None, None, 1)
.unwrap();
page.add_block(
"note",
BlockSpec::Note { xywh: None },
Some("root"),
None,
2,
)
.unwrap();
let mut spec = PlaygroundView::showcase_database_spec();
let first = spec.views[0].clone();
spec.views = (0..10)
.map(|index| {
let mut view = first.clone();
view.id = format!("v-{index}");
view.name = format!("View {index}");
view
})
.collect();
page.add_block("db", BlockSpec::Database(spec), Some("note"), None, 3)
.unwrap();
state
}
/// A 390 x 844 phone window on `state` with a right-to-left root, after its first frames.
fn open_rtl_phone_window(
state: DocState,
) -> (
Rc<ui::HeadlessPlatform>,
ui::ApplicationHandle,
ui::WindowHandle<PlaygroundView>,
ui::HeadlessWindow,
) {
let options = PlaygroundOptions::for_form_factor(FormFactor::Phone);
let (platform, app, win, headless) = open_authoring_window(390, 844, options, state);
app.update(|cx| {
win.update(cx, |_, w, _| w.set_root_layout_direction(Direction::Rtl))
.unwrap()
});
for _ in 0..2 {
platform.run_until_parked();
headless.request_frame();
}
platform.run_until_parked();
(platform, app, win, headless)
}
#[test]
fn view_state_change_of_one_block_lays_out_only_that_block_among_10k_paragraphs() {
// A preview revision that another test changes starts a layout pass of its own.
let _global_lock = crate::GLOBAL_PREVIEW_PROVIDER_TEST_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let (mut state, db_id) = build_roadmap_doc();
add_table_and_paragraphs(&mut state, "p-note");
let (platform, app, win, headless) = open_authoring_window(
1280,
1000,
PlaygroundOptions {
theme: PlaygroundTheme::Light,
..Default::default()
},
state,
);
let tick = || {
platform.run_until_parked();
headless.request_frame();
platform.run_until_parked();
};
let layout = || app.update(|cx| win.read(cx).unwrap().flow_layout().expect("layout"));
// `(laid_out, reused)` of the layout pass that `action` caused, or `None` when the page
// kept its layout.
let pass_of = |action: &dyn Fn()| {
let before = layout();
action();
tick();
let after = layout();
(!Rc::ptr_eq(&before, &after)).then_some((after.stats.laid_out, after.stats.reused))
};
let update = |f: &dyn Fn(View<'_>, &mut ui::Window, Cx<'_, '_>)| {
app.update(|cx| win.update(cx, |v, w, cx| f(v, w, cx)).unwrap())
};
let hit_centers = |pred: &dyn Fn(&DatabaseAuthoringHitKind) -> bool| -> Vec<(f32, f32)> {
app.update(|cx| {
win.update(cx, |v, w, _| {
let kinds: Vec<_> = v
.flow
.database_authoring_hits(&db_id)
.iter()
.filter(|hit| pred(&hit.kind))
.map(|hit| hit.kind.clone())
.collect();
kinds
.iter()
.map(|kind| {
v.database_authoring_hit_screen_center(&db_id, w, |k| k == kind)
.expect("hit center")
})
.collect()
})
.unwrap()
})
};
tick();
assert_eq!(
layout().blocks.len(),
PARAGRAPHS + 3,
"title, database, table and paragraphs"
);
// 1. Entry points that change the view state of the database, in the Table view.
type Entry<'a> = (
&'a str,
&'a dyn Fn(View<'_>, &mut ui::Window, Cx<'_, '_>),
Pass,
);
let panel = |open: Option<ActiveToolbarPanel>| {
let db_id = db_id.clone();
move |v: View<'_>, _: &mut ui::Window, cx: Cx<'_, '_>| {
v.update_database_authoring(&db_id, |a| a.toolbar_panel = open, cx)
}
};
let entries: [Entry<'_>; 8] = [
(
"scroll the wide table sideways",
&|v, _, cx| v.scroll_database_x(&db_id, 24.0, cx),
Pass::None,
),
(
"open the Filter panel",
&panel(Some(ActiveToolbarPanel::Filter)),
Pass::OneBlock,
),
("close the Filter panel", &panel(None), Pass::OneBlock),
(
"open the title cell editor",
&|v, w, cx| v.focus_database_first_editable_cell(&db_id, "r2", Some(w), cx),
Pass::OneBlock,
),
(
"compose in the cell",
&|v, w, cx| v.replace_and_mark_text_in_range(None, "ni", None, w, cx),
Pass::OneBlock,
),
(
"commit the composition",
&|v, w, cx| v.replace_text_in_range(None, "你", w, cx),
Pass::OneBlock,
),
(
"close the cell editor",
&|v, w, cx| {
v.finish_inline_targets(InlineTargetEnd::CommitPreedit, Some(w), Some(cx));
},
Pass::OneBlock,
),
(
"focus a table cell",
&|v, w, cx| {
v.focus_table_cell("tbl".into(), "row-0".into(), "col-0".into(), None, w, cx)
},
Pass::OneBlock,
),
];
for (step, entry, expected) in entries {
expected.check(pass_of(&|| update(entry)), step);
}
Pass::OneBlock.check(
pass_of(&|| {
update(&|v, w, cx| {
v.finish_inline_targets(InlineTargetEnd::CommitPreedit, Some(w), Some(cx));
})
}),
"leave the table",
);
// 2. A view switch, then the pointer hover on Calendar days and on Kanban lanes.
type IsTarget = fn(&DatabaseAuthoringHitKind) -> bool;
let hover_views: [(&str, IsTarget); 2] = [
("v-cal", |kind| {
matches!(kind, DatabaseAuthoringHitKind::CalendarDayDropTarget { .. })
}),
("v-unnamed-kanban", |kind| {
matches!(kind, DatabaseAuthoringHitKind::KanbanLaneDropTarget { .. })
}),
];
for (view_id, is_target) in hover_views {
Pass::OneBlock.check(
pass_of(&|| update(&|v, _, cx| v.set_database_active_view(&db_id, view_id, cx))),
&format!("{view_id}: show the view"),
);
let targets = hit_centers(&is_target);
assert!(targets.len() >= 2, "{view_id}: {} targets", targets.len());
let (first, second) = (targets[0], targets[1]);
let off_block = (2.0, first.1);
let moves = [
("enter the first target", first, Pass::OneBlock),
(
"stay in the first target",
(first.0 + 3.0, first.1 + 3.0),
Pass::None,
),
("go to the second target", second, Pass::OneBlock),
("leave the database", off_block, Pass::OneBlock),
(
"stay off the database",
(off_block.0, off_block.1 + 9.0),
Pass::None,
),
];
for (step, (x, y), expected) in moves {
expected.check(
pass_of(&|| mouse_move(&headless, x, y, false)),
&format!("{view_id}: {step}"),
);
}
}
// 3. A Kanban card drag to another lane and its commit, still in the Kanban view.
let card = hit_centers(
&|kind| matches!(kind, DatabaseAuthoringHitKind::KanbanCardDragRegion { row_id, .. } if row_id == "r1"),
)[0];
let lanes =
hit_centers(&|kind| matches!(kind, DatabaseAuthoringHitKind::KanbanLaneDropTarget { .. }));
let lane = *lanes
.iter()
.max_by(|a, b| (a.0 - card.0).abs().total_cmp(&(b.0 - card.0).abs()))
.unwrap();
let database = || app.update(|cx| win.read(cx).unwrap().database_snapshot_data(&db_id));
let before_drag = database();
let mut passes = vec![pass_of(&|| mouse_down(&headless, card.0, card.1))];
for step in 1..=4 {
let t = step as f32 / 4.0;
let (x, y) = (
card.0 + (lane.0 - card.0) * t,
card.1 + (lane.1 - card.1) * t,
);
passes.push(pass_of(&|| mouse_move(&headless, x, y, true)));
}
passes.push(pass_of(&|| mouse_up(&headless, lane.0, lane.1)));
assert_ne!(
database(),
before_drag,
"the drag must move the card to the other lane"
);
assert!(
passes.contains(&Some((1, OTHER_BODIES))),
"the drag must lay the database out again: {passes:?}"
);
for pass in &passes {
Pass::AtMostOneBlock.check(*pass, &format!("a pass of the card drag in {passes:?}"));
}
}
#[test]
fn touch_swipe_on_rtl_view_tabs_lays_out_only_the_database_among_10k_paragraphs() {
// A preview revision that another test changes starts a layout pass of its own.
let _global_lock = crate::GLOBAL_PREVIEW_PROVIDER_TEST_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let mut state = page_with_ten_view_database();
add_table_and_paragraphs(&mut state, "note");
let (platform, app, win, headless) = open_rtl_phone_window(state);
let tick = || {
platform.run_until_parked();
headless.request_frame();
platform.run_until_parked();
};
let layout = || app.update(|cx| win.read(cx).unwrap().flow_layout().expect("layout"));
let tabs_scroll = || {
app.update(|cx| {
let view = win.read(cx).unwrap();
view.flow.database_state.state_for("db").view_tabs_scroll_px
})
};
let strip_y = crate::TOPBAR_HEIGHT + layout().block("db").expect("database").y + 54.0;
let touch = |phase: TouchPhase, x: f32| {
headless.dispatch_input(PlatformInput::Touch(TouchEvent {
id: TouchId(7),
phase,
position: point(px(x), px(strip_y)),
predicted_position: None,
force: None,
}));
tick();
};
// The finger moves right three times. On a right-to-left page that shows later views.
touch(TouchPhase::Started, 80.0);
let mut offsets = vec![tabs_scroll()];
for x in [120.0, 160.0, 200.0] {
let before = layout();
touch(TouchPhase::Moved, x);
let after = layout();
assert!(!Rc::ptr_eq(&before, &after), "move to {x}: no layout pass");
Pass::OneBlock.check(
Some((after.stats.laid_out, after.stats.reused)),
&format!("move to {x}"),
);
offsets.push(tabs_scroll());
}
touch(TouchPhase::Ended, 200.0);
assert_eq!(
offsets,
[0, 40, 80, 120],
"tab strip offset after each move"
);
}
#[test]
fn tabs_scroll_that_stays_at_zero_after_a_reveal_lays_out_the_database_again() {
let mut state = page_with_ten_view_database();
let other = PlaygroundView::showcase_database_spec();
let other_view = other.views[1].id.clone();
let page = state.workspace.ensure_page(HOME_PAGE_ID).unwrap();
page.add_block("other", BlockSpec::Database(other), Some("note"), None, 4)
.unwrap();
let (platform, app, win, headless) = open_rtl_phone_window(state);
let tick = || {
platform.run_until_parked();
headless.request_frame();
platform.run_until_parked();
};
let shown_tabs = || {
app.update(|cx| {
let view = win.read(cx).unwrap();
view.flow.database_view_tabs_metrics("db")
})
};
app.update(|cx| {
win.update(cx, |v, _, cx| v.set_database_active_view("db", "v-9", cx))
.unwrap()
});
tick();
let (revealed, max) = shown_tabs();
assert!(revealed > 0, "the reveal must show the last tab");
// The scroll stays at the stored offset 0 and only stops the reveal. The pass that the
// other database starts must lay out `db` again, without the reveal.
app.update(|cx| {
win.update(cx, |v, _, cx| {
assert!(v.flow.database_state.scroll_view_tabs("db", 1, max));
v.set_database_active_view("other", &other_view, cx);
})
.unwrap()
});
tick();
assert_eq!(shown_tabs().0, 0, "the tab strip must leave the reveal");
}
@@ -34,15 +34,39 @@ fn extract_page_snippet(snap: &PageSnapshot) -> String {
}
use crate::{
HOME_PAGE_ID, PILL_EDGELESS_X, PILL_PAGE_X, PILL_TRANSITION_MS, PlaygroundMode, PlaygroundView,
SCROLL_LINE,
block_flow::{FlowInput, FlowLayout, ImageSlot, decode_image},
HOME_PAGE_ID, PILL_EDGELESS_X, PILL_PAGE_X, PILL_TRANSITION_MS, PlaygroundMode,
PlaygroundTheme, PlaygroundView, SCROLL_LINE,
block_flow::{FlowInput, FlowLayout, FormFactor, ImageSlot, decode_image},
directory,
overlays::InlineTargetEnd,
room_client::RoomCommand,
view_room::BlobFetchState,
};
/// The inputs of one cached page layout. Equation draft, database view state and table focus
/// are local to one block: they are not in `FlowInput::env_rev`, which every block hashes.
#[derive(Clone, PartialEq)]
pub(crate) struct LayoutKey {
doc_rev: u64,
draft_hash: u64,
db_revision: u64,
table_focus_hash: u64,
environment: LayoutEnvironment,
}
/// The inputs that every block reads. A pass reuses unchanged blocks only while these are equal.
#[derive(Clone, PartialEq)]
struct LayoutEnvironment {
width_bits: u32,
theme: PlaygroundTheme,
env_rev: u64,
preview_rev: u64,
is_rtl: bool,
form_factor: FormFactor,
utc_offset_minutes: i32,
local_day: i64,
}
impl PlaygroundView {
pub(crate) fn capture_reading_anchor(&mut self) {
if self.reading_anchor.is_none() && self.scroll_y > 0.0 {
@@ -621,7 +645,6 @@ impl PlaygroundView {
max_px,
)
{
self.env_rev += 1;
cx.notify();
return;
}
@@ -683,70 +706,61 @@ impl PlaygroundView {
latex: editor.committed_draft().to_string(),
},
});
let draft_hash = {
let mut h = std::collections::hash_map::DefaultHasher::new();
equation_draft.hash(&mut h);
h.finish()
};
let focused_table_block = (!self.table_is_readonly())
.then(|| self.table_cell.as_ref().map(|c| c.block_id.clone()))
let focused_table = (!self.table_is_readonly())
.then(|| self.table_cell.as_ref().map(|c| c.block_id.as_str()))
.flatten();
if self.flow.focused_table_block != focused_table_block {
self.flow.focused_table_block = focused_table_block;
self.env_rev = self.env_rev.wrapping_add(1);
fn hash_of(value: impl Hash) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
value.hash(&mut h);
h.finish()
}
let effective_env_rev = self
.env_rev
.wrapping_add(self.flow.database_state.revision());
let key = (
self.doc_rev,
width.to_bits(),
self.theme,
effective_env_rev,
preview_rev,
let (draft_hash, table_focus_hash) = (hash_of(&equation_draft), hash_of(focused_table));
let key = LayoutKey {
doc_rev: self.doc_rev,
draft_hash,
is_rtl,
self.form_factor,
utc_offset_minutes,
local_day,
);
db_revision: self.flow.database_state.revision(),
table_focus_hash,
environment: LayoutEnvironment {
width_bits: width.to_bits(),
theme: self.theme,
env_rev: self.env_rev,
preview_rev,
is_rtl,
form_factor: self.form_factor,
utc_offset_minutes,
local_day,
},
};
if let Some((cached, layout)) = &self.layout
&& *cached == key
{
return Some(layout.clone());
}
let snapshot = self.preedit_snapshot().map(Rc::new).unwrap_or(snapshot);
let mut dirty = self.dirty_text.take().filter(|_| {
self.layout.as_ref().is_some_and(|(old, _)| {
old.1 == key.1
&& old.2 == key.2
&& old.3 == key.3
&& old.4 == key.4
&& old.6 == key.6
&& old.7 == key.7
&& old.8 == key.8
&& old.9 == key.9
})
});
// If only the live equation draft changed, mark just the target block dirty so sibling
// blocks stay cached (preserving single-keystroke relayout == 1).
if let Some((old, _)) = &self.layout
&& old.5 != key.5
{
if let Some(ref mut set) = dirty {
if let Some(draft) = &equation_draft {
let bid = match draft {
crate::block_flow::EquationDraft::Block { block_id, .. }
| crate::block_flow::EquationDraft::Inline { block_id, .. } => {
block_id.clone()
}
};
set.insert(bid);
} else {
// Equation editor closed; full pass reconciles the previously overridden block.
dirty = None;
}
}
let old = self.layout.as_ref().map(|(old, _)| old);
let draft_changed = old.is_some_and(|old| old.draft_hash != key.draft_hash);
let same_environment = old.is_some_and(|old| old.environment == key.environment);
let mut dirty = self.dirty_text.take().filter(|_| same_environment);
if draft_changed {
// A changed equation draft marks only its block dirty, so one keystroke lays out
// one block. A closed equation editor names no block: the pass lays out all blocks.
dirty = dirty.zip(equation_draft.as_ref()).map(|(mut set, draft)| {
let (crate::block_flow::EquationDraft::Block { block_id, .. }
| crate::block_flow::EquationDraft::Inline { block_id, .. }) = draft;
set.insert(block_id.clone());
set
});
}
// A pass over the changed blocks also lays out each database block whose view state
// changed and the tables that lost and got the focus. It reuses all other blocks.
let mut db_dirty = self.flow.database_state.take_dirty_blocks();
if self.flow.focused_table_block.as_deref() != focused_table {
db_dirty.extend(self.flow.focused_table_block.take());
self.flow.focused_table_block = focused_table.map(str::to_string);
db_dirty.extend(self.flow.focused_table_block.clone());
}
if let Some(set) = &mut dirty {
set.append(&mut db_dirty);
}
self.flow.database_state.mobile_readonly = self.database_readonly;
self.flow.database_state.clock_ms = now_ms;
@@ -765,7 +779,7 @@ impl PlaygroundView {
pdf_previews: Some(&self.pdf_previews),
doc_directory: Some(doc_dir),
equation_draft: equation_draft.as_ref(),
env_rev: effective_env_rev,
env_rev: self.env_rev,
direction: window.layout_direction(),
form_factor: self.form_factor,
utc_offset_minutes,
+7 -14
View File
@@ -168,19 +168,9 @@ pub(crate) const THEME_TOGGLE_SIZE: f32 = 32.0;
pub(crate) const TOPBAR_EDGE: f32 = 12.0;
pub(crate) const SCROLL_LINE: f32 = 20.0;
type LayoutKey = (
u64,
u32,
PlaygroundTheme,
u64,
u64,
u64,
bool,
block_flow::FormFactor,
i32,
i64,
);
/// Each test that changes the global preview providers or a preview revision holds this lock.
/// So does each test that counts the blocks of a layout pass, because a changed revision
/// starts a layout pass in every view.
#[cfg(test)]
pub(crate) static GLOBAL_PREVIEW_PROVIDER_TEST_LOCK: std::sync::Mutex<()> =
std::sync::Mutex::new(());
@@ -257,7 +247,7 @@ pub struct PlaygroundView {
pub(crate) doc_epoch: u64,
pub(crate) env_rev: u64,
pub(crate) flow: BlockFlow,
pub(crate) layout: Option<(LayoutKey, Rc<FlowLayout>)>,
pub(crate) layout: Option<(layout_cache::LayoutKey, Rc<FlowLayout>)>,
pub(crate) scroll_y: f32,
pub(crate) max_scroll: f32,
/// Window size of the latest frame, in logical pixels.
@@ -1608,6 +1598,9 @@ pub(crate) mod tests {
#[test]
fn editing_one_block_lays_out_only_that_block_again() {
let _global_lock = crate::GLOBAL_PREVIEW_PROVIDER_TEST_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let session = open(1280, 800, PlaygroundOptions::default());
session.frame();
let first = session.view(|view, _| view.flow_layout().expect("layout"));
@@ -245,7 +245,6 @@ impl PlaygroundView {
.authoring_mut(block_id)
.dismiss_popovers();
self.sync_database_authoring_input(None, cx);
self.env_rev += 1;
cx.notify();
}
@@ -261,7 +260,6 @@ impl PlaygroundView {
self.flow
.database_state
.step_calendar_month(block_id, current, delta_months);
self.env_rev += 1;
cx.notify();
}
@@ -276,7 +274,6 @@ impl PlaygroundView {
self.flow
.database_state
.set_calendar_month(block_id, Some((y as i32, m)));
self.env_rev += 1;
cx.notify();
}
@@ -291,9 +288,7 @@ impl PlaygroundView {
if self.flow.database_state.mobile_readonly != readonly {
self.flow.database_state.mobile_readonly = readonly;
if !readonly {
for state in self.flow.database_state.ui_states.values_mut() {
state.mobile_readonly_notice = false;
}
self.flow.database_state.clear_mobile_readonly_notices();
}
self.env_rev += 1;
cx.notify();
@@ -375,7 +370,6 @@ impl PlaygroundView {
let hits = self.flow.database_hits(block_id);
if hits.is_empty() {
if self.flow.database_state.close_more_views(block_id) {
self.env_rev += 1;
cx.notify();
return true;
}
@@ -405,7 +399,6 @@ impl PlaygroundView {
.cloned();
let Some(target) = target else {
if self.flow.database_state.close_more_views(block_id) {
self.env_rev += 1;
cx.notify();
return true;
}
@@ -421,7 +414,6 @@ impl PlaygroundView {
}
database::DatabaseHitKind::ToggleMoreViews => {
self.flow.database_state.toggle_more_views(block_id);
self.env_rev += 1;
cx.notify();
true
}
@@ -441,7 +433,6 @@ impl PlaygroundView {
self.flow
.database_state
.set_calendar_selected_day(block_id, Some(*day_index));
self.env_rev += 1;
cx.notify();
true
}
@@ -452,7 +443,6 @@ impl PlaygroundView {
}
database::DatabaseHitKind::ToggleGroup { group_key } => {
self.flow.database_state.toggle_group(block_id, group_key);
self.env_rev += 1;
cx.notify();
true
}
@@ -461,7 +451,6 @@ impl PlaygroundView {
self.flow
.database_state
.set_mobile_readonly_notice(block_id, true);
self.env_rev += 1;
cx.notify();
true
}
@@ -475,7 +464,6 @@ impl PlaygroundView {
self.flow
.database_state
.set_mobile_readonly_notice(block_id, true);
self.env_rev += 1;
cx.notify();
}
return true;
@@ -495,7 +483,6 @@ impl PlaygroundView {
self.flow
.database_state
.set_mobile_readonly_notice(block_id, true);
self.env_rev += 1;
cx.notify();
}
return true;