diff --git a/packages/frontend/mobile/AGENTS.md b/packages/frontend/mobile/AGENTS.md index b6296ab33b..5dad07d021 100644 --- a/packages/frontend/mobile/AGENTS.md +++ b/packages/frontend/mobile/AGENTS.md @@ -20,7 +20,7 @@ - Keep `Backlinks` outside the `Navigation("Breadcrumb")` landmark and synchronize `AccessibilityTree` on frame 1 in production builds (without `harness` feature gates in shipping views). - Change documents only through `WorkspaceData::docs_mut`, `doc_mut`, `set_doc_crdt_update`, and `remove_doc_crdt_update`. Their process-wide revision stamps key the cached search hits, drawer sections, Explorer rows, editor directory snapshot, and bridge sync, so a direct write would leave them stale. -- Explorer lists mount only the rows that `explorer_model::row_window` puts inside the viewport plus overscan, and the accessibility tree publishes rows from the same model and window. +- Explorer and Home document lists mount only the rows that `row_window` / `row_window_overscan` puts inside the viewport plus overscan, and the accessibility tree publishes rows from the same cached models and windows. - Keep every `.rs` file at or below 800 non-test lines, zero `super::super::`, and zero `is_headless` branches. ## Verification diff --git a/packages/frontend/mobile/src/a11y/mod.rs b/packages/frontend/mobile/src/a11y/mod.rs index 35c9ca4e2f..8b7a6d5181 100644 --- a/packages/frontend/mobile/src/a11y/mod.rs +++ b/packages/frontend/mobile/src/a11y/mod.rs @@ -206,30 +206,30 @@ pub fn build_accessibility_tree_with_layout( ); main_children.push(settings_id); - for (idx, doc) in state - .active_workspace() - .docs() - .iter() - .filter(|d| !d.trashed && d.is_favorite) - .take(2) - .enumerate() - { - let fav_id = format!("mobile.home.fav.{}", doc.id); + let model = crate::home_model::home_model(state); + let effective_h = (viewport_height - safe_top - safe_bottom).max(160.0); + let g = crate::home_model::HomeGeometry::new( + effective_h, + !model.favorites.is_empty(), + model.recent.len(), + ); + for (idx, (doc_id, title)) in model.favorites.iter().enumerate() { + let fav_id = format!("mobile.home.fav.{doc_id}"); let card_w = ((content_w - 42.0) * 0.5).max(80.0); nodes.insert( fav_id.clone(), AccessibilityNode { id: fav_id.clone(), role: AccessibilityRole::Button, - name: doc.display_title(locale), + name: title.clone(), value: None, state: AccessibilityState::default(), focused: false, bounds: AccessibilityBounds { x: content_left + 16.0 + (idx as f32) * (card_w + 10.0), - y: safe_top + 92.0, + y: safe_top + 56.0 + g.pad + 25.0, width: card_w, - height: 80.0, + height: g.fav_card_h, }, children: Vec::new(), }, @@ -237,28 +237,36 @@ pub fn build_accessibility_tree_with_layout( main_children.push(fav_id); } - for (idx, doc) in state - .active_workspace() - .docs() - .iter() - .filter(|d| !d.trashed) - .enumerate() - { + let scroll_y = crate::home_model::clamp_scroll(state.home_scroll_y, g.max_scroll); + let window = crate::explorer_model::row_window_overscan( + g.shown_docs, + g.row_h, + g.list_top, + scroll_y, + g.avail_h, + g.overscan_px, + ); + for idx in window.visible_range { + let doc = &model.recent[idx]; + let top = g.list_top + (idx as f32) * g.row_h; + if !crate::explorer_model::fully_visible(top, g.row_h, scroll_y, g.avail_h) { + continue; + } let doc_node_id = format!("mobile.home.doc.{}", doc.id); nodes.insert( doc_node_id.clone(), AccessibilityNode { id: doc_node_id.clone(), role: AccessibilityRole::Button, - name: doc.display_title(locale), + name: doc.title.clone(), value: None, state: AccessibilityState::default(), focused: false, bounds: AccessibilityBounds { x: content_left + 16.0, - y: safe_top + 206.0 + (idx as f32) * 72.0, + y: safe_top + 56.0 + top - scroll_y, width: (content_w - 32.0).max(44.0), - height: 72.0, + height: g.row_h, }, children: Vec::new(), }, diff --git a/packages/frontend/mobile/src/bin/mobile_harness/scale.rs b/packages/frontend/mobile/src/bin/mobile_harness/scale.rs index a0534e2a1c..c5c02710ad 100644 --- a/packages/frontend/mobile/src/bin/mobile_harness/scale.rs +++ b/packages/frontend/mobile/src/bin/mobile_harness/scale.rs @@ -81,6 +81,8 @@ fn measure(work: impl FnOnce()) -> (f64, u64) { const SIZES: [usize; 3] = [10, 100, 1_000]; const FRAMES: usize = 24; const SCALE_FOLDER: &str = "f-scale"; +/// Maximum Home document rows mounted at `390×844` (`ceil(724 / 72) + 1 + 2 * 2` overscan). +const MAX_HOME_MOUNTED_ROWS: u64 = 16; fn summary(samples: &[(f64, u64)]) -> Value { let mut ms: Vec = samples.iter().map(|s| s.0).collect(); @@ -142,11 +144,13 @@ fn frames(session: &MobileSession, mut step: impl FnMut(&mut MobileAppState)) -> let stats = session.update_state(|s| s.work_stats())?; let mut out = summary(&samples); out["explorer_builds"] = json!(stats.explorer_builds - stats_before.explorer_builds); + out["home_builds"] = json!(stats.home_builds - stats_before.home_builds); out["search_builds"] = json!(stats.search_builds - stats_before.search_builds); out["drawer_builds"] = json!(stats.drawer_builds - stats_before.drawer_builds); out["index_builds"] = json!(stats.index_builds - stats_before.index_builds); out["breadcrumb_builds"] = json!(stats.breadcrumb_builds - stats_before.breadcrumb_builds); out["explorer_mounted_rows"] = json!(stats.explorer_mounted_rows); + out["home_mounted_rows"] = json!(stats.home_mounted_rows); Ok(out) } @@ -155,6 +159,18 @@ fn route_cases(n: usize) -> Result { session.draw(); let mut out = json!({}); + session.update_state(|s| s.switch_tab(MobileTab::Home, 0.0))?; + session.draw(); + let home_report = frames(&session, |s| s.scroll_home_by(144.0, f32::MAX))?; + let home_mounted = home_report["home_mounted_rows"] + .as_u64() + .unwrap_or(u64::MAX); + anyhow::ensure!( + home_mounted <= MAX_HOME_MOUNTED_ROWS, + "home mounted rows {home_mounted} exceeded bound {MAX_HOME_MOUNTED_ROWS} at n={n}" + ); + out["home"] = home_report; + session.update_state(|s| s.switch_tab(MobileTab::Explorer, 0.0))?; session.draw(); out["explorer"] = frames(&session, |s| s.scroll_explorer_by(138.0, f32::MAX))?; diff --git a/packages/frontend/mobile/src/explorer_model.rs b/packages/frontend/mobile/src/explorer_model.rs index 775ea74843..64606d1826 100644 --- a/packages/frontend/mobile/src/explorer_model.rs +++ b/packages/frontend/mobile/src/explorer_model.rs @@ -407,6 +407,19 @@ pub(crate) fn row_window( list_top: f32, scroll_y: f32, avail_h: f32, +) -> VirtualWindow { + row_window_overscan(count, row_h, list_top, scroll_y, avail_h, OVERSCAN_PX) +} + +/// Rows of a `count`-row list starting at content offset `list_top` that intersect the scroll +/// viewport `[scroll_y, scroll_y + avail_h)`, with `overscan_px` on each side. +pub(crate) fn row_window_overscan( + count: usize, + row_h: f32, + list_top: f32, + scroll_y: f32, + avail_h: f32, + overscan_px: f32, ) -> VirtualWindow { let list = VirtualList::fixed(count, row_h); let total = list.total_height(); @@ -421,7 +434,7 @@ pub(crate) fn row_window( total_height: total, }; } - list.window(bottom - top, top, OVERSCAN_PX) + list.window(bottom - top, top, overscan_px) } /// Whether a row at content offset `top` with height `h` lies completely inside the viewport. diff --git a/packages/frontend/mobile/src/home_model.rs b/packages/frontend/mobile/src/home_model.rs new file mode 100644 index 0000000000..f83a4ee56b --- /dev/null +++ b/packages/frontend/mobile/src/home_model.rs @@ -0,0 +1,200 @@ +//! Cached Home document list and viewport geometry shared by `views::tabs` and `a11y`. + +use std::sync::Arc; + +use crate::{ + state::{MobileAppState, cached}, + strings::MobileLocale, +}; + +/// Header (`56`) plus tab bar (`64`) heights around the Home scroll viewport. +const CHROME_H: f32 = 56.0 + 64.0; +/// `text_size(12.0)` section label (`19.0`) plus `gap(6.0)` above the section body. +const SECTION_HEADER_H: f32 = 25.0; +/// Top and bottom `1.0` borders around `recent_list`. +const LIST_BORDER_H: f32 = 2.0; +/// Maximum number of favorite cards rendered on Home. +const HOME_FAVORITES: usize = 2; + +/// One recent-document row on Home. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct HomeDocRow { + pub id: String, + pub title: String, + pub body_preview: String, +} + +/// Cached favorites and non-trashed recent documents of the active workspace. +#[derive(Debug, Default)] +pub(crate) struct HomeModel { + pub favorites: Vec<(String, String)>, + pub recent: Vec, +} + +pub(crate) struct HomeKey { + workspace_id: String, + locale: MobileLocale, + docs_rev: u64, +} + +impl HomeKey { + fn matches(&self, state: &MobileAppState) -> bool { + let ws = state.active_workspace(); + self.docs_rev == ws.docs_revision() + && self.locale == state.locale() + && self.workspace_id == ws.scope.workspace_id + } +} + +/// Cached Home favorites and document rows; rebuilt only when documents, workspace, or locale change. +pub(crate) fn home_model(state: &MobileAppState) -> Arc { + let ws = state.active_workspace(); + let locale = state.locale(); + let docs_rev = ws.docs_revision(); + cached( + &ws.derived.home, + ws.derived.home_builds(), + |key| key.matches(state), + || { + let mut favorites = Vec::with_capacity(HOME_FAVORITES); + let mut recent = Vec::new(); + for doc in ws.docs() { + if doc.trashed { + continue; + } + let title = doc.display_title(locale); + if doc.is_favorite && favorites.len() < HOME_FAVORITES { + favorites.push((doc.id.clone(), title.clone())); + } + recent.push(HomeDocRow { + id: doc.id.clone(), + title, + body_preview: doc.body_preview.clone(), + }); + } + let key = HomeKey { + workspace_id: ws.scope.workspace_id.clone(), + locale, + docs_rev, + }; + (key, HomeModel { favorites, recent }) + }, + ) +} + +/// Content geometry of the Home scroll viewport for `effective_h` and document counts. +#[derive(Clone, Copy, Debug)] +pub(crate) struct HomeGeometry { + pub compact: bool, + pub tight_portrait: bool, + pub row_h: f32, + pub fav_card_h: f32, + pub pad: f32, + pub gap: f32, + pub avail_h: f32, + pub shown_docs: usize, + pub list_top: f32, + pub overscan_px: f32, + pub max_scroll: f32, +} + +impl HomeGeometry { + pub(crate) fn new(effective_h: f32, has_favorites: bool, doc_count: usize) -> Self { + let compact = effective_h < 460.0; + let tight_portrait = !compact && effective_h < 620.0; + let row_h = if compact { + 46.0 + } else if tight_portrait { + 78.0 + } else { + 84.0 + }; + let fav_card_h = if compact { 64.0 } else { 87.0 }; + let avail_h = (effective_h - CHROME_H).max(44.0); + let pad = if compact || tight_portrait { + 10.0 + } else { + 16.0 + }; + let gap = if tight_portrait { 8.0 } else { 14.0 }; + let fav_h = SECTION_HEADER_H + if has_favorites { fav_card_h } else { 0.0 }; + let shown_docs = if compact { doc_count.min(2) } else { doc_count }; + let recent_h = SECTION_HEADER_H + (shown_docs as f32) * row_h + LIST_BORDER_H; + let content_h = if compact { + pad * 2.0 + fav_h.max(recent_h) + } else { + pad * 2.0 + fav_h + gap + recent_h + }; + let list_top = if compact { + pad + SECTION_HEADER_H + 1.0 + } else { + pad + fav_h + gap + SECTION_HEADER_H + 1.0 + }; + Self { + compact, + tight_portrait, + row_h, + fav_card_h, + pad, + gap, + avail_h, + shown_docs, + list_top, + overscan_px: 2.0 * row_h, + max_scroll: (content_h - avail_h).max(0.0), + } + } +} + +/// Clamp `scroll_y` into `0.0..=max_scroll`, resetting non-finite values to `0.0`. +pub(crate) fn clamp_scroll(scroll_y: f32, max_scroll: f32) -> f32 { + if scroll_y.is_finite() { + scroll_y.clamp(0.0, max_scroll.max(0.0)) + } else { + 0.0 + } +} + +#[cfg(test)] +mod tests { + use super::{HomeGeometry, clamp_scroll}; + use crate::explorer_model::row_window_overscan; + + #[test] + fn home_window_mounts_only_visible_rows_and_clamps_non_finite_or_overshot_scroll() { + // (doc_count, viewport_h, scroll_y, expected_range, expected_clamped) + let cases = [ + (0usize, 844.0_f32, 0.0_f32, 0..0, 0.0_f32), + (3, 844.0, 0.0, 0..3, 0.0), + (3, 844.0, 20_000.0, 0..3, 0.0), + (3, 844.0, f32::NAN, 0..3, 0.0), + (1_000, 844.0, 0.0, 0..9, 0.0), + (1_000, 844.0, 20_000.0, 234..247, 20_000.0), + (1_000, 844.0, 1.0e9, 989..1_000, 83_461.0), + (1_000, 390.0, 20_000.0, 0..2, 0.0), + ]; + for (count, vp_h, raw_scroll, expected_range, expected_scroll) in cases { + let g = HomeGeometry::new(vp_h, true, count); + let clamped = clamp_scroll(raw_scroll, g.max_scroll); + assert_eq!(clamped, expected_scroll, "count={count} vp_h={vp_h}"); + let win = row_window_overscan( + g.shown_docs, + g.row_h, + g.list_top, + clamped, + g.avail_h, + g.overscan_px, + ); + assert_eq!( + win.visible_range, expected_range, + "count={count} vp_h={vp_h}" + ); + assert_eq!( + win.leading_spacer + + (win.visible_range.len() as f32) * g.row_h + + win.trailing_spacer, + (g.shown_docs as f32) * g.row_h + ); + } + } +} diff --git a/packages/frontend/mobile/src/lib.rs b/packages/frontend/mobile/src/lib.rs index 95639fe4c5..e41ea73b1d 100644 --- a/packages/frontend/mobile/src/lib.rs +++ b/packages/frontend/mobile/src/lib.rs @@ -11,6 +11,7 @@ pub mod a11y; #[cfg(not(target_family = "wasm"))] mod connected_workspace; mod explorer_model; +mod home_model; mod shell_actions; pub mod showcase; pub mod state; diff --git a/packages/frontend/mobile/src/state/derived.rs b/packages/frontend/mobile/src/state/derived.rs index bc7cabdedc..2ee869fb98 100644 --- a/packages/frontend/mobile/src/state/derived.rs +++ b/packages/frontend/mobile/src/state/derived.rs @@ -15,7 +15,7 @@ use std::collections::BTreeMap; use affine_client::{SearchDocument, SearchHit, WorkspaceBreadcrumbSnapshot}; use super::MobileAppState; -use crate::{explorer_model::ExplorerModel, strings::MobileLocale}; +use crate::{explorer_model::ExplorerModel, home_model::HomeModel, strings::MobileLocale}; /// Most search hits the shell shows. pub(crate) const SEARCH_HIT_LIMIT: usize = 20; @@ -35,10 +35,14 @@ pub struct WorkStats { pub drawer_builds: u64, /// Explorer list builds. pub explorer_builds: u64, + /// Home list builds. + pub home_builds: u64, /// Breadcrumb snapshot and backlink clock table builds. pub breadcrumb_builds: u64, /// List rows that the last Explorer frame built. pub explorer_mounted_rows: u64, + /// Document rows that the last Home frame built. + pub home_mounted_rows: u64, } /// `(favorites, recent, all docs)` drawer rows of `(doc_id, display title)`, capped at the @@ -89,6 +93,7 @@ pub(crate) struct DerivedCache { search: Slot>, drawer: Slot, pub(crate) explorer: Slot, + pub(crate) home: Slot, breadcrumb: Slot, live_clocks: Slot>, index_builds: AtomicU64, @@ -96,7 +101,9 @@ pub(crate) struct DerivedCache { search_builds: AtomicU64, drawer_builds: AtomicU64, explorer_builds: AtomicU64, + home_builds: AtomicU64, explorer_mounted_rows: AtomicU64, + home_mounted_rows: AtomicU64, } /// A cloned slice starts with empty caches and zero counters. @@ -142,8 +149,10 @@ impl DerivedCache { search_builds: self.search_builds.load(Ordering::Relaxed), drawer_builds: self.drawer_builds.load(Ordering::Relaxed), explorer_builds: self.explorer_builds.load(Ordering::Relaxed), + home_builds: self.home_builds.load(Ordering::Relaxed), breadcrumb_builds: self.breadcrumb_builds.load(Ordering::Relaxed), explorer_mounted_rows: self.explorer_mounted_rows.load(Ordering::Relaxed), + home_mounted_rows: self.home_mounted_rows.load(Ordering::Relaxed), } } @@ -155,10 +164,18 @@ impl DerivedCache { &self.explorer_builds } + pub(crate) fn home_builds(&self) -> &AtomicU64 { + &self.home_builds + } + pub(crate) fn record_explorer_mounted_rows(&self, rows: usize) { self.explorer_mounted_rows .store(rows as u64, Ordering::Relaxed); } + + pub(crate) fn record_home_mounted_rows(&self, rows: usize) { + self.home_mounted_rows.store(rows as u64, Ordering::Relaxed); + } } impl MobileAppState { diff --git a/packages/frontend/mobile/src/state/mod.rs b/packages/frontend/mobile/src/state/mod.rs index 7218256bd6..5a8739dfc6 100644 --- a/packages/frontend/mobile/src/state/mod.rs +++ b/packages/frontend/mobile/src/state/mod.rs @@ -308,6 +308,8 @@ impl MobileAppState { self.pending_delete_target = None; self.explorer_scroll_y = 0.0; self.explorer_scroll_by_seq.clear(); + self.home_scroll_y = 0.0; + self.search_scroll_y = 0.0; self.sync_route_from_history(); self.close_sheet(now_ms); } diff --git a/packages/frontend/mobile/src/state_ops.rs b/packages/frontend/mobile/src/state_ops.rs index 5d8db2a734..e8d6dac8a7 100644 --- a/packages/frontend/mobile/src/state_ops.rs +++ b/packages/frontend/mobile/src/state_ops.rs @@ -33,6 +33,12 @@ impl MobileAppState { &self.active_workspace().scope.workspace_id } + /// Adjust `home_scroll_y` by `delta_y` and clamp to `0.0..=max_scroll`. + pub fn scroll_home_by(&mut self, delta_y: f32, max_scroll: f32) { + let current = crate::home_model::clamp_scroll(self.home_scroll_y, max_scroll); + self.home_scroll_y = crate::home_model::clamp_scroll(current + delta_y, max_scroll); + } + /// Adjust `explorer_scroll_y` by `delta_y`, clamp to `0.0..=max_scroll`, and persist it /// against the current history entry `seq` for back-navigation restoration. pub fn scroll_explorer_by(&mut self, delta_y: f32, max_scroll: f32) { diff --git a/packages/frontend/mobile/src/views/tabs.rs b/packages/frontend/mobile/src/views/tabs.rs index 5a1b5ea617..8c9f5bca64 100644 --- a/packages/frontend/mobile/src/views/tabs.rs +++ b/packages/frontend/mobile/src/views/tabs.rs @@ -9,6 +9,8 @@ use ui::{ use ui_kit::{LogicalStyled, MicroIconKind, evaluate_micro_icon}; use crate::{ + explorer_model::{fully_visible, row_window_overscan}, + home_model::{HomeGeometry, clamp_scroll, home_model}, state::{MobileAppState, MobileSheet, MobileTab}, strings::MobileStrings, }; @@ -29,8 +31,10 @@ pub(super) fn render_home( cx: &mut Context, ) -> impl IntoElement { let ws_name = state.active_workspace().summary.name.clone(); - let locale = state.locale(); - let compact = viewport_h < 460.0; + let model = home_model(state); + let g = HomeGeometry::new(viewport_h, !model.favorites.is_empty(), model.recent.len()); + let scroll_y = clamp_scroll(state.home_scroll_y, g.max_scroll); + state.home_scroll_y = scroll_y; let header = row_dir(dir) .id("mobile.home.header") @@ -164,20 +168,12 @@ pub(super) fn render_home( ), ); - let fav_docs: Vec<(String, String)> = state - .active_workspace() - .docs() - .iter() - .filter(|d| !d.trashed && d.is_favorite) - .take(2) - .map(|d| (d.id.clone(), d.display_title(locale))) - .collect(); let mut fav_row = row_dir(dir) .w_full() .flex_shrink(0.0) .items_stretch() .gap(px(10.0)); - for (doc_id, title) in &fav_docs { + for (doc_id, title) in &model.favorites { let click_id = doc_id.clone(); let node_id = format!("mobile.home.fav.{doc_id}"); fav_row = fav_row.child( @@ -187,7 +183,7 @@ pub(super) fn render_home( .relative() .flex_1() .min_w(px(0.0)) - .min_h(px(if compact { 64.0 } else { 80.0 })) + .h(px(g.fav_card_h)) .p(px(12.0)) .rounded(px(12.0)) .bg(palette.bg_surface) @@ -208,42 +204,37 @@ pub(super) fn render_home( .data(STAR_ICON_SVG) .w(px(14.0)) .h(px(14.0)) + .flex_shrink(0.0) .text_color(palette.accent), ) .child( div() .w_full() + .flex_1() + .min_h(px(0.0)) .text_size(px(13.0)) .text_color(palette.text_primary) .align_start_for(dir) - .overflow_hidden() + .line_clamp(if g.compact { 1 } else { 2 }) + .text_ellipsis() .child(title.clone()), ), ); } - let tight_portrait = !compact && viewport_h < 620.0; - let active_docs: Vec<(String, String, String)> = state + let window = row_window_overscan( + g.shown_docs, + g.row_h, + g.list_top, + scroll_y, + g.avail_h, + g.overscan_px, + ); + state .active_workspace() - .docs() - .iter() - .filter(|d| !d.trashed) - .map(|d| { - ( - d.id.clone(), - d.display_title(locale), - d.body_preview.clone(), - ) - }) - .collect(); - let row_h = if compact { - 46.0 - } else if tight_portrait { - 64.0 - } else { - 72.0 - }; - let max_recent = if compact { 2 } else { active_docs.len() }; + .derived + .record_home_mounted_rows(window.visible_range.len()); + let mut recent_list = div() .w_full() .flex_shrink(0.0) @@ -255,18 +246,32 @@ pub(super) fn render_home( .flex_col() .overflow_hidden(); - for (idx, (doc_id, title, preview)) in active_docs.iter().take(max_recent).enumerate() { - let click_id = doc_id.clone(); - let node_id = format!("mobile.home.doc.{doc_id}"); + if window.leading_spacer > 0.0 { + recent_list = + recent_list.child(div().w_full().h(px(window.leading_spacer)).flex_shrink(0.0)); + } + for idx in window.visible_range.clone() { + let doc = &model.recent[idx]; + let click_id = doc.id.clone(); + let node_id = format!("mobile.home.doc.{}", doc.id); + let publish = fully_visible( + g.list_top + (idx as f32) * g.row_h, + g.row_h, + scroll_y, + g.avail_h, + ); let mut row = div() .id(node_id.clone()) - .snapshot(node_id.clone(), Some("mobile.shell.root")) .relative() .w_full() - .min_h(px(row_h)) + .h(px(g.row_h)) .flex_shrink(0.0) .px(px(14.0)) - .py(px(if compact || tight_portrait { 6.0 } else { 9.0 })) + .py(px(if g.compact || g.tight_portrait { + 6.0 + } else { + 9.0 + })) .flex() .flex_col() .justify_center() @@ -276,33 +281,50 @@ pub(super) fn render_home( this.state .open_doc(&click_id, Origin::Direct(DirectKind::Home)); cx.notify(); - })) - .child(a11y_bounds_probe(node_id, a11y_bounds.clone())); + })); + if publish { + row = row + .snapshot(node_id.clone(), Some("mobile.shell.root")) + .child(a11y_bounds_probe(node_id, a11y_bounds.clone())); + } if idx > 0 { row = row.border_t(px(1.0)).border_color(palette.border); } row = row.child( div() .w_full() + .flex_shrink(0.0) .text_size(px(14.0)) .text_color(palette.text_primary) .align_start_for(dir) - .overflow_hidden() - .child(title.clone()), + .line_clamp(1) + .text_ellipsis() + .child(doc.title.clone()), ); - if !compact { + if !g.compact { row = row.child( div() .w_full() + .flex_1() + .min_h(px(0.0)) .text_size(px(12.0)) .text_color(palette.text_secondary) .align_start_for(dir) - .overflow_hidden() - .child(preview.clone()), + .line_clamp(2) + .text_ellipsis() + .child(doc.body_preview.clone()), ); } recent_list = recent_list.child(row); } + if window.trailing_spacer > 0.0 { + recent_list = recent_list.child( + div() + .w_full() + .h(px(window.trailing_spacer)) + .flex_shrink(0.0), + ); + } let fav_section = div() .w_full() @@ -334,32 +356,11 @@ pub(super) fn render_home( ) .child(recent_list); - let avail_h = (viewport_h - 56.0 - 64.0).max(44.0); - let pad = if compact || tight_portrait { - 10.0 - } else { - 16.0 - }; - let gap = if tight_portrait { 8.0 } else { 14.0 }; - let fav_h: f32 = if fav_docs.is_empty() { - 0.0 - } else { - 22.0 + if compact { 64.0 } else { 80.0 } - }; - let recent_h: f32 = 22.0 + (active_docs.len().min(max_recent) as f32) * row_h + 4.0; - let content_h = if compact { - pad * 2.0 + fav_h.max(recent_h) - } else { - pad * 2.0 + fav_h + gap + recent_h - }; - let max_scroll = (content_h - avail_h).max(0.0); - state.home_scroll_y = state.home_scroll_y.clamp(0.0, max_scroll); - let scroll_y = state.home_scroll_y; - - let inner: ui::AnyElement = if compact { + let max_scroll = g.max_scroll; + let inner: ui::AnyElement = if g.compact { row_dir(dir) .w_full() - .p(px(pad)) + .p(px(g.pad)) .gap(px(10.0)) .items_start() .child(div().flex_1().min_w(px(0.0)).child(fav_section)) @@ -368,10 +369,10 @@ pub(super) fn render_home( } else { div() .w_full() - .p(px(pad)) + .p(px(g.pad)) .flex() .flex_col() - .gap(px(gap)) + .gap(px(g.gap)) .child(fav_section) .child(recent_section) .into_any_element() @@ -387,7 +388,7 @@ pub(super) fn render_home( .on_scroll(cx.listener(move |this, event: &ui::ScrollEvent, _, cx| { let dy: f32 = event.delta.pixel_delta(px(24.0)).y.into(); if dy.abs() > 0.01 { - this.state.home_scroll_y = (this.state.home_scroll_y - dy).clamp(0.0, max_scroll); + this.state.scroll_home_by(-dy, max_scroll); cx.notify(); } })) diff --git a/packages/frontend/mobile/tests/scale_work_counts.rs b/packages/frontend/mobile/tests/scale_work_counts.rs index f3283cd556..e7c5041d58 100644 --- a/packages/frontend/mobile/tests/scale_work_counts.rs +++ b/packages/frontend/mobile/tests/scale_work_counts.rs @@ -8,7 +8,8 @@ use std::{cell::RefCell, rc::Rc}; use affine_client::{DirectKind, EditorDocMode, HostKind, NavTarget, Origin, WorkspaceSession}; use affine_mobile::{ MobileAppState, MobileDocRecord, MobileLocale, MobileShellView, MobileTab, - MobileWorkspaceBridge, WorkStats, register_mobile_fonts, seed_showcase_state, + MobileWorkspaceBridge, WorkStats, build_accessibility_tree, register_mobile_fonts, + seed_showcase_state, }; use affine_store::workspace_db::FolderRow; use ui::{ @@ -21,6 +22,9 @@ const SIZES: [usize; 3] = [10, 100, 1_000]; /// Rows one list can show in the `724`-pt Explorer viewport (`ceil(724 / 46) + 1`) plus two /// overscan rows on each side. const MAX_ROWS_PER_LIST: u64 = 17 + 4; +/// Rows Home can show in the `724`-pt viewport (`ceil(724 / 84) + 1`) plus two overscan rows on +/// each side. +const MAX_HOME_ROWS: u64 = 10 + 4; struct Shell { platform: Rc, @@ -106,8 +110,10 @@ fn scale_state(n: usize) -> MobileAppState { ws.folder_revision += 1; ws.docs_mut().extend((0..n).map(|i| MobileDocRecord { id: format!("doc-scale-{i:05}"), - title: format!("Spec Document #{i:05}"), - body_preview: String::new(), + title: format!("Spec Document #{i:05} with a long multi-clause heading for overflow testing"), + body_preview: format!( + "Long multi-line English preview for document #{i:05}: deterministic virtualization keeps fixed row height, prevents spacer drift across deep scrolling, and clamps overflowing prose cleanly inside mobile Home cards without changing viewport layout." + ), tags: Vec::new(), updated_at_ms: 1_764_000_000 + i as i64, is_favorite: i % 50 == 0, @@ -121,15 +127,26 @@ fn scale_state(n: usize) -> MobileAppState { } #[test] -fn explorer_search_drawer_and_page_frames_mount_visible_rows_without_warm_rebuilds() { +fn home_explorer_search_drawer_and_page_frames_mount_visible_rows_without_warm_rebuilds() { + enum RouteKind { + Home, + Explorer(u64), + Other, + } for n in SIZES { let shell = Shell::launch(scale_state(n)); - // (route, setup, list count, scrolls) - let routes: [(&str, Box, u64, bool); 5] = [ + // (route, setup, kind, scrolls) + let routes: [(&str, Box, RouteKind, bool); 6] = [ + ( + "home", + Box::new(|s| s.switch_tab(MobileTab::Home, 0.0)), + RouteKind::Home, + true, + ), ( "explorer", Box::new(|s| s.switch_tab(MobileTab::Explorer, 0.0)), - 2, + RouteKind::Explorer(2), true, ), ( @@ -140,7 +157,7 @@ fn explorer_search_drawer_and_page_frames_mount_visible_rows_without_warm_rebuil Origin::Direct(DirectKind::AllDocs), ); }), - 1, + RouteKind::Explorer(1), true, ), ( @@ -149,7 +166,7 @@ fn explorer_search_drawer_and_page_frames_mount_visible_rows_without_warm_rebuil s.switch_tab(MobileTab::Search, 0.0); s.search_query = "Spec".into(); }), - 0, + RouteKind::Other, false, ), ( @@ -159,7 +176,7 @@ fn explorer_search_drawer_and_page_frames_mount_visible_rows_without_warm_rebuil s.open_workspace_drawer(None, 0.0); s.settle_animations(1_000.0); }), - 0, + RouteKind::Other, false, ), ( @@ -169,25 +186,39 @@ fn explorer_search_drawer_and_page_frames_mount_visible_rows_without_warm_rebuil s.settle_animations(2_000.0); s.open_doc("doc-arch", Origin::Direct(DirectKind::Home)); }), - 0, + RouteKind::Other, false, ), ]; - for (route, setup, lists, scrolls) in routes { + for (route, setup, kind, scrolls) in routes { shell.frame(|s| setup(s)); let first = shell.stats(); for _ in 0..12 { shell.frame(|s| { if scrolls { - s.scroll_explorer_by(138.0, f32::MAX); + match kind { + RouteKind::Home => s.scroll_home_by(144.0, f32::MAX), + RouteKind::Explorer(_) => s.scroll_explorer_by(138.0, f32::MAX), + RouteKind::Other => {} + } } }); - if lists > 0 { - let mounted = shell.stats().explorer_mounted_rows; - assert!( - mounted <= lists * MAX_ROWS_PER_LIST, - "{n} docs, {route}: {mounted} rows built" - ); + match kind { + RouteKind::Home => { + let mounted = shell.stats().home_mounted_rows; + assert!( + mounted <= MAX_HOME_ROWS, + "{n} docs, {route}: {mounted} home rows built" + ); + } + RouteKind::Explorer(lists) => { + let mounted = shell.stats().explorer_mounted_rows; + assert!( + mounted <= lists * MAX_ROWS_PER_LIST, + "{n} docs, {route}: {mounted} rows built" + ); + } + RouteKind::Other => {} } } let warm = shell.stats(); @@ -195,6 +226,7 @@ fn explorer_search_drawer_and_page_frames_mount_visible_rows_without_warm_rebuil for (what, count) in [ ("index", rebuilds(|s| s.index_builds)), ("explorer", rebuilds(|s| s.explorer_builds)), + ("home", rebuilds(|s| s.home_builds)), ("search", rebuilds(|s| s.search_builds)), ("drawer", rebuilds(|s| s.drawer_builds)), ("breadcrumb", rebuilds(|s| s.breadcrumb_builds)), @@ -205,6 +237,83 @@ fn explorer_search_drawer_and_page_frames_mount_visible_rows_without_warm_rebuil } } +#[test] +fn home_deep_scroll_clamps_and_resets_when_workspace_shrinks_or_switches() { + // 1. Deep-scroll 1,000-doc Home to 20,000pt, then shrink active docs to 3 -> scroll clamps + // to <= max_scroll (0.0) and first-screen items stay visible. + let shell = Shell::launch(scale_state(1_000)); + shell.frame(|s| { + s.home_scroll_y = 20_000.0; + }); + let (scroll_deep, mounted_deep) = + shell.frame(|s| (s.home_scroll_y, s.work_stats().home_mounted_rows)); + assert_eq!(scroll_deep, 20_000.0); + assert!(mounted_deep <= MAX_HOME_ROWS); + + shell.frame(|s| { + s.active_workspace_mut() + .docs_mut() + .retain(|d| !d.id.starts_with("doc-scale-")); + }); + let (scroll_after_shrink, has_first_doc, first_doc_y, has_a11y_doc) = shell + .app + .update(|cx| { + shell.window.update(cx, |view, window, _| { + let snap = window.frame_snapshot(); + let doc = snap.elements.get("mobile.home.doc.doc-arch"); + let a11y_ok = view + .published_a11y_tree() + .nodes + .contains_key("mobile.home.doc.doc-arch"); + ( + view.state.home_scroll_y, + doc.is_some(), + doc.map_or(-1.0, |el| el.bounds.y), + a11y_ok, + ) + }) + }) + .unwrap(); + assert_eq!(scroll_after_shrink, 0.0); + assert!(has_first_doc, "first-screen doc-arch must remain mounted"); + assert!( + (56.0..=844.0 - 64.0).contains(&first_doc_y), + "doc-arch y={first_doc_y} must remain inside viewport" + ); + assert!(has_a11y_doc, "doc-arch must remain in a11y tree"); + + // 2. Deep-scroll 1,000-doc Home to 20,000pt, then switch to small workspace -> scroll resets + // to 0.0 and personal workspace's first-screen item is visible. + let shell2 = Shell::launch(scale_state(1_000)); + shell2.frame(|s| { + s.home_scroll_y = 20_000.0; + }); + shell2.frame(|s| { + s.select_workspace(1, 50.0); + assert_eq!(s.home_scroll_y, 0.0); + }); + let (scroll_after_switch, has_personal_doc, personal_y) = shell2 + .app + .update(|cx| { + shell2.window.update(cx, |view, window, _| { + let snap = window.frame_snapshot(); + let doc = snap.elements.get("mobile.home.doc.doc-personal-1"); + ( + view.state.home_scroll_y, + doc.is_some(), + doc.map_or(-1.0, |el| el.bounds.y), + ) + }) + }) + .unwrap(); + assert_eq!(scroll_after_switch, 0.0); + assert!( + has_personal_doc, + "doc-personal-1 must be visible after switch" + ); + assert!((56.0..=844.0 - 64.0).contains(&personal_y)); +} + #[test] fn steady_bridge_sync_reads_no_cached_crdt_bytes_and_reports_no_change() { for n in SIZES { @@ -246,3 +355,210 @@ fn steady_bridge_sync_reads_no_cached_crdt_bytes_and_reports_no_change() { assert_eq!(bridge.merged_crdt_bytes(), read_before, "{n} docs"); } } + +fn launch_with_viewport(w: u32, h: u32, state: MobileAppState) -> Shell { + let platform = HeadlessPlatform::new(w, h, 1.0); + let slot: Rc>>> = Rc::new(RefCell::new(None)); + let out = slot.clone(); + let state = RefCell::new(Some(state)); + let app = Application::with_platform(platform.clone()).run_embedded(move |cx| { + register_mobile_fonts(cx).unwrap(); + let state = state.borrow_mut().take().unwrap(); + let window = cx + .open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds::new( + point(px(0.0), px(0.0)), + size(px(w as f32), px(h as f32)), + ))), + ..WindowOptions::default() + }, + |_, cx| cx.new(|cx| MobileShellView::new(state, cx)), + ) + .unwrap(); + *out.borrow_mut() = Some(window); + }); + let window = slot.borrow_mut().take().unwrap(); + let headless = platform.windows().into_iter().next().unwrap(); + Shell { + platform, + app, + window, + headless, + } +} + +#[test] +fn home_fixed_row_height_and_geometry_hold_for_long_previews_and_zero_favorites() { + // Expected HomeGeometry constants at 390x844 standard viewport. + const ROW_H_STD: f32 = 84.0; + const FAV_H_STD: f32 = 87.0; + const HEADER_H: f32 = 56.0; + const TABBAR_H: f32 = 64.0; + const AVAIL_H_STD: f32 = 844.0 - HEADER_H - TABBAR_H; + + // 1. Long >180-char previews with favorites: rows 0, 500, and 999 stay strictly 84px tall + // and align with HomeGeometry within <= 1.0px. + let shell = Shell::launch(scale_state(1_000)); + let doc_ids: Vec = shell.frame(|s| { + s.active_workspace() + .docs() + .iter() + .filter(|d| !d.trashed) + .map(|d| d.id.clone()) + .collect() + }); + let total_docs = doc_ids.len(); + assert_eq!(total_docs, 1_003); + let fav_list_top = 16.0 + (25.0 + FAV_H_STD) + 14.0 + 26.0; + let fav_max_scroll = + (16.0 * 2.0 + (25.0 + FAV_H_STD) + 14.0 + 25.0 + (total_docs as f32) * ROW_H_STD + 2.0 + - AVAIL_H_STD) + .max(0.0); + + for (idx, scroll) in [ + (0usize, 0.0_f32), + ( + 500usize, + (fav_list_top + 500.0 * ROW_H_STD - 100.0).min(fav_max_scroll), + ), + ( + 999usize, + (fav_list_top + 999.0 * ROW_H_STD - 100.0).min(fav_max_scroll), + ), + (total_docs - 1, fav_max_scroll), + ] { + shell.frame(|s| s.home_scroll_y = scroll); + let node_id = format!("mobile.home.doc.{}", doc_ids[idx]); + let expected_y = HEADER_H + fav_list_top + (idx as f32) * ROW_H_STD - scroll; + shell + .app + .update(|cx| { + shell.window.update(cx, |_, window, _| { + let snap = window.frame_snapshot(); + let el = snap + .elements + .get(&node_id) + .unwrap_or_else(|| panic!("missing snapshot element {node_id}")); + assert!( + (el.bounds.height - ROW_H_STD).abs() <= 0.01, + "row {idx} ({node_id}) height={} expected {ROW_H_STD}", + el.bounds.height + ); + assert!( + (el.bounds.y - expected_y).abs() <= 1.0, + "row {idx} ({node_id}) y={} expected {expected_y}", + el.bounds.y + ); + }) + }) + .unwrap(); + } + + // 2. Zero-favorites + 1,000 docs across standard, tight_portrait, and compact viewports: + // first row aligns with list_top, and at max_scroll the last doc (`doc-scale-00999`) + // fits completely inside the viewport in both FrameSnapshot and published_a11y_tree(). + for (label, w, h, row_h, list_top, max_scroll, check_bottom) in [ + ( + "standard", + 390u32, + 844u32, + 84.0_f32, + 16.0 + 25.0 + 14.0 + 26.0, + (16.0_f32 * 2.0 + 25.0 + 14.0 + 25.0 + 1_000.0 * 84.0 + 2.0 - (844.0 - 120.0)).max(0.0), + true, + ), + ( + "tight_portrait", + 320, + 568, + 78.0, + 10.0 + 25.0 + 8.0 + 26.0, + (10.0_f32 * 2.0 + 25.0 + 8.0 + 25.0 + 1_000.0 * 78.0 + 2.0 - (568.0 - 120.0)).max(0.0), + true, + ), + ("compact", 844, 390, 46.0, 10.0 + 26.0, 0.0, false), + ] { + let mut state = scale_state(1_000); + state + .active_workspace_mut() + .docs_mut() + .retain(|d| d.id.starts_with("doc-scale-")); + for doc in state.active_workspace_mut().docs_mut() { + doc.is_favorite = false; + } + // Check P2: build_accessibility_tree at 390x844 must not clamp state.home_scroll_y. + let huge_scroll = 200_000.0_f32; + state.home_scroll_y = huge_scroll; + let _tree = build_accessibility_tree(&mut state, 390.0, 844.0); + assert_eq!( + state.home_scroll_y, huge_scroll, + "{label}: build_accessibility_tree must not clamp home_scroll_y" + ); + let zero_shell = launch_with_viewport(w, h, state); + + zero_shell.frame(|s| s.home_scroll_y = 0.0); + let first_id = "mobile.home.doc.doc-scale-00000"; + let expected_first_y = HEADER_H + list_top; + zero_shell + .app + .update(|cx| { + zero_shell.window.update(cx, |_, window, _| { + let snap = window.frame_snapshot(); + let el = snap.elements.get(first_id).expect("first row missing"); + assert!( + (el.bounds.y - expected_first_y).abs() <= 1.0, + "{label}: first row y={} expected {expected_first_y}", + el.bounds.y + ); + assert!( + (el.bounds.height - row_h).abs() <= 0.01, + "{label}: first row height={} expected {row_h}", + el.bounds.height + ); + }) + }) + .unwrap(); + + if check_bottom { + zero_shell.frame(|s| s.home_scroll_y = max_scroll); + let last_id = "mobile.home.doc.doc-scale-00999"; + zero_shell + .app + .update(|cx| { + zero_shell.window.update(cx, |view, window, _| { + let snap = window.frame_snapshot(); + let el = snap + .elements + .get(last_id) + .unwrap_or_else(|| panic!("{label}: missing bottom {last_id}")); + assert!( + (el.bounds.height - row_h).abs() <= 0.01, + "{label}: last row height={} expected {row_h}", + el.bounds.height + ); + assert!( + el.bounds.y >= HEADER_H - 1.0 + && el.bounds.y + el.bounds.height <= (h as f32) - TABBAR_H + 1.0, + "{label}: last row bounds ({}, +{}) out of viewport [{HEADER_H}, {}]", + el.bounds.y, + el.bounds.height, + (h as f32) - TABBAR_H + ); + let a11y_node = view + .published_a11y_tree() + .nodes + .get(last_id) + .unwrap_or_else(|| panic!("{label}: missing a11y node {last_id}")); + assert!( + (a11y_node.bounds.y - el.bounds.y).abs() <= 1.0, + "{label}: a11y y={} vs snapshot y={}", + a11y_node.bounds.y, + el.bounds.y + ); + }) + }) + .unwrap(); + } + } +}