feat(mobile): finish shell parity and layout fixes

Update mobile shell screens across Home, Explorer, Journals,
Settings, and Trash document pages.

- Explorer and navigation: show active documents in the All Docs root
  with wheel and native touch scroll, and keep the bottom tab bar
  fixed. Scroll Collections and Tags lists, restore scroll on back
  navigation, and add screen-reader scroll actions.

- Scoped actions and Trash: encode workspace and document IDs with a
  byte-length prefix to stop dot collisions, and require confirmation
  before permanent delete. Purge matching history entries with
  NavHistory::remove_target, replay outgoing edges on restore, and
  show a document-not-found state for missing pages.

- Journals and Settings: wrap the 7-day strip into two rows below
  364pt and use a compact landscape layout below 460pt so every day
  pill and CTA reaches 44x44pt. Separate read-only settings rows from
  toggle and cycle controls without chevrons, and use localized
  untitled titles in main landmarks and backlinks.

- Harness and tests: cover Journals and Trash in audit-matrix with
  width and height touch-target checks. Add touch, scroll, collision,
  and accessibility parity tests alongside matching gallery captures.
This commit is contained in:
DarkSky committed 2026-11-27 06:55:48 +09:00
1 parent e88ee8e9fe
commit 1bf1a4e31d
21 files changed
+4163 -800

No files matched your search

+88
View File
@@ -282,6 +282,46 @@ impl NavHistory {
self.entries.get(cur + 1)
}
/// Remove every history entry matching `(scope, target)` while preserving the original
/// causal `seq` of all remaining entries, adjusting `cursor` to the nearest preceding
/// retained entry if the active entry was removed.
pub fn remove_target(&mut self, scope: &Scope, target: &NavTarget) -> usize {
let old_cursor = self.cursor;
let mut retained = Vec::with_capacity(self.entries.len());
let mut removed = 0usize;
let mut new_cursor: Option<usize> = None;
let mut retained_before_cursor = 0usize;
for (idx, entry) in self.entries.drain(..).enumerate() {
if entry.scope == *scope && entry.target == *target {
removed += 1;
continue;
}
let new_idx = retained.len();
if old_cursor == Some(idx) {
new_cursor = Some(new_idx);
}
if old_cursor.is_some_and(|c| idx < c) {
retained_before_cursor += 1;
}
retained.push(entry);
}
self.entries = retained;
self.cursor = if self.entries.is_empty() {
None
} else if let Some(exact) = new_cursor {
Some(exact)
} else {
Some(
retained_before_cursor
.saturating_sub(1)
.min(self.entries.len() - 1),
)
};
removed
}
/// Update `pick` in place on the entry with `seq` without pushing a new history entry.
pub fn pick_location(&mut self, seq: u64, choice: Option<LocationChoice>) -> bool {
if let Some(entry) = self.entries.iter_mut().find(|e| e.seq == seq) {
@@ -373,3 +413,51 @@ impl NavHistory {
entry
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn remove_target_purges_all_matching_entries_and_keeps_seqs_intact() {
let scope = Scope::new("u1", "https://app.affine.pro", "ws1");
let mut history = NavHistory::new();
let s_home = history.push(
scope.clone(),
NavTarget::Home,
Origin::Direct(DirectKind::Home),
None,
);
history.push(
scope.clone(),
NavTarget::Doc("doc-trash".into()),
Origin::Direct(DirectKind::AllDocs),
None,
);
let s_arch = history.push(
scope.clone(),
NavTarget::Doc("doc-arch".into()),
Origin::Direct(DirectKind::Home),
None,
);
history.push(
scope.clone(),
NavTarget::Doc("doc-trash".into()),
Origin::Direct(DirectKind::AllDocs),
None,
);
let removed = history.remove_target(&scope, &NavTarget::Doc("doc-trash".into()));
assert_eq!(removed, 2);
assert_eq!(history.len(), 2);
assert_eq!(
history.current().map(|e| (e.seq, e.target.clone())),
Some((s_arch, NavTarget::Doc("doc-arch".into())))
);
assert_eq!(
history.back().map(|e| (e.seq, e.target.clone())),
Some((s_home, NavTarget::Home))
);
assert!(!history.can_back());
}
}
+126 -3
View File
@@ -13,7 +13,9 @@ use affine_client::{
};
use ui::{IntoElement, Styled, canvas};
use crate::state::{MobileAppState, MobileBackCoordinator, MobileRoute, MobileSheet, MobileTab};
use crate::state::{
MobileAppState, MobileBackCoordinator, MobileRoute, MobileSheet, MobileTab, SettingsGroupId,
};
/// Shared per-frame map from accessibility node ID to real post-layout painted bounds.
pub type A11yBoundsMap = Rc<RefCell<HashMap<String, AccessibilityBounds>>>;
@@ -57,6 +59,8 @@ pub fn a11y_bounds_probe_border(
pub enum MobileA11yAction {
Activate,
Dismiss,
ScrollForward,
ScrollBackward,
}
/// Thread-safe in-memory [`PlatformAccessibility`] sink for hosts and integration tests.
@@ -211,6 +215,42 @@ pub(crate) fn perform_a11y_action_with_layout(
return false;
}
if matches!(
action,
MobileA11yAction::ScrollForward | MobileA11yAction::ScrollBackward
) {
if state.active_sheet != MobileSheet::None || state.route != MobileRoute::Explorer {
return false;
}
let valid_scroll_target = node_id == "mobile.explorer.scroll_viewport"
|| node_id == "app.main"
|| node_id.starts_with("mobile.explorer.");
if !valid_scroll_target
|| !super::build_accessibility_tree_with_layout(
state,
viewport_width,
viewport_height,
safe_area,
measured_breadcrumb,
)
.nodes
.contains_key(node_id)
{
return false;
}
let (avail_h, max_scroll) =
super::explorer::explorer_scroll_metrics(state, viewport_height, safe_area);
let step = (avail_h - 46.0).max(46.0);
let prev = state.explorer_scroll_y.clamp(0.0, max_scroll);
let delta = if action == MobileA11yAction::ScrollForward {
step
} else {
-step
};
state.scroll_explorer_by(delta, max_scroll);
return (state.explorer_scroll_y - prev).abs() > 0.5;
}
if state.active_sheet != MobileSheet::None {
return perform_sheet_a11y_action(state, node_id, now_ms);
}
@@ -247,7 +287,7 @@ pub(crate) fn perform_a11y_action_with_layout(
state.switch_tab(MobileTab::Search, now_ms);
true
}
"mobile.page.back_btn" | "mobile.settings.back_btn" => {
"mobile.page.back_btn" | "mobile.settings.back_btn" | "mobile.page.not_found_back_btn" => {
MobileBackCoordinator::handle_back(state, now_ms);
true
}
@@ -274,6 +314,53 @@ pub(crate) fn perform_a11y_action_with_layout(
);
true
}
"mobile.home.new_doc_btn" => {
state.create_doc(None, now_ms);
true
}
"mobile.explorer.new_doc_btn" => {
let folder_id = match state.history.current().map(|e| &e.target) {
Some(NavTarget::Folder(fid)) => Some(fid.clone()),
_ => None,
};
state.create_doc(folder_id.as_deref(), now_ms);
true
}
"mobile.journals.create_btn" => {
let date = state.selected_journal_date.clone();
state.open_or_create_journal_for_date(&date, now_ms);
true
}
_ if node_id.starts_with("mobile.page.trash_restore_btn.") => {
let rest = &node_id["mobile.page.trash_restore_btn.".len()..];
let Some((ws_id, doc_id)) = crate::decode_scoped_doc_target(rest) else {
return false;
};
state.restore_doc_scoped(ws_id, doc_id)
}
_ if node_id.starts_with("mobile.page.trash_delete_btn.") => {
let rest = &node_id["mobile.page.trash_delete_btn.".len()..];
let Some((ws_id, doc_id)) = crate::decode_scoped_doc_target(rest) else {
return false;
};
state.request_delete_doc_scoped(ws_id, doc_id, Some(node_id), now_ms)
}
_ if node_id.starts_with("mobile.settings.row.") => {
let key = &node_id["mobile.settings.row.".len()..];
let Some(group) = SettingsGroupId::ALL
.iter()
.copied()
.find(|g| g.a11y_key() == key)
else {
return false;
};
state.activate_setting(group)
}
_ if node_id.starts_with("mobile.journals.day.") => {
let date = &node_id["mobile.journals.day.".len()..];
state.select_journal_date(date);
true
}
"page.backlinks.pill" => {
state.open_sheet_from(MobileSheet::Backlinks, Some("page.backlinks.pill"), now_ms);
true
@@ -321,7 +408,13 @@ pub(crate) fn perform_a11y_action_with_layout(
true
}
_ if node_id.starts_with("mobile.explorer.doc.") => {
let doc_id = &node_id["mobile.explorer.doc.".len()..];
let rest = &node_id["mobile.explorer.doc.".len()..];
let Some((ws_id, doc_id)) = crate::decode_scoped_doc_target(rest) else {
return false;
};
if ws_id != state.active_workspace_id() {
return false;
}
let origin = derive_explorer_doc_origin(state, doc_id);
state.open_doc(doc_id, origin);
true
@@ -447,6 +540,36 @@ fn perform_sheet_a11y_action(state: &mut MobileAppState, node_id: &str, now_ms:
);
true
}
MobileSheet::ConfirmDeleteDoc => {
if let Some(rest) = node_id.strip_prefix("app.sheet.delete_cancel.") {
let Some((ws_id, doc_id)) = crate::decode_scoped_doc_target(rest) else {
return false;
};
if state
.pending_delete_target
.as_ref()
.is_some_and(|(w, d)| w == ws_id && d == doc_id)
{
state.close_sheet(now_ms);
return true;
}
return false;
}
if let Some(rest) = node_id.strip_prefix("app.sheet.delete_confirm.") {
let Some((ws_id, doc_id)) = crate::decode_scoped_doc_target(rest) else {
return false;
};
if state
.pending_delete_target
.as_ref()
.is_some_and(|(w, d)| w == ws_id && d == doc_id)
{
return state.delete_doc_permanently_scoped(ws_id, doc_id, now_ms);
}
return false;
}
false
}
MobileSheet::None => false,
}
}
+309 -17
View File
@@ -15,6 +15,7 @@ use super::SafeAreaMetrics;
pub(super) fn insert_explorer_a11y_nodes(
state: &mut MobileAppState,
viewport_width: f32,
viewport_height: f32,
safe: SafeAreaMetrics,
is_rtl: bool,
nodes: &mut BTreeMap<String, AccessibilityNode>,
@@ -23,7 +24,12 @@ pub(super) fn insert_explorer_a11y_nodes(
let content_left = safe.left;
let content_w = (viewport_width - safe.left - safe.right).max(44.0);
let safe_top = safe.top;
let strings = state.locale().strings();
let effective_h = (viewport_height - safe.top - safe.bottom).max(160.0);
let avail_h = (effective_h - 56.0 - 64.0).max(44.0);
let locale = state.locale();
let strings = locale.strings();
let ws_id = state.active_workspace_id().to_string();
let scroll_y = state.explorer_scroll_y.max(0.0);
if let Some(back_name) = explorer_back_label(state) {
let back_id = "mobile.explorer.back_btn".to_string();
@@ -59,7 +65,34 @@ pub(super) fn insert_explorer_a11y_nodes(
.map(|e| e.target.clone())
.unwrap_or(NavTarget::AllDocs);
let mut rows: Vec<(String, String)> = Vec::new();
if matches!(cur_target, NavTarget::AllDocs | NavTarget::Folder(_)) {
let new_doc_id = "mobile.explorer.new_doc_btn".to_string();
nodes.insert(
new_doc_id.clone(),
AccessibilityNode {
id: new_doc_id.clone(),
role: AccessibilityRole::Button,
name: strings.new_doc_label.to_string(),
value: None,
state: AccessibilityState::default(),
focused: false,
bounds: AccessibilityBounds {
x: if is_rtl {
content_left + 12.0
} else {
content_left + (content_w - 56.0).max(0.0)
},
y: safe_top + 6.0,
width: 44.0,
height: 44.0,
},
children: Vec::new(),
},
);
main_children.push(new_doc_id);
}
let mut rows: Vec<(String, String, f32, f32)> = Vec::new();
match cur_target {
NavTarget::Folder(folder_id) => {
if let FolderForestState::Ready(forest) = state.forest_state() {
@@ -73,81 +106,205 @@ pub(super) fn insert_explorer_a11y_nodes(
.into_iter()
.map(|p| p.doc_id.clone())
.collect();
rows.extend(subs);
let mut idx = 0usize;
for (id, name) in subs {
rows.push((id, name, 17.0 + (idx as f32) * 46.0, 46.0));
idx += 1;
}
for doc_id in doc_ids {
if let Some(doc) = state.doc_by_id(&doc_id)
&& !doc.trashed
{
rows.push((format!("mobile.explorer.doc.{}", doc.id), doc.title.clone()));
rows.push((
format!(
"mobile.explorer.doc.{}",
crate::encode_scoped_doc_target(&ws_id, &doc.id)
),
doc.display_title(locale),
17.0 + (idx as f32) * 46.0,
46.0,
));
idx += 1;
}
}
}
}
NavTarget::Collection(col_id) if col_id.is_empty() => {
for col in &state.collections {
for (idx, col) in state.collections.iter().enumerate() {
rows.push((
format!("mobile.explorer.collection.{}", col.id),
col.name.clone(),
17.0 + (idx as f32) * 46.0,
46.0,
));
}
}
NavTarget::Collection(col_id) => {
if let Some(col) = state.collections.iter().find(|c| c.id == col_id) {
let member_ids = col.doc_ids.clone();
let mut idx = 0usize;
for doc in &state.docs {
if !doc.trashed && member_ids.iter().any(|id| id == &doc.id) {
rows.push((format!("mobile.explorer.doc.{}", doc.id), doc.title.clone()));
rows.push((
format!(
"mobile.explorer.doc.{}",
crate::encode_scoped_doc_target(&ws_id, &doc.id)
),
doc.display_title(locale),
17.0 + (idx as f32) * 46.0,
46.0,
));
idx += 1;
}
}
}
}
NavTarget::Tag(tag_id) if tag_id.is_empty() => {
for (tag_id, tag_name) in &state.tags {
for (idx, (tag_id, tag_name)) in state.tags.iter().enumerate() {
rows.push((
format!("mobile.explorer.tag.{tag_id}"),
format!("#{tag_name}"),
17.0 + (idx as f32) * 46.0,
46.0,
));
}
}
NavTarget::Tag(tag_id) => {
let mut idx = 0usize;
for doc in &state.docs {
if !doc.trashed && doc.tags.iter().any(|t| t == &tag_id) {
rows.push((format!("mobile.explorer.doc.{}", doc.id), doc.title.clone()));
rows.push((
format!(
"mobile.explorer.doc.{}",
crate::encode_scoped_doc_target(&ws_id, &doc.id)
),
doc.display_title(locale),
17.0 + (idx as f32) * 46.0,
46.0,
));
idx += 1;
}
}
}
NavTarget::Trash => {
let mut idx = 0usize;
for doc in &state.docs {
if doc.trashed {
rows.push((format!("mobile.explorer.doc.{}", doc.id), doc.title.clone()));
rows.push((
format!(
"mobile.explorer.doc.{}",
crate::encode_scoped_doc_target(&ws_id, &doc.id)
),
doc.display_title(locale),
17.0 + (idx as f32) * 46.0,
46.0,
));
idx += 1;
}
}
}
_ => {
let compact = effective_h < 460.0;
let tight_portrait = !compact && effective_h < 620.0;
let row_h = if compact || tight_portrait {
44.0
} else {
46.0
};
let pad = if compact || tight_portrait {
10.0
} else {
16.0
};
let gap = if tight_portrait { 8.0 } else { 12.0 };
let heading_h = 16.0;
let folder_top = if compact {
pad + 1.0
} else {
pad + heading_h + gap + 1.0
};
let mut folder_count = 0usize;
if let FolderForestState::Ready(forest) = state.forest_state() {
for (folder, _) in forest.dfs_folders() {
for (idx, (folder, _)) in forest.dfs_folders().into_iter().enumerate() {
rows.push((
format!("mobile.explorer.folder.{}", folder.id),
folder.data.clone(),
folder_top + (idx as f32) * row_h,
row_h,
));
folder_count += 1;
}
}
let folder_h = (folder_count as f32) * row_h + 2.0;
let org_top = if compact {
pad + 1.0
} else {
pad + heading_h + gap + folder_h + gap + 1.0
};
let org_h = if tight_portrait {
44.0 + 2.0
} else {
3.0 * row_h + 2.0
};
rows.push((
"mobile.explorer.collections".to_string(),
strings.collections.to_string(),
org_top,
row_h,
));
rows.push((
"mobile.explorer.tags".to_string(),
strings.tags.to_string(),
if tight_portrait {
org_top
} else {
org_top + row_h
},
row_h,
));
rows.push(("mobile.explorer.tags".to_string(), strings.tags.to_string()));
rows.push((
"mobile.explorer.trash".to_string(),
strings.trash.to_string(),
if tight_portrait {
org_top
} else {
org_top + row_h * 2.0
},
row_h,
));
let docs_top = if compact {
pad + 1.0
} else {
pad + heading_h + gap + folder_h + gap + org_h + gap + heading_h + gap + 1.0
};
let mut doc_idx = 0usize;
for doc in &state.docs {
if !doc.trashed {
rows.push((
format!(
"mobile.explorer.doc.{}",
crate::encode_scoped_doc_target(&ws_id, &doc.id)
),
doc.display_title(locale),
docs_top + (doc_idx as f32) * row_h,
row_h,
));
doc_idx += 1;
}
}
}
}
let (_, max_scroll) = explorer_scroll_metrics(state, viewport_height, safe);
let clamped_scroll = scroll_y.clamp(0.0, max_scroll);
let row_x = content_left + 16.0;
let row_w = (content_w - 32.0).max(44.0);
let mut y = safe_top + 72.0;
for (id, name) in rows {
let mut viewport_children = Vec::new();
for (id, name, top_in_content, h) in rows {
let vis_top = top_in_content - clamped_scroll;
if vis_top < -1.0 || vis_top + h > avail_h + 1.0 {
continue;
}
nodes.insert(
id.clone(),
AccessibilityNode {
@@ -159,16 +316,151 @@ pub(super) fn insert_explorer_a11y_nodes(
focused: false,
bounds: AccessibilityBounds {
x: row_x,
y,
y: safe_top + 56.0 + vis_top,
width: row_w,
height: 46.0,
height: h,
},
children: Vec::new(),
},
);
main_children.push(id);
y += 46.0;
viewport_children.push(id);
}
let viewport_id = "mobile.explorer.scroll_viewport".to_string();
nodes.insert(
viewport_id.clone(),
AccessibilityNode {
id: viewport_id.clone(),
role: AccessibilityRole::Region,
name: strings.tab_explorer.to_string(),
value: (max_scroll > 0.5).then(|| format!("{clamped_scroll:.0}/{max_scroll:.0}")),
state: AccessibilityState::default(),
focused: false,
bounds: AccessibilityBounds {
x: content_left,
y: safe_top + 56.0,
width: content_w,
height: avail_h,
},
children: viewport_children,
},
);
main_children.push(viewport_id);
}
/// Compute `(avail_h, max_scroll)` for the active Explorer sub-view matching visual layout.
pub(super) fn explorer_scroll_metrics(
state: &mut MobileAppState,
viewport_height: f32,
safe: SafeAreaMetrics,
) -> (f32, f32) {
let effective_h = (viewport_height - safe.top - safe.bottom).max(160.0);
let avail_h = (effective_h - 56.0 - 64.0).max(44.0);
let cur_target = state
.history
.current()
.map(|e| e.target.clone())
.unwrap_or(NavTarget::AllDocs);
let content_h = match cur_target {
NavTarget::Folder(folder_id) => {
let total_rows = match state.forest_state() {
FolderForestState::Ready(forest) => {
let subs = forest.child_folders(Some(&folder_id)).len();
let docs = forest
.doc_links_in_folder(&folder_id)
.into_iter()
.filter(|p| state.doc_by_id(&p.doc_id).is_some_and(|d| !d.trashed))
.count();
subs + docs
}
FolderForestState::Unresolved => 0,
};
32.0 + (total_rows as f32) * 46.0 + 2.0
}
NavTarget::Collection(col_id) if col_id.is_empty() => {
32.0 + (state.collections.len() as f32) * 46.0 + 2.0
}
NavTarget::Collection(col_id) => {
let count = state
.collections
.iter()
.find(|c| c.id == col_id)
.map(|c| {
state
.docs
.iter()
.filter(|d| !d.trashed && c.doc_ids.iter().any(|id| id == &d.id))
.count()
})
.unwrap_or(0);
32.0 + (count as f32) * 46.0 + 2.0
}
NavTarget::Tag(tag_id) if tag_id.is_empty() => {
32.0 + (state.tags.len() as f32) * 46.0 + 2.0
}
NavTarget::Tag(tag_id) => {
let count = state
.docs
.iter()
.filter(|d| !d.trashed && d.tags.iter().any(|t| t == &tag_id))
.count();
32.0 + (count as f32) * 46.0 + 2.0
}
NavTarget::Trash => {
let count = state.docs.iter().filter(|d| d.trashed).count();
32.0 + (count as f32) * 46.0 + 2.0
}
_ => {
let compact = effective_h < 460.0;
let tight_portrait = !compact && effective_h < 620.0;
let row_h = if compact || tight_portrait {
44.0
} else {
46.0
};
let pad = if compact || tight_portrait {
10.0
} else {
16.0
};
let gap = if tight_portrait { 8.0 } else { 12.0 };
let heading_h = 16.0;
let folder_count = match state.forest_state() {
FolderForestState::Ready(forest) => forest.dfs_folders().len(),
FolderForestState::Unresolved => 0,
};
let active_docs = state.docs.iter().filter(|d| !d.trashed).count();
let folder_h = (folder_count as f32) * row_h + 2.0;
let org_h = if tight_portrait {
44.0 + 2.0
} else {
3.0 * row_h + 2.0
};
let docs_h = if active_docs == 0 {
0.0
} else {
(active_docs as f32) * row_h + 2.0
};
if compact {
pad * 2.0 + folder_h.max(org_h).max(docs_h)
} else if active_docs == 0 {
pad * 2.0 + heading_h + gap + folder_h + gap + org_h
} else {
pad * 2.0
+ heading_h
+ gap
+ folder_h
+ gap
+ org_h
+ gap
+ heading_h
+ gap
+ docs_h
}
}
};
(avail_h, (content_h - avail_h).max(0.0))
}
fn explorer_back_label(state: &mut MobileAppState) -> Option<String> {
+258 -29
View File
@@ -23,7 +23,13 @@ use ui_kit::{
layout_breadcrumb_bar,
};
use crate::state::{MobileAppState, MobileRoute, MobileSheet, MobileTab};
use crate::{
state::{
MobileAppState, MobileRoute, MobileSheet, MobileTab, SettingRowInteraction,
SettingsGroupId, ThemePreference,
},
views::week_days_for_date,
};
use self::{explorer::insert_explorer_a11y_nodes, sheet::insert_sheet_a11y_nodes};
@@ -147,12 +153,102 @@ pub fn build_accessibility_tree_with_layout(
},
);
main_children.push(ws_btn_id);
let new_doc_id = "mobile.home.new_doc_btn".to_string();
nodes.insert(
new_doc_id.clone(),
AccessibilityNode {
id: new_doc_id.clone(),
role: AccessibilityRole::Button,
name: strings.new_doc_label.to_string(),
value: None,
state: AccessibilityState::default(),
focused: false,
bounds: AccessibilityBounds {
x: if is_rtl {
content_left + 64.0
} else {
content_left + (content_w - 108.0).max(0.0)
},
y: safe_top + 6.0,
width: 44.0,
height: 44.0,
},
children: Vec::new(),
},
);
main_children.push(new_doc_id);
}
if let MobileRoute::Journals = state.route {
let week = week_days_for_date(&state.today_date);
let strip_w = (content_w - 32.0).max(44.0);
let day_w = ((strip_w - 24.0) / 7.0).max(32.0);
for (idx, (_, _, iso_date)) in week.iter().enumerate() {
let day_id = format!("mobile.journals.day.{iso_date}");
let day_x = if is_rtl {
content_left + 16.0 + ((6 - idx) as f32) * (day_w + 4.0)
} else {
content_left + 16.0 + (idx as f32) * (day_w + 4.0)
};
nodes.insert(
day_id.clone(),
AccessibilityNode {
id: day_id.clone(),
role: AccessibilityRole::Button,
name: iso_date.clone(),
value: None,
state: AccessibilityState {
selected: iso_date == &state.selected_journal_date,
..AccessibilityState::default()
},
focused: false,
bounds: AccessibilityBounds {
x: day_x,
y: safe_top + 72.0,
width: day_w,
height: 52.0,
},
children: Vec::new(),
},
);
main_children.push(day_id);
}
let has_entry = state.docs.iter().any(|d| {
!d.trashed && d.journal_date.as_deref() == Some(state.selected_journal_date.as_str())
});
let cta_id = "mobile.journals.create_btn".to_string();
nodes.insert(
cta_id.clone(),
AccessibilityNode {
id: cta_id.clone(),
role: AccessibilityRole::Button,
name: if has_entry {
strings.open_journal.to_string()
} else {
strings.create_journal.to_string()
},
value: None,
state: AccessibilityState::default(),
focused: false,
bounds: AccessibilityBounds {
x: content_left + 16.0,
y: safe_top + 250.0,
width: strip_w,
height: 46.0,
},
children: Vec::new(),
},
);
main_children.push(cta_id);
}
if let MobileRoute::Explorer = state.route {
insert_explorer_a11y_nodes(
state,
viewport_width,
viewport_height,
safe,
is_rtl,
&mut nodes,
@@ -160,6 +256,57 @@ pub fn build_accessibility_tree_with_layout(
);
}
if let MobileRoute::Settings = state.route {
let row_x = content_left + 14.0;
let row_w = (content_w - 28.0).max(44.0);
for (idx, group) in SettingsGroupId::ALL.iter().copied().enumerate() {
if group.interaction() == SettingRowInteraction::Info {
continue;
}
let row_id = format!("mobile.settings.row.{}", group.a11y_key());
let val = match group {
SettingsGroupId::Appearance => match state.settings.theme_preference {
ThemePreference::Light => strings.theme_light.to_string(),
ThemePreference::Dark => strings.theme_dark.to_string(),
ThemePreference::System => strings.theme_system.to_string(),
},
SettingsGroupId::Language => state.settings.locale.display_name().to_string(),
SettingsGroupId::SyncOffline => if state.settings.offline_sync_enabled {
strings.toggle_on
} else {
strings.toggle_off
}
.to_string(),
SettingsGroupId::Notifications => if state.settings.push_notifications {
strings.toggle_on
} else {
strings.toggle_off
}
.to_string(),
_ => String::new(),
};
nodes.insert(
row_id.clone(),
AccessibilityNode {
id: row_id.clone(),
role: AccessibilityRole::Button,
name: strings.settings_groups[idx].to_string(),
value: Some(val),
state: AccessibilityState::default(),
focused: false,
bounds: AccessibilityBounds {
x: row_x,
y: safe_top + 66.0 + (idx as f32) * 44.0,
width: row_w,
height: 44.0,
},
children: Vec::new(),
},
);
main_children.push(row_id);
}
}
if let MobileRoute::Page(doc_id) = state.route.clone() {
let derivation = state.derive_breadcrumb();
if !derivation.should_hide_bar_on_mobile && !derivation.crumbs.is_empty() {
@@ -174,6 +321,17 @@ pub fn build_accessibility_tree_with_layout(
.map(|c| {
let label = if c.is_switcher {
match &derivation.context {
ContextState::MultiLocation {
count,
owner_doc_id,
owner_doc_title,
..
} if *owner_doc_id != doc_id => strings
.compact_owner_multi_location_label(
locale,
owner_doc_title,
*count,
),
ContextState::MultiLocation { count, .. } => {
strings.multi_location_label(locale, *count)
}
@@ -311,34 +469,105 @@ pub fn build_accessibility_tree_with_layout(
);
main_children.push(more_id);
let backlinks_id = "page.backlinks.pill".to_string();
let bl = state.backlinks_for(&doc_id);
nodes.insert(
backlinks_id.clone(),
AccessibilityNode {
id: backlinks_id.clone(),
role: AccessibilityRole::Button,
name: strings.backlinks_pill_label(
locale,
bl.items.len(),
bl.completeness == affine_client::BacklinkCompleteness::Ready,
),
value: None,
state: AccessibilityState {
expanded: Some(state.active_sheet == MobileSheet::Backlinks),
..AccessibilityState::default()
let doc_exists = state.doc_by_id(&doc_id).is_some();
let ws_id = state.active_workspace_id().to_string();
if !doc_exists {
let nf_id = "mobile.page.not_found_back_btn".to_string();
nodes.insert(
nf_id.clone(),
AccessibilityNode {
id: nf_id.clone(),
role: AccessibilityRole::Button,
name: strings.back_label.to_string(),
value: None,
state: AccessibilityState::default(),
focused: false,
bounds: AccessibilityBounds {
x: content_left + (content_w - 120.0).max(0.0) * 0.5,
y: safe_top + 200.0,
width: 120.0,
height: 44.0,
},
children: Vec::new(),
},
focused: false,
bounds: AccessibilityBounds {
x: content_left + 16.0,
y: safe_top + 108.0,
width: (content_w - 32.0).max(44.0),
height: 44.0,
);
main_children.push(nf_id);
} else {
if derivation.in_trash {
let scoped = crate::encode_scoped_doc_target(&ws_id, &doc_id);
let restore_id = format!("mobile.page.trash_restore_btn.{scoped}");
nodes.insert(
restore_id.clone(),
AccessibilityNode {
id: restore_id.clone(),
role: AccessibilityRole::Button,
name: strings.restore_doc_label.to_string(),
value: None,
state: AccessibilityState::default(),
focused: false,
bounds: AccessibilityBounds {
x: content_left + 16.0,
y: safe_top + 114.0,
width: 72.0,
height: 44.0,
},
children: Vec::new(),
},
);
main_children.push(restore_id);
let delete_id = format!("mobile.page.trash_delete_btn.{scoped}");
nodes.insert(
delete_id.clone(),
AccessibilityNode {
id: delete_id.clone(),
role: AccessibilityRole::Button,
name: strings.delete_permanently_label.to_string(),
value: None,
state: AccessibilityState::default(),
focused: false,
bounds: AccessibilityBounds {
x: content_left + 96.0,
y: safe_top + 114.0,
width: 120.0,
height: 44.0,
},
children: Vec::new(),
},
);
main_children.push(delete_id);
}
let backlinks_id = "page.backlinks.pill".to_string();
let bl = state.backlinks_for(&doc_id);
nodes.insert(
backlinks_id.clone(),
AccessibilityNode {
id: backlinks_id.clone(),
role: AccessibilityRole::Button,
name: strings.backlinks_pill_label(
locale,
bl.items.len(),
bl.completeness == affine_client::BacklinkCompleteness::Ready,
),
value: None,
state: AccessibilityState {
expanded: Some(state.active_sheet == MobileSheet::Backlinks),
..AccessibilityState::default()
},
focused: false,
bounds: AccessibilityBounds {
x: content_left + 16.0,
y: safe_top + 108.0,
width: (content_w - 32.0).max(44.0),
height: 44.0,
},
children: Vec::new(),
},
children: Vec::new(),
},
);
main_children.push(backlinks_id);
);
main_children.push(backlinks_id);
}
}
let main_name = match &state.route {
@@ -349,8 +578,8 @@ pub fn build_accessibility_tree_with_layout(
MobileRoute::Settings => strings.settings_title.to_string(),
MobileRoute::Page(id) => state
.doc_by_id(id)
.map(|d| d.title.clone())
.unwrap_or_else(|| "Untitled".to_string()),
.map(|d| d.display_title(locale))
.unwrap_or_else(|| strings.untitled_doc.to_string()),
};
let show_tabbar = matches!(
+23 -1
View File
@@ -130,13 +130,34 @@ pub(super) fn insert_sheet_a11y_nodes(
.map(|(i, item)| {
let title = state
.doc_by_id(&item.source_doc_id)
.map(|d| d.title.clone())
.map(|d| d.display_title(state.locale()))
.unwrap_or_else(|| item.source_doc_id.clone());
(format!("mobile.sheet.backlink.{i}"), title, false, 46.0)
})
.collect(),
);
}
MobileSheet::ConfirmDeleteDoc => {
let (ws_id, doc_id) = state
.pending_delete_target
.clone()
.unwrap_or_else(|| (state.active_workspace_id().to_string(), String::new()));
let scoped = crate::encode_scoped_doc_target(&ws_id, &doc_id);
cols.push(vec![
(
format!("app.sheet.delete_cancel.{scoped}"),
strings.cancel_label.to_string(),
false,
44.0,
),
(
format!("app.sheet.delete_confirm.{scoped}"),
strings.delete_permanently_label.to_string(),
false,
44.0,
),
]);
}
MobileSheet::None => {}
}
@@ -224,6 +245,7 @@ pub(super) fn insert_sheet_a11y_nodes(
MobileSheet::WorkspaceSelector => strings.switch_workspace,
MobileSheet::LocationAndTrail => strings.location_trail_title,
MobileSheet::Backlinks => strings.backlinks_label,
MobileSheet::ConfirmDeleteDoc => strings.confirm_delete_title,
MobileSheet::None => "",
};
nodes.insert(
@@ -156,13 +156,16 @@ fn check_snapshot_bounds(
));
}
let is_touch_control = id.contains(".btn")
|| id.contains("_btn")
|| id.starts_with("mobile.tab.")
|| id.starts_with("mobile.journals.day.")
|| id.starts_with("mobile.settings.row.")
|| id == "mobile.page.backlinks_pill"
|| id == "mobile.page.breadcrumb_bar";
if is_touch_control && b.height < 43.5 {
if is_touch_control && (b.height < 43.5 || b.width < 43.5) {
violations.push(format!(
"{context}: touch target {id} height {:.1} < 44pt",
b.height
"{context}: touch target {id} size {:.1}x{:.1} < 44x44pt",
b.width, b.height
));
}
}
@@ -221,21 +224,32 @@ fn run_audit_matrix() -> Result<()> {
let session = start_session(vp_w, vp_h, 1.0, state)?;
let tag_prefix = format!("{vp_w}x{vp_h}/{:?}/{}", theme, locale.code());
let routes: [(&str, Box<dyn Fn(&mut MobileAppState)>); 6] = [
let routes: [(&str, Box<dyn Fn(&mut MobileAppState)>); 8] = [
("home", Box::new(|s| s.switch_tab(MobileTab::Home, 0.0))),
(
"explorer",
Box::new(|s| s.switch_tab(MobileTab::Explorer, 50.0)),
),
(
"journals",
Box::new(|s| s.switch_tab(MobileTab::Journals, 75.0)),
),
(
"page_multi",
Box::new(|s| {
s.open_doc("doc-arch", Origin::Direct(DirectKind::Home));
}),
),
(
"page_trash",
Box::new(|s| {
s.open_doc("doc-trash", Origin::Direct(DirectKind::AllDocs));
}),
),
(
"location_sheet",
Box::new(|s| {
s.open_doc("doc-arch", Origin::Direct(DirectKind::Home));
s.open_sheet(MobileSheet::LocationAndTrail, 100.0);
s.settle_animations(500.0);
}),
@@ -534,9 +548,72 @@ fn run_gallery(out_dir: PathBuf) -> Result<()> {
);
}),
),
(
"search-empty-no-results.png",
MobileLocale::En,
ThemeMode::Light,
Box::new(|s| {
s.switch_tab(MobileTab::Search, 0.0);
s.search_query = "NonexistentQuery".to_string();
}),
),
(
"journals-today-and-other-day.png",
MobileLocale::En,
ThemeMode::Light,
Box::new(|s| {
s.switch_tab(MobileTab::Journals, 0.0);
s.select_journal_date("2026-11-26");
}),
),
(
"trash-doc-actions.png",
MobileLocale::En,
ThemeMode::Light,
Box::new(|s| {
s.open_doc("doc-trash", Origin::Direct(DirectKind::AllDocs));
}),
),
(
"trash-delete-confirm-sheet.png",
MobileLocale::En,
ThemeMode::Light,
Box::new(|s| {
s.open_doc("doc-trash", Origin::Direct(DirectKind::AllDocs));
let delete_id = format!(
"mobile.page.trash_delete_btn.{}",
affine_mobile::encode_scoped_doc_target("ws-mobile-rust", "doc-trash")
);
s.request_delete_doc_scoped("ws-mobile-rust", "doc-trash", Some(&delete_id), 0.0);
s.settle_animations(500.0);
}),
),
(
"explorer-30-docs-scrolled.png",
MobileLocale::En,
ThemeMode::Light,
Box::new(|s| {
for i in 1..=30 {
s.docs.push(affine_mobile::MobileDocRecord {
id: format!("doc-bulk-{i}"),
title: format!("Spec Document #{i:02}"),
body_preview: format!("Body preview for document #{i:02}."),
tags: Vec::new(),
updated_at_ms: 1_764_000_000 + i as i64,
is_favorite: false,
trashed: false,
journal_date: None,
clock: 1,
outgoing_edges: Vec::new(),
});
}
s.switch_tab(MobileTab::Explorer, 0.0);
s.explorer_scroll_y = 2000.0;
}),
),
];
// Reuse one HeadlessPlatform + GPU surface across all 7 shots so full gallery renders in < 5s.
// Reuse one HeadlessPlatform + GPU surface across all 390x844 shots.
let initial = seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-11-25");
let session = start_session(390, 844, 2.0, initial)?;
@@ -552,6 +629,24 @@ fn run_gallery(out_dir: PathBuf) -> Result<()> {
);
}
// 320x568 narrow viewport LTR & RTL Journals 2-row grid shots.
let narrow_initial = seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-11-25");
let narrow_session = start_session(320, 568, 2.0, narrow_initial)?;
for (filename, locale) in [
("journals-320-ltr.png", MobileLocale::En),
("journals-320-rtl.png", MobileLocale::Ar),
] {
let mut next_state = seed_showcase_state(locale, ThemeMode::Light, "2026-11-25");
next_state.switch_tab(MobileTab::Journals, 0.0);
narrow_session.update_state(|s| *s = next_state)?;
let out_path = out_dir.join(filename);
let glyphs = narrow_session.render_png(&out_path)?;
println!(
"gallery: rendered {} (640x1136, {glyphs} glyphs)",
out_path.display()
);
}
Ok(())
}
+4 -2
View File
@@ -10,6 +10,7 @@
pub mod a11y;
pub mod showcase;
pub mod state;
mod state_ops;
pub mod strings;
pub mod views;
@@ -25,9 +26,10 @@ pub use a11y::{
pub use showcase::seed_showcase_state;
pub use state::{
BackOutcome, MobileAppState, MobileBackCoordinator, MobileCollection, MobileDocRecord,
MobileRoute, MobileSheet, MobileTab, SettingsGroupId, SettingsState, ThemePreference,
WorkspaceData, WorkspaceSummary,
MobileRoute, MobileSheet, MobileTab, SettingRowInteraction, SettingsGroupId, SettingsState,
ThemePreference, WorkspaceData, WorkspaceSummary,
};
pub use state_ops::{decode_scoped_doc_target, encode_scoped_doc_target};
pub use strings::{MobileLocale, MobileStrings};
pub use views::MobileShellView;
+34 -32
View File
@@ -96,6 +96,7 @@ fn build_primary_workspace(locale: MobileLocale, today_date: &str) -> WorkspaceD
trashed: false,
journal_date: None,
clock: 3,
outgoing_edges: Vec::new(),
},
MobileDocRecord {
id: "doc-sync".into(),
@@ -115,6 +116,12 @@ fn build_primary_workspace(locale: MobileLocale, today_date: &str) -> WorkspaceD
trashed: false,
journal_date: None,
clock: 2,
outgoing_edges: vec![DocRefEdge {
source_doc_id: "doc-sync".into(),
target_doc_id: "doc-arch".into(),
source_block_id: "b-sync-1".into(),
kind: OutboundRefKind::InlineMention,
}],
},
MobileDocRecord {
id: "doc-journal".into(),
@@ -130,6 +137,12 @@ fn build_primary_workspace(locale: MobileLocale, today_date: &str) -> WorkspaceD
trashed: false,
journal_date: Some(today_date.to_string()),
clock: 1,
outgoing_edges: vec![DocRefEdge {
source_doc_id: "doc-journal".into(),
target_doc_id: "doc-arch".into(),
source_block_id: "b-j-1".into(),
kind: OutboundRefKind::EmbedLinkedDoc,
}],
},
MobileDocRecord {
id: "doc-trash".into(),
@@ -145,31 +158,14 @@ fn build_primary_workspace(locale: MobileLocale, today_date: &str) -> WorkspaceD
trashed: true,
journal_date: None,
clock: 1,
outgoing_edges: Vec::new(),
},
];
let mut link_graph = LinkGraph::new();
link_graph.replace_edges(
"doc-sync",
vec![DocRefEdge {
source_doc_id: "doc-sync".into(),
target_doc_id: "doc-arch".into(),
source_block_id: "b-sync-1".into(),
kind: OutboundRefKind::InlineMention,
}],
2,
);
link_graph.replace_edges(
"doc-journal",
vec![DocRefEdge {
source_doc_id: "doc-journal".into(),
target_doc_id: "doc-arch".into(),
source_block_id: "b-j-1".into(),
kind: OutboundRefKind::EmbedLinkedDoc,
}],
1,
);
link_graph.replace_edges("doc-arch", Vec::new(), 3);
for doc in &docs {
link_graph.replace_edges(&doc.id, doc.outgoing_edges.clone(), doc.clock);
}
let mut history = NavHistory::new();
history.push(
@@ -223,6 +219,7 @@ fn build_primary_workspace(locale: MobileLocale, today_date: &str) -> WorkspaceD
link_graph,
workspace_index_seeded: true,
history,
next_doc_seq: 1,
}
}
@@ -264,6 +261,7 @@ fn build_personal_workspace(locale: MobileLocale) -> WorkspaceData {
trashed: false,
journal_date: None,
clock: 1,
outgoing_edges: Vec::new(),
},
MobileDocRecord {
id: "doc-personal-2".into(),
@@ -279,20 +277,18 @@ fn build_personal_workspace(locale: MobileLocale) -> WorkspaceData {
trashed: false,
journal_date: None,
clock: 1,
outgoing_edges: vec![DocRefEdge {
source_doc_id: "doc-personal-2".into(),
target_doc_id: "doc-personal-1".into(),
source_block_id: "b-p-1".into(),
kind: OutboundRefKind::InlineMention,
}],
},
];
let mut link_graph = LinkGraph::new();
link_graph.replace_edges(
"doc-personal-2",
vec![DocRefEdge {
source_doc_id: "doc-personal-2".into(),
target_doc_id: "doc-personal-1".into(),
source_block_id: "b-p-1".into(),
kind: OutboundRefKind::InlineMention,
}],
1,
);
link_graph.replace_edges("doc-personal-1", Vec::new(), 1);
for doc in &docs {
link_graph.replace_edges(&doc.id, doc.outgoing_edges.clone(), doc.clock);
}
let mut history = NavHistory::new();
history.push(
@@ -328,6 +324,7 @@ fn build_personal_workspace(locale: MobileLocale) -> WorkspaceData {
link_graph,
workspace_index_seeded: true,
history,
next_doc_seq: 1,
}
}
@@ -361,12 +358,17 @@ pub fn seed_showcase_state(
route: MobileRoute::Home,
active_sheet: MobileSheet::None,
closing_sheet: None,
pending_delete_target: None,
sheet_trigger_a11y_id: None,
focused_a11y_id: None,
sheet_motion: Sheet::new(),
tab_anim_start_ms: 0.0,
page_overlay_active: false,
explorer_scroll_y: 0.0,
explorer_scroll_by_seq: std::collections::HashMap::new(),
today_date: today_date.to_string(),
selected_journal_date: today_date.to_string(),
next_doc_seq: primary.next_doc_seq,
search_query: match locale {
MobileLocale::En => "Sync".into(),
MobileLocale::ZhHans => "同步".into(),
+73 -1
View File
@@ -10,6 +10,7 @@ use affine_client::{
nav::breadcrumb,
};
use affine_store::workspace_db::FolderRow;
use blocksuite_playground_doc::refs::DocRefEdge;
use serde::{Deserialize, Serialize};
use ui_kit::{MicroIconKind, Sheet};
use ui_tokens::ThemeMode;
@@ -68,6 +69,7 @@ pub enum MobileSheet {
WorkspaceSelector,
LocationAndTrail,
Backlinks,
ConfirmDeleteDoc,
}
/// Appearance mode preference in Settings.
@@ -105,6 +107,14 @@ pub enum SettingsGroupId {
About,
}
/// Honest interaction kind for each mobile Settings row.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum SettingRowInteraction {
Info,
Toggle,
Cycle,
}
impl SettingsGroupId {
pub const ALL: [Self; 10] = [
Self::Account,
@@ -118,6 +128,34 @@ impl SettingsGroupId {
Self::Experimental,
Self::About,
];
pub const fn interaction(self) -> SettingRowInteraction {
match self {
Self::Appearance | Self::Language => SettingRowInteraction::Cycle,
Self::SyncOffline | Self::Notifications => SettingRowInteraction::Toggle,
Self::Account
| Self::Workspace
| Self::Editor
| Self::Storage
| Self::Experimental
| Self::About => SettingRowInteraction::Info,
}
}
pub const fn a11y_key(self) -> &'static str {
match self {
Self::Account => "account",
Self::Workspace => "workspace",
Self::Appearance => "appearance",
Self::Language => "language",
Self::Editor => "editor",
Self::SyncOffline => "sync_offline",
Self::Storage => "storage",
Self::Notifications => "notifications",
Self::Experimental => "experimental",
Self::About => "about",
}
}
}
/// Full 10-group mobile settings model.
@@ -190,6 +228,7 @@ pub struct WorkspaceData {
pub link_graph: LinkGraph,
pub workspace_index_seeded: bool,
pub history: NavHistory,
pub next_doc_seq: u64,
}
/// Document record stored in the mobile shell view model.
@@ -204,6 +243,18 @@ pub struct MobileDocRecord {
pub trashed: bool,
pub journal_date: Option<String>,
pub clock: u64,
pub outgoing_edges: Vec<DocRefEdge>,
}
impl MobileDocRecord {
/// Localized display title, falling back to the locale's untitled placeholder when empty.
pub fn display_title(&self, locale: MobileLocale) -> String {
if self.title.trim().is_empty() {
locale.strings().untitled_doc.to_string()
} else {
self.title.clone()
}
}
}
/// Result of dispatching a platform back gesture through [`MobileBackCoordinator`].
@@ -253,6 +304,8 @@ pub struct MobileAppState {
pub active_sheet: MobileSheet,
/// Retains the sheet kind while its closing transition finishes so content never flashes empty.
pub closing_sheet: Option<MobileSheet>,
/// Scoped `(workspace_id, doc_id)` awaiting confirmation in `MobileSheet::ConfirmDeleteDoc`.
pub pending_delete_target: Option<(String, String)>,
/// Accessibility node ID of the control that opened the active sheet (restored on close).
pub sheet_trigger_a11y_id: Option<String>,
/// Active semantic focus target exported into `AccessibilityTree`.
@@ -260,7 +313,11 @@ pub struct MobileAppState {
pub sheet_motion: Sheet,
pub tab_anim_start_ms: f64,
pub page_overlay_active: bool,
pub explorer_scroll_y: f32,
pub explorer_scroll_by_seq: std::collections::HashMap<u64, f32>,
pub today_date: String,
pub selected_journal_date: String,
pub next_doc_seq: u64,
pub search_query: String,
pub search_selection: Range<usize>,
pub search_preedit: Option<Range<usize>>,
@@ -312,6 +369,7 @@ impl MobileAppState {
prev.link_graph = self.link_graph.clone();
prev.workspace_index_seeded = self.workspace_index_seeded;
prev.history = self.history.clone();
prev.next_doc_seq = self.next_doc_seq;
}
// Load incoming workspace slice.
self.active_workspace_idx = idx;
@@ -327,10 +385,15 @@ impl MobileAppState {
self.link_graph = next.link_graph;
self.workspace_index_seeded = next.workspace_index_seeded;
self.history = next.history;
self.next_doc_seq = next.next_doc_seq;
self.selected_journal_date = self.today_date.clone();
self.search_query.clear();
self.search_selection = 0..0;
self.search_preedit = None;
self.page_overlay_active = false;
self.pending_delete_target = None;
self.explorer_scroll_y = 0.0;
self.explorer_scroll_by_seq.clear();
self.sync_route_from_history();
self.close_sheet(now_ms);
}
@@ -383,13 +446,17 @@ impl MobileAppState {
self.sync_route_from_history();
return;
}
self.save_current_explorer_scroll();
self.history.push(self.scope.clone(), target, origin, None);
self.explorer_scroll_y = 0.0;
self.sync_route_from_history();
}
pub fn switch_tab(&mut self, tab: MobileTab, now_ms: f64) {
self.save_current_explorer_scroll();
self.active_tab = tab;
self.tab_anim_start_ms = now_ms;
self.explorer_scroll_y = 0.0;
let target = match tab {
MobileTab::Home => NavTarget::Home,
MobileTab::Explorer => NavTarget::AllDocs,
@@ -407,6 +474,7 @@ impl MobileAppState {
.current()
.is_some_and(|e| e.target == target && e.scope == self.scope);
if already_same_root {
self.restore_current_explorer_scroll();
return;
}
// Switching between top-level root tabs resets the root entry instead of piling up
@@ -420,6 +488,7 @@ impl MobileAppState {
});
if at_single_root {
self.history = NavHistory::new();
self.explorer_scroll_by_seq.clear();
}
self.history.push(
self.scope.clone(),
@@ -458,6 +527,7 @@ impl MobileAppState {
if self.active_sheet != MobileSheet::None {
self.closing_sheet = Some(self.active_sheet);
self.active_sheet = MobileSheet::None;
self.pending_delete_target = None;
self.focused_a11y_id = self.sheet_trigger_a11y_id.take();
self.sheet_motion.close(now_ms);
}
@@ -535,6 +605,7 @@ impl MobileAppState {
self.route = MobileRoute::Settings;
}
}
self.restore_current_explorer_scroll();
}
pub fn breadcrumb_snapshot(&mut self) -> WorkspaceBreadcrumbSnapshot {
@@ -543,6 +614,7 @@ impl MobileAppState {
self.folder_revision,
&self.folder_rows,
);
let locale = self.locale();
let docs = self
.docs
.iter()
@@ -550,7 +622,7 @@ impl MobileAppState {
(
d.id.clone(),
DocMetaSnapshot {
title: d.title.clone(),
title: d.display_title(locale),
trashed: d.trashed,
journal_date: d.journal_date.clone(),
revoked_or_deleted: false,
+310
View File
@@ -0,0 +1,310 @@
//! Scoped document creation, journal management, trash restore/delete with confirmation,
//! settings toggles, and Explorer vertical scroll helpers on [`MobileAppState`].
use affine_client::{DirectKind, NavTarget, Origin};
use affine_store::workspace_db::FolderRow;
use crate::{
state::{MobileAppState, MobileDocRecord, MobileSheet, SettingsGroupId, ThemePreference},
strings::MobileLocale,
};
const BASE62_ALPHABET: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
/// Encode `(ws_id, doc_id)` with an unambiguous byte-length prefix (`"{ws_len}:{ws_id}{doc_id}"`)
/// so workspace or document IDs containing `.` or `:` never collide.
pub fn encode_scoped_doc_target(ws_id: &str, doc_id: &str) -> String {
format!("{}:{ws_id}{doc_id}", ws_id.len())
}
/// Decode a length-prefixed scoped document target created by [`encode_scoped_doc_target`].
pub fn decode_scoped_doc_target(raw: &str) -> Option<(&str, &str)> {
let (len_str, rest) = raw.split_once(':')?;
let ws_len: usize = len_str.parse().ok()?;
if ws_len > rest.len() || !rest.is_char_boundary(ws_len) {
return None;
}
Some((&rest[..ws_len], &rest[ws_len..]))
}
/// Generate a valid fractional-index key strictly greater than `max_existing` in ASCII order.
pub(crate) fn next_fractional_index(max_existing: Option<&str>) -> String {
let Some(last) = max_existing.filter(|s| !s.is_empty()) else {
return "a0".to_string();
};
let bytes = last.as_bytes();
if let Some(&tail) = bytes.last()
&& let Some(pos) = BASE62_ALPHABET.iter().position(|&b| b == tail)
&& pos + 1 < BASE62_ALPHABET.len()
{
let mut next = bytes[..bytes.len() - 1].to_vec();
next.push(BASE62_ALPHABET[pos + 1]);
if let Ok(s) = String::from_utf8(next) {
return s;
}
}
format!("{last}V")
}
impl MobileAppState {
pub fn active_workspace_id(&self) -> &str {
&self.scope.workspace_id
}
pub(crate) fn sync_active_workspace_doc_count(&mut self) {
let active_count = self.docs.iter().filter(|d| !d.trashed).count();
if let Some(ws) = self.workspaces.get_mut(self.active_workspace_idx) {
ws.doc_count = active_count;
}
if let Some(store) = self.workspace_store.get_mut(self.active_workspace_idx) {
store.summary.doc_count = active_count;
}
}
/// 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) {
let ceiling = max_scroll.max(0.0);
self.explorer_scroll_y = (self.explorer_scroll_y + delta_y).clamp(0.0, ceiling);
if let Some(seq) = self.history.current().map(|e| e.seq) {
self.explorer_scroll_by_seq
.insert(seq, self.explorer_scroll_y);
}
}
pub(crate) fn save_current_explorer_scroll(&mut self) {
if self.route == crate::state::MobileRoute::Explorer
&& let Some(seq) = self.history.current().map(|e| e.seq)
{
self.explorer_scroll_by_seq
.insert(seq, self.explorer_scroll_y.max(0.0));
}
}
pub(crate) fn restore_current_explorer_scroll(&mut self) {
if self.route == crate::state::MobileRoute::Explorer {
self.explorer_scroll_y = self
.history
.current()
.and_then(|e| self.explorer_scroll_by_seq.get(&e.seq).copied())
.unwrap_or(0.0);
}
}
/// Create a new document in the active workspace, optionally placing a folder link under
/// `folder_id`, and immediately open it.
pub fn create_doc(&mut self, folder_id: Option<&str>, now_ms: f64) -> String {
let seq = self.next_doc_seq;
self.next_doc_seq += 1;
let ws_id = self.scope.workspace_id.clone();
let doc_id = format!("doc-{ws_id}-new-{seq}");
let updated_at_ms = 1_764_001_000 + (now_ms.max(0.0) as i64) + (seq as i64);
self.docs.insert(
0,
MobileDocRecord {
id: doc_id.clone(),
title: String::new(),
body_preview: String::new(),
tags: Vec::new(),
updated_at_ms,
is_favorite: false,
trashed: false,
journal_date: None,
clock: 1,
outgoing_edges: Vec::new(),
},
);
self.link_graph.replace_edges(&doc_id, Vec::new(), 1);
self.sync_active_workspace_doc_count();
if let Some(fid) = folder_id {
let link_id = format!("l-{ws_id}-new-{seq}");
let max_idx = self
.folder_rows
.iter()
.filter(|r| r.parent_id.as_deref() == Some(fid))
.map(|r| r.index.as_str())
.max();
let index = next_fractional_index(max_idx);
self.folder_rows.push(FolderRow {
id: link_id.clone(),
parent_id: Some(fid.to_string()),
data: doc_id.clone(),
folder_type: "doc".to_string(),
index,
});
self.folder_revision += 1;
self.open_doc(&doc_id, Origin::Placement { link_id });
} else {
self.open_doc(&doc_id, Origin::Direct(DirectKind::AllDocs));
}
doc_id
}
/// Select a calendar date in the `Journals` tab.
pub fn select_journal_date(&mut self, date: &str) {
self.selected_journal_date = date.to_string();
}
/// Open the existing journal document for `date` (restoring a trashed journal for `date` if
/// present to prevent duplicate per-date journals), or create a new one bound to `date` and
/// open it with `Origin::Journal`.
pub fn open_or_create_journal_for_date(&mut self, date: &str, now_ms: f64) -> String {
if let Some(existing_id) = self
.docs
.iter()
.find(|d| !d.trashed && d.journal_date.as_deref() == Some(date))
.map(|d| d.id.clone())
{
self.open_doc(&existing_id, Origin::Journal);
return existing_id;
}
if let Some(trashed_id) = self
.docs
.iter()
.find(|d| d.trashed && d.journal_date.as_deref() == Some(date))
.map(|d| d.id.clone())
{
let ws_id = self.scope.workspace_id.clone();
self.restore_doc_scoped(&ws_id, &trashed_id);
self.open_doc(&trashed_id, Origin::Journal);
return trashed_id;
}
let seq = self.next_doc_seq;
self.next_doc_seq += 1;
let ws_id = self.scope.workspace_id.clone();
let doc_id = format!("doc-{ws_id}-journal-{date}-{seq}");
let updated_at_ms = 1_764_001_000 + (now_ms.max(0.0) as i64) + (seq as i64);
self.docs.insert(
0,
MobileDocRecord {
id: doc_id.clone(),
title: format!("Journal {date}"),
body_preview: String::new(),
tags: vec!["daily".to_string()],
updated_at_ms,
is_favorite: false,
trashed: false,
journal_date: Some(date.to_string()),
clock: 1,
outgoing_edges: Vec::new(),
},
);
self.link_graph.replace_edges(&doc_id, Vec::new(), 1);
self.sync_active_workspace_doc_count();
self.open_doc(&doc_id, Origin::Journal);
doc_id
}
/// Open the two-step permanent-delete confirmation sheet for `(ws_id, doc_id)` only when
/// `ws_id` matches the active workspace and `doc_id` is currently in Trash.
pub fn request_delete_doc_scoped(
&mut self,
ws_id: &str,
doc_id: &str,
trigger_a11y_id: Option<&str>,
now_ms: f64,
) -> bool {
if self.scope.workspace_id != ws_id {
return false;
}
if !self.docs.iter().any(|d| d.id == doc_id && d.trashed) {
return false;
}
self.pending_delete_target = Some((ws_id.to_string(), doc_id.to_string()));
self.open_sheet_from(MobileSheet::ConfirmDeleteDoc, trigger_a11y_id, now_ms);
true
}
/// Restore a trashed document scoped to `(ws_id, doc_id)`, synchronizing its `link_graph`
/// clock so workspace backlinks stay `Ready`.
pub fn restore_doc_scoped(&mut self, ws_id: &str, doc_id: &str) -> bool {
if self.scope.workspace_id != ws_id {
return false;
}
let Some(doc) = self.docs.iter_mut().find(|d| d.id == doc_id && d.trashed) else {
return false;
};
doc.trashed = false;
doc.clock += 1;
let edges = doc.outgoing_edges.clone();
let clock = doc.clock;
self.link_graph.replace_edges(doc_id, edges, clock);
self.sync_active_workspace_doc_count();
true
}
/// Permanently delete a trashed document scoped to `(ws_id, doc_id)`, purge all history
/// entries pointing to it, close the confirmation sheet, and navigate safely.
pub fn delete_doc_permanently_scoped(
&mut self,
ws_id: &str,
doc_id: &str,
now_ms: f64,
) -> bool {
if self.scope.workspace_id != ws_id {
return false;
}
if !self.docs.iter().any(|d| d.id == doc_id && d.trashed) {
return false;
}
self.docs.retain(|d| d.id != doc_id);
let rows_before = self.folder_rows.len();
self.folder_rows
.retain(|r| !(r.folder_type == "doc" && r.data == doc_id));
if self.folder_rows.len() != rows_before {
self.folder_revision += 1;
}
for col in &mut self.collections {
col.doc_ids.retain(|id| id != doc_id);
}
self.link_graph.replace_edges(doc_id, Vec::new(), u64::MAX);
self.sync_active_workspace_doc_count();
self.pending_delete_target = None;
self.close_sheet(now_ms);
self.history
.remove_target(&self.scope, &NavTarget::Doc(doc_id.to_string()));
if self.history.is_empty() {
self.history.push(
self.scope.clone(),
NavTarget::AllDocs,
Origin::Direct(DirectKind::AllDocs),
None,
);
}
self.sync_route_from_history();
true
}
/// Apply an in-place toggle or cycle action for an interactive Settings row.
pub fn activate_setting(&mut self, group: SettingsGroupId) -> bool {
match group {
SettingsGroupId::Appearance => {
self.settings.theme_preference = match self.settings.theme_preference {
ThemePreference::Light => ThemePreference::Dark,
ThemePreference::Dark => ThemePreference::System,
ThemePreference::System => ThemePreference::Light,
};
true
}
SettingsGroupId::Language => {
self.settings.locale = match self.settings.locale {
MobileLocale::En => MobileLocale::ZhHans,
MobileLocale::ZhHans => MobileLocale::Ar,
MobileLocale::Ar => MobileLocale::En,
};
true
}
SettingsGroupId::SyncOffline => {
self.settings.offline_sync_enabled = !self.settings.offline_sync_enabled;
true
}
SettingsGroupId::Notifications => {
self.settings.push_notifications = !self.settings.push_notifications;
true
}
_ => false,
}
}
}
+114 -5
View File
@@ -21,6 +21,14 @@ impl MobileLocale {
}
}
pub const fn display_name(self) -> &'static str {
match self {
Self::En => "English",
Self::ZhHans => "简体中文",
Self::Ar => "العربية",
}
}
pub const fn direction(self) -> Direction {
match self {
Self::Ar => Direction::Rtl,
@@ -55,12 +63,18 @@ pub struct MobileStrings {
pub recent_docs: &'static str,
pub favorites: &'static str,
pub folders: &'static str,
pub documents_heading: &'static str,
pub new_doc_label: &'static str,
pub untitled_doc: &'static str,
pub collections: &'static str,
pub tags: &'static str,
pub trash: &'static str,
pub today_journal: &'static str,
pub open_journal: &'static str,
pub create_journal: &'static str,
pub no_journal_for_date: &'static str,
pub search_placeholder: &'static str,
pub search_no_results: &'static str,
pub exact_match_badge: &'static str,
pub settings_title: &'static str,
pub back_label: &'static str,
@@ -73,6 +87,16 @@ pub struct MobileStrings {
pub backlinks_ready_zero: &'static str,
pub backlinks_partial_suffix: &'static str,
pub in_trash_badge: &'static str,
pub restore_doc_label: &'static str,
pub delete_permanently_label: &'static str,
pub confirm_delete_title: &'static str,
pub confirm_delete_body: &'static str,
pub cancel_label: &'static str,
pub doc_not_found_title: &'static str,
pub doc_not_found_body: &'static str,
pub toggle_on: &'static str,
pub toggle_off: &'static str,
pub weekday_short: [&'static str; 7],
pub close_label: &'static str,
pub settings_groups: [&'static str; 10],
pub theme_light: &'static str,
@@ -103,6 +127,20 @@ impl MobileStrings {
}
}
pub fn compact_owner_multi_location_label(
&self,
locale: MobileLocale,
owner_title: &str,
count: usize,
) -> String {
let short = truncate_display_width(owner_title, 12);
match locale {
MobileLocale::En => format!("{short} · {count} locations"),
MobileLocale::ZhHans => format!("{short} 的 {count} 个位置"),
MobileLocale::Ar => format!("{short} ({count} مواقع)"),
}
}
pub fn backlinks_pill_label(
&self,
locale: MobileLocale,
@@ -123,6 +161,29 @@ impl MobileStrings {
}
}
fn char_display_width(ch: char) -> usize {
if ch.is_ascii() { 1 } else { 2 }
}
fn truncate_display_width(text: &str, max_units: usize) -> String {
let total: usize = text.chars().map(char_display_width).sum();
if total <= max_units {
return text.to_string();
}
let budget = max_units.saturating_sub(2);
let mut used = 0usize;
let mut prefix = String::new();
for ch in text.chars() {
let w = char_display_width(ch);
if used + w > budget {
break;
}
prefix.push(ch);
used += w;
}
format!("{}…", prefix.trim_end())
}
const EN_STRINGS: MobileStrings = MobileStrings {
tab_home: "Home",
tab_explorer: "All Docs",
@@ -131,12 +192,18 @@ const EN_STRINGS: MobileStrings = MobileStrings {
recent_docs: "Recent Documents",
favorites: "Favorites",
folders: "Folders",
documents_heading: "Documents",
new_doc_label: "New Document",
untitled_doc: "Untitled",
collections: "Collections",
tags: "Tags",
trash: "Trash",
today_journal: "Today's Journal",
open_journal: "Open Journal",
create_journal: "New Journal Entry",
search_placeholder: "Exact substring search…",
no_journal_for_date: "No journal entry for this date yet.",
search_placeholder: "Search docs…",
search_no_results: "No matching documents",
exact_match_badge: "Exact Match",
settings_title: "Settings",
back_label: "Back",
@@ -149,6 +216,16 @@ const EN_STRINGS: MobileStrings = MobileStrings {
backlinks_ready_zero: "No backlinks",
backlinks_partial_suffix: "Indexing…",
in_trash_badge: "In Trash",
restore_doc_label: "Restore",
delete_permanently_label: "Delete Permanently",
confirm_delete_title: "Delete Permanently?",
confirm_delete_body: "This action cannot be undone. The document and its links will be removed from this workspace.",
cancel_label: "Cancel",
doc_not_found_title: "Document not found",
doc_not_found_body: "This document was deleted or is no longer available in this workspace.",
toggle_on: "On",
toggle_off: "Off",
weekday_short: ["M", "T", "W", "T", "F", "S", "S"],
close_label: "Done",
settings_groups: [
"Account",
@@ -176,12 +253,18 @@ const ZH_STRINGS: MobileStrings = MobileStrings {
recent_docs: "最近文档",
favorites: "收藏夹",
folders: "文件夹",
documents_heading: "文档",
new_doc_label: "新建文档",
untitled_doc: "无标题",
collections: "集合",
tags: "标签",
trash: "回收站",
today_journal: "今日日记",
create_journal: "新建今日日记",
search_placeholder: "精确子串搜索…",
open_journal: "打开日记",
create_journal: "新建日记",
no_journal_for_date: "该日期尚未创建日记。",
search_placeholder: "搜索文档…",
search_no_results: "无匹配结果",
exact_match_badge: "精确匹配",
settings_title: "设置",
back_label: "返回",
@@ -194,6 +277,16 @@ const ZH_STRINGS: MobileStrings = MobileStrings {
backlinks_ready_zero: "暂无引用",
backlinks_partial_suffix: "索引中",
in_trash_badge: "已移入回收站",
restore_doc_label: "恢复",
delete_permanently_label: "永久删除",
confirm_delete_title: "永久删除此文档?",
confirm_delete_body: "此操作不可撤销,该文档及其所有链接将从当前工作区永久移除。",
cancel_label: "取消",
doc_not_found_title: "文档不存在",
doc_not_found_body: "该文档已被删除或不在当前工作区中。",
toggle_on: "已开启",
toggle_off: "已关闭",
weekday_short: ["一", "二", "三", "四", "五", "六", "日"],
close_label: "完成",
settings_groups: [
"账户",
@@ -221,12 +314,18 @@ const AR_STRINGS: MobileStrings = MobileStrings {
recent_docs: "المستندات الأخيرة",
favorites: "المفضلة",
folders: "المجلدات",
documents_heading: "المستندات",
new_doc_label: "مستند جديد",
untitled_doc: "بدون عنوان",
collections: "المجموعات",
tags: "الوسوم",
trash: "المهملات",
today_journal: "يومية اليوم",
create_journal: "إنشاء يومية جديدة",
search_placeholder: "بحث نصي دقيق…",
open_journal: "فتح اليومية",
create_journal: "إدخال يومية جديد",
no_journal_for_date: "لا توجد يومية لهذا التاريخ بعد.",
search_placeholder: "البحث في المستندات…",
search_no_results: "لا توجد نتائج",
exact_match_badge: "مطابقة دقيقة",
settings_title: "الإعدادات",
back_label: "رجوع",
@@ -239,6 +338,16 @@ const AR_STRINGS: MobileStrings = MobileStrings {
backlinks_ready_zero: "لا توجد روابط خلفية",
backlinks_partial_suffix: "جارٍ الفهرسة",
in_trash_badge: "في المهملات",
restore_doc_label: "استعادة",
delete_permanently_label: "حذف نهائي",
confirm_delete_title: "حذف المستند نهائياً؟",
confirm_delete_body: "لا يمكن التراجع عن هذا الإجراء. سيتم حذف المستند وجميع روابطه من مساحة العمل.",
cancel_label: "إلغاء",
doc_not_found_title: "المستند غير موجود",
doc_not_found_body: "تم حذف هذا المستند أو لم يعد متاحاً في مساحة العمل هذه.",
toggle_on: "مفعّل",
toggle_off: "متوقف",
weekday_short: ["ن", "ث", "ر", "خ", "ج", "س", "ح"],
close_label: "تم",
settings_groups: [
"الحساب",
+350 -414
View File
@@ -8,30 +8,18 @@ use ui::{
};
use ui_kit::LogicalStyled;
use crate::{a11y::derive_explorer_doc_origin, state::MobileAppState, strings::MobileStrings};
use crate::{state::MobileAppState, strings::MobileStrings};
use super::{
A11yBoundsMap, CHEVRON_LEFT_SVG, EXPLORER_ICON_SVG, MobileFlexExt, MobilePalette,
MobileShellView, a11y_bounds_probe,
A11yBoundsMap, EXPLORER_ICON_SVG, MobileFlexExt, MobilePalette, MobileShellView,
a11y_bounds_probe,
explorer_rows::{
ExplorerEnv, drilldown_header, explorer_compact_meta_cell, explorer_doc_row,
explorer_meta_row, explorer_scroll_viewport, new_doc_button, render_collection_drilldown,
render_tag_drilldown, render_trash_drilldown, row_dir,
},
};
#[derive(Clone, Copy)]
struct ExplorerEnv<'a> {
palette: MobilePalette,
dir: Direction,
strings: &'static MobileStrings,
a11y_bounds: &'a A11yBoundsMap,
}
fn row_dir(dir: Direction) -> ui::Div {
let d = div().flex().flex_row().items_center();
if dir.is_rtl() {
d.dir_rtl()
} else {
d.dir_ltr()
}
}
pub(super) fn render_explorer(
state: &mut MobileAppState,
viewport_h: f32,
@@ -55,19 +43,21 @@ pub(super) fn render_explorer(
match cur_target {
NavTarget::Folder(folder_id) => {
render_folder_drilldown(state, &folder_id, env, cx).into_any_element()
render_folder_drilldown(state, &folder_id, viewport_h, env, cx).into_any_element()
}
NavTarget::Collection(col_id) if col_id.is_empty() => {
render_collections_index(state, env, cx).into_any_element()
render_collections_index(state, viewport_h, env, cx).into_any_element()
}
NavTarget::Collection(col_id) => {
render_collection_drilldown(state, &col_id, env, cx).into_any_element()
render_collection_drilldown(state, &col_id, viewport_h, env, cx).into_any_element()
}
NavTarget::Tag(tag_id) if tag_id.is_empty() => {
render_tags_index(state, env, cx).into_any_element()
render_tags_index(state, viewport_h, env, cx).into_any_element()
}
NavTarget::Tag(tag_id) => render_tag_drilldown(state, &tag_id, env, cx).into_any_element(),
NavTarget::Trash => render_trash_drilldown(state, env, cx).into_any_element(),
NavTarget::Tag(tag_id) => {
render_tag_drilldown(state, &tag_id, viewport_h, env, cx).into_any_element()
}
NavTarget::Trash => render_trash_drilldown(state, viewport_h, env, cx).into_any_element(),
_ => render_all_docs_root(state, viewport_h, env, cx).into_any_element(),
}
}
@@ -79,7 +69,24 @@ fn render_all_docs_root(
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let (palette, dir, strings) = (env.palette, env.dir, env.strings);
let locale = state.locale();
let ws_id = state.active_workspace_id().to_string();
let compact = viewport_h < 460.0;
let tight_portrait = !compact && viewport_h < 620.0;
let row_h = if compact || tight_portrait {
44.0
} else {
46.0
};
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 { 12.0 };
let heading_h = 16.0;
let forest_state = state.forest_state();
let folder_items: Vec<(String, String, usize)> = match forest_state {
FolderForestState::Ready(forest) => forest
@@ -90,6 +97,43 @@ fn render_all_docs_root(
FolderForestState::Unresolved => Vec::new(),
};
let trash_count = state.docs.iter().filter(|d| d.trashed).count();
let active_docs: Vec<(String, String)> = state
.docs
.iter()
.filter(|d| !d.trashed)
.map(|d| (d.id.clone(), d.display_title(locale)))
.collect();
let folder_h = (folder_items.len() as f32) * row_h + 2.0;
let org_h = if tight_portrait {
44.0 + 2.0
} else {
3.0 * row_h + 2.0
};
let docs_h = if active_docs.is_empty() {
0.0
} else {
(active_docs.len() as f32) * row_h + 2.0
};
let docs_top = if compact {
pad + 1.0
} else {
pad + heading_h + gap + folder_h + gap + org_h + gap + heading_h + gap + 1.0
};
let content_h = if compact {
pad * 2.0 + folder_h.max(org_h).max(docs_h)
} else if active_docs.is_empty() {
pad * 2.0 + heading_h + gap + folder_h + gap + org_h
} else {
pad * 2.0 + heading_h + gap + folder_h + gap + org_h + gap + heading_h + gap + docs_h
};
let max_scroll = (content_h - avail_h).max(0.0);
state.explorer_scroll_y = state.explorer_scroll_y.clamp(0.0, max_scroll);
let scroll_y = state.explorer_scroll_y;
let is_visible = |top_in_content: f32, h: f32| -> bool {
let vis_top = top_in_content - scroll_y;
vis_top >= -1.0 && vis_top + h <= avail_h + 1.0
};
let header = row_dir(dir)
.id("mobile.explorer.header")
@@ -97,20 +141,28 @@ fn render_all_docs_root(
.w_full()
.h(px(56.0))
.flex_shrink(0.0)
.justify_between()
.bg(palette.bg_surface)
.border_b_1()
.border_color(palette.border)
.ps(px(16.0), dir)
.pe(px(16.0), dir)
.pe(px(12.0), dir)
.child(
div()
.w_full()
.flex_1()
.min_w(px(0.0))
.text_size(px(18.0))
.text_color(palette.text_primary)
.align_start_for(dir)
.child(strings.tab_explorer),
);
)
.child(new_doc_button(None, env, cx));
let folder_top = if compact {
pad + 1.0
} else {
pad + heading_h + gap + 1.0
};
let mut folder_card = div()
.w_full()
.rounded(px(12.0))
@@ -125,12 +177,13 @@ fn render_all_docs_root(
let indent = 14.0 + (depth.min(6) as f32) * 16.0;
let folder_id = id.clone();
let row_id = format!("mobile.explorer.folder.{id}");
let row_vis = is_visible(folder_top + (idx as f32) * row_h, row_h);
let mut row = row_dir(dir)
.id(row_id.clone())
.snapshot(row_id.clone(), Some("mobile.shell.root"))
.relative()
.w_full()
.h(px(46.0))
.h(px(row_h))
.flex_shrink(0.0)
.gap(px(10.0))
.ps(px(indent), dir)
.pe(px(14.0), dir)
@@ -142,7 +195,6 @@ fn render_all_docs_root(
);
cx.notify();
}))
.child(a11y_bounds_probe(row_id, env.a11y_bounds.clone()))
.child(
svg()
.data(EXPLORER_ICON_SVG)
@@ -160,78 +212,176 @@ fn render_all_docs_root(
.align_start_for(dir)
.child(name),
);
if row_vis {
row = row
.snapshot(row_id.clone(), Some("mobile.shell.root"))
.child(a11y_bounds_probe(row_id, env.a11y_bounds.clone()));
}
if idx > 0 {
row = row.border_t(px(1.0)).border_color(palette.border);
}
folder_card = folder_card.child(row);
}
let org_card = div()
.w_full()
.rounded(px(12.0))
.bg(palette.bg_surface)
.border_1()
.border_color(palette.border)
.flex()
.flex_col()
.overflow_hidden()
.child(explorer_meta_row(
"mobile.explorer.collections",
strings.collections,
state.collections.len(),
NavTarget::Collection(String::new()),
env,
false,
cx,
))
.child(explorer_meta_row(
"mobile.explorer.tags",
strings.tags,
state.tags.len(),
NavTarget::Tag(String::new()),
env,
true,
cx,
))
.child(explorer_meta_row(
"mobile.explorer.trash",
strings.trash,
trash_count,
NavTarget::Trash,
env,
true,
cx,
));
let content = if compact {
let org_top = if compact {
pad + 1.0
} else {
pad + heading_h + gap + folder_h + gap + 1.0
};
let org_card = if tight_portrait {
row_dir(dir)
.flex_1()
.min_h(px(0.0))
.p(px(12.0))
.gap(px(12.0))
.items_start()
.w_full()
.rounded(px(12.0))
.bg(palette.bg_surface)
.border_1()
.border_color(palette.border)
.overflow_hidden()
.child(div().flex_1().min_w(px(0.0)).child(folder_card))
.child(div().flex_1().min_w(px(0.0)).child(org_card))
.child(explorer_compact_meta_cell(
"mobile.explorer.collections",
strings.collections,
state.collections.len(),
NavTarget::Collection(String::new()),
env,
false,
cx,
))
.child(explorer_compact_meta_cell(
"mobile.explorer.tags",
strings.tags,
state.tags.len(),
NavTarget::Tag(String::new()),
env,
true,
cx,
))
.child(explorer_compact_meta_cell(
"mobile.explorer.trash",
strings.trash,
trash_count,
NavTarget::Trash,
env,
true,
cx,
))
.into_any_element()
} else {
div()
.flex_1()
.min_h(px(0.0))
.p(px(16.0))
.w_full()
.rounded(px(12.0))
.bg(palette.bg_surface)
.border_1()
.border_color(palette.border)
.flex()
.flex_col()
.gap(px(12.0))
.overflow_hidden()
.child(explorer_meta_row(
"mobile.explorer.collections",
strings.collections,
state.collections.len(),
NavTarget::Collection(String::new()),
row_h,
is_visible(org_top, row_h),
env,
false,
cx,
))
.child(explorer_meta_row(
"mobile.explorer.tags",
strings.tags,
state.tags.len(),
NavTarget::Tag(String::new()),
row_h,
is_visible(org_top + row_h, row_h),
env,
true,
cx,
))
.child(explorer_meta_row(
"mobile.explorer.trash",
strings.trash,
trash_count,
NavTarget::Trash,
row_h,
is_visible(org_top + row_h * 2.0, row_h),
env,
true,
cx,
))
.into_any_element()
};
let docs_card_opt = if active_docs.is_empty() {
None
} else {
let mut docs_card = div()
.w_full()
.rounded(px(12.0))
.bg(palette.bg_surface)
.border_1()
.border_color(palette.border)
.flex()
.flex_col()
.overflow_hidden();
for (idx, (doc_id, doc_title)) in active_docs.into_iter().enumerate() {
let row_vis = is_visible(docs_top + (idx as f32) * row_h, row_h);
docs_card = docs_card.child(explorer_doc_row(
&ws_id,
doc_id,
doc_title,
row_h,
idx > 0,
row_vis,
env,
cx,
));
}
Some(docs_card)
};
let inner: ui::AnyElement = if compact {
let mut row = row_dir(dir)
.w_full()
.p(px(pad))
.gap(px(10.0))
.items_start()
.child(div().flex_1().min_w(px(0.0)).child(folder_card))
.child(div().flex_1().min_w(px(0.0)).child(org_card));
if let Some(docs_card) = docs_card_opt {
row = row.child(div().flex_1().min_w(px(0.0)).child(docs_card));
}
row.into_any_element()
} else {
let mut col = div()
.w_full()
.p(px(pad))
.flex()
.flex_col()
.gap(px(gap))
.child(
div()
.w_full()
.h(px(heading_h))
.text_size(px(12.0))
.text_color(palette.text_secondary)
.align_start_for(dir)
.child(strings.folders),
)
.child(folder_card)
.child(org_card)
.child(org_card);
if let Some(docs_card) = docs_card_opt {
col = col
.child(
div()
.w_full()
.h(px(heading_h))
.text_size(px(12.0))
.text_color(palette.text_secondary)
.align_start_for(dir)
.child(strings.documents_heading),
)
.child(docs_card);
}
col.into_any_element()
};
div()
@@ -240,82 +390,19 @@ fn render_all_docs_root(
.flex_col()
.overflow_hidden()
.child(header)
.child(content)
}
fn drilldown_header(
title: String,
parent_target: NavTarget,
back_label: String,
env: ExplorerEnv<'_>,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let (palette, dir) = (env.palette, env.dir);
row_dir(dir)
.id("mobile.explorer.header")
.snapshot("mobile.explorer.header", Some("mobile.shell.root"))
.w_full()
.h(px(56.0))
.flex_shrink(0.0)
.bg(palette.bg_surface)
.border_b_1()
.border_color(palette.border)
.ps(px(8.0), dir)
.pe(px(16.0), dir)
.gap(px(8.0))
.child(
row_dir(dir)
.id("mobile.explorer.back_btn")
.snapshot("mobile.explorer.back_btn", Some("mobile.shell.root"))
.relative()
.h(px(44.0))
.min_w(px(64.0))
.gap(px(4.0))
.ps(px(4.0), dir)
.pe(px(8.0), dir)
.on_click(cx.listener(move |this, _, _, cx| {
let t = this.now_ms(cx);
this.state
.navigate_back_or_replace(parent_target.clone(), t);
cx.notify();
}))
.child(a11y_bounds_probe(
"mobile.explorer.back_btn",
env.a11y_bounds.clone(),
))
.child(
svg()
.data(CHEVRON_LEFT_SVG)
.mirror_in_rtl(true)
.w(px(15.0))
.h(px(15.0))
.text_color(palette.accent),
)
.child(
div()
.text_size(px(14.0))
.text_color(palette.accent)
.child(back_label),
),
)
.child(
div()
.flex_1()
.min_w(px(0.0))
.text_size(px(16.0))
.text_color(palette.text_primary)
.align_start_for(dir)
.child(title),
)
.child(explorer_scroll_viewport(scroll_y, max_scroll, inner, cx))
}
fn render_folder_drilldown(
state: &mut MobileAppState,
folder_id: &str,
viewport_h: f32,
env: ExplorerEnv<'_>,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let (palette, dir, strings) = (env.palette, env.dir, env.strings);
let locale = state.locale();
let ws_id = state.active_workspace_id().to_string();
let forest_state = state.forest_state();
let (title, parent_target, back_label, child_folders, doc_entries) = match forest_state {
FolderForestState::Ready(forest) => {
@@ -343,7 +430,8 @@ fn render_folder_drilldown(
.into_iter()
.filter_map(|p| {
let doc = state.doc_by_id(&p.doc_id)?;
(!doc.trashed).then(|| (p.link_id.clone(), doc.id.clone(), doc.title.clone()))
(!doc.trashed)
.then(|| (p.link_id.clone(), doc.id.clone(), doc.display_title(locale)))
})
.collect();
(title, parent_target, back_label, subs, docs)
@@ -357,6 +445,13 @@ fn render_folder_drilldown(
),
};
let avail_h = (viewport_h - 56.0 - 64.0).max(44.0);
let total_rows = child_folders.len() + doc_entries.len();
let content_h = 32.0 + (total_rows as f32) * 46.0 + 2.0;
let max_scroll = (content_h - avail_h).max(0.0);
state.explorer_scroll_y = state.explorer_scroll_y.clamp(0.0, max_scroll);
let scroll_y = state.explorer_scroll_y;
let mut list = div()
.w_full()
.rounded(px(12.0))
@@ -371,12 +466,14 @@ fn render_folder_drilldown(
for (sub_id, sub_name) in child_folders {
let nav_id = sub_id.clone();
let row_id = format!("mobile.explorer.folder.{sub_id}");
let top = 17.0 + (row_idx as f32) * 46.0 - scroll_y;
let row_vis = top >= -1.0 && top + 46.0 <= avail_h + 1.0;
let mut row = row_dir(dir)
.id(row_id.clone())
.snapshot(row_id.clone(), Some("mobile.shell.root"))
.relative()
.w_full()
.h(px(46.0))
.flex_shrink(0.0)
.gap(px(10.0))
.ps(px(14.0), dir)
.pe(px(14.0), dir)
@@ -387,7 +484,6 @@ fn render_folder_drilldown(
);
cx.notify();
}))
.child(a11y_bounds_probe(row_id, env.a11y_bounds.clone()))
.child(
svg()
.data(EXPLORER_ICON_SVG)
@@ -405,6 +501,11 @@ fn render_folder_drilldown(
.align_start_for(dir)
.child(sub_name),
);
if row_vis {
row = row
.snapshot(row_id.clone(), Some("mobile.shell.root"))
.child(a11y_bounds_probe(row_id, env.a11y_bounds.clone()));
}
if row_idx > 0 {
row = row.border_t(px(1.0)).border_color(palette.border);
}
@@ -413,48 +514,41 @@ fn render_folder_drilldown(
}
for (_link_id, doc_id, doc_title) in doc_entries {
let row_id = format!("mobile.explorer.doc.{doc_id}");
let mut row = row_dir(dir)
.id(row_id.clone())
.snapshot(row_id.clone(), Some("mobile.shell.root"))
.relative()
.w_full()
.h(px(46.0))
.ps(px(14.0), dir)
.pe(px(14.0), dir)
.on_click(cx.listener(move |this, _, _, cx| {
let origin = derive_explorer_doc_origin(&mut this.state, &doc_id);
this.state.open_doc(&doc_id, origin);
cx.notify();
}))
.child(a11y_bounds_probe(row_id, env.a11y_bounds.clone()))
.child(
div()
.flex_1()
.min_w(px(0.0))
.text_size(px(14.0))
.text_color(palette.text_primary)
.align_start_for(dir)
.child(doc_title),
);
if row_idx > 0 {
row = row.border_t(px(1.0)).border_color(palette.border);
}
list = list.child(row);
let top = 17.0 + (row_idx as f32) * 46.0 - scroll_y;
let row_vis = top >= -1.0 && top + 46.0 <= avail_h + 1.0;
list = list.child(explorer_doc_row(
&ws_id,
doc_id,
doc_title,
46.0,
row_idx > 0,
row_vis,
env,
cx,
));
row_idx += 1;
}
let inner = div().w_full().p(px(16.0)).child(list).into_any_element();
div()
.size_full()
.flex()
.flex_col()
.overflow_hidden()
.child(drilldown_header(title, parent_target, back_label, env, cx))
.child(div().flex_1().min_h(px(0.0)).p(px(16.0)).child(list))
.child(drilldown_header(
title,
parent_target,
back_label,
Some(folder_id.to_string()),
env,
cx,
))
.child(explorer_scroll_viewport(scroll_y, max_scroll, inner, cx))
}
fn render_collections_index(
state: &MobileAppState,
state: &mut MobileAppState,
viewport_h: f32,
env: ExplorerEnv<'_>,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
@@ -476,16 +570,19 @@ fn render_collections_index(
})
.collect();
render_index_list(
state,
env.strings.collections.to_string(),
env.strings.tab_explorer.to_string(),
items,
viewport_h,
env,
cx,
)
}
fn render_tags_index(
state: &MobileAppState,
state: &mut MobileAppState,
viewport_h: f32,
env: ExplorerEnv<'_>,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
@@ -507,68 +604,91 @@ fn render_tags_index(
})
.collect();
render_index_list(
state,
env.strings.tags.to_string(),
env.strings.tab_explorer.to_string(),
items,
viewport_h,
env,
cx,
)
}
#[allow(clippy::too_many_arguments)]
fn render_index_list(
state: &mut MobileAppState,
title: String,
back_label: String,
items: Vec<(String, String, usize, NavTarget)>,
viewport_h: f32,
env: ExplorerEnv<'_>,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let (palette, dir) = (env.palette, env.dir);
let mut list = div()
.w_full()
.rounded(px(12.0))
.bg(palette.bg_surface)
.border_1()
.border_color(palette.border)
.flex()
.flex_col()
.overflow_hidden();
for (idx, (row_id, label, count, target)) in items.into_iter().enumerate() {
let mut row = row_dir(dir)
.id(row_id.clone())
.snapshot(row_id.clone(), Some("mobile.shell.root"))
.relative()
let avail_h = (viewport_h - 56.0 - 64.0).max(44.0);
let content_h = 32.0 + (items.len() as f32) * 46.0 + 2.0;
let max_scroll = (content_h - avail_h).max(0.0);
state.explorer_scroll_y = state.explorer_scroll_y.clamp(0.0, max_scroll);
let scroll_y = state.explorer_scroll_y;
let inner: ui::AnyElement = if items.is_empty() {
div().w_full().p(px(16.0)).into_any_element()
} else {
let mut list = div()
.w_full()
.h(px(46.0))
.justify_between()
.ps(px(14.0), dir)
.pe(px(14.0), dir)
.on_click(cx.listener(move |this, _, _, cx| {
this.state
.navigate_target(target.clone(), Origin::Direct(DirectKind::AllDocs));
cx.notify();
}))
.child(a11y_bounds_probe(row_id, env.a11y_bounds.clone()))
.child(
div()
.text_size(px(14.0))
.text_color(palette.text_primary)
.child(label),
)
.child(
div()
.px(px(8.0))
.py(px(2.0))
.rounded(px(8.0))
.bg(palette.bg_pill)
.text_size(px(12.0))
.text_color(palette.text_secondary)
.child(count.to_string()),
);
if idx > 0 {
row = row.border_t(px(1.0)).border_color(palette.border);
.rounded(px(12.0))
.bg(palette.bg_surface)
.border_1()
.border_color(palette.border)
.flex()
.flex_col()
.overflow_hidden();
for (idx, (row_id, label, count, target)) in items.into_iter().enumerate() {
let top = 17.0 + (idx as f32) * 46.0 - scroll_y;
let row_vis = top >= -1.0 && top + 46.0 <= avail_h + 1.0;
let mut row = row_dir(dir)
.id(row_id.clone())
.relative()
.w_full()
.h(px(46.0))
.flex_shrink(0.0)
.justify_between()
.ps(px(14.0), dir)
.pe(px(14.0), dir)
.on_click(cx.listener(move |this, _, _, cx| {
this.state
.navigate_target(target.clone(), Origin::Direct(DirectKind::AllDocs));
cx.notify();
}))
.child(
div()
.text_size(px(14.0))
.text_color(palette.text_primary)
.child(label),
)
.child(
div()
.px(px(8.0))
.py(px(2.0))
.rounded(px(8.0))
.bg(palette.bg_pill)
.text_size(px(12.0))
.text_color(palette.text_secondary)
.child(count.to_string()),
);
if row_vis {
row = row
.snapshot(row_id.clone(), Some("mobile.shell.root"))
.child(a11y_bounds_probe(row_id, env.a11y_bounds.clone()));
}
if idx > 0 {
row = row.border_t(px(1.0)).border_color(palette.border);
}
list = list.child(row);
}
list = list.child(row);
}
div().w_full().p(px(16.0)).child(list).into_any_element()
};
div()
.size_full()
.flex()
@@ -578,193 +698,9 @@ fn render_index_list(
title,
NavTarget::AllDocs,
back_label,
None,
env,
cx,
))
.child(div().flex_1().min_h(px(0.0)).p(px(16.0)).child(list))
}
fn render_collection_drilldown(
state: &MobileAppState,
col_id: &str,
env: ExplorerEnv<'_>,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let col = state.collections.iter().find(|c| c.id == col_id);
let title = col
.map(|c| c.name.clone())
.unwrap_or_else(|| env.strings.collections.to_string());
let docs: Vec<(String, String)> = match col {
Some(c) => state
.docs
.iter()
.filter(|d| !d.trashed && c.doc_ids.iter().any(|id| id == &d.id))
.map(|d| (d.id.clone(), d.title.clone()))
.collect(),
None => Vec::new(),
};
render_doc_list_drilldown(
title,
NavTarget::Collection(String::new()),
env.strings.collections.to_string(),
docs,
env,
cx,
)
}
fn render_tag_drilldown(
state: &MobileAppState,
tag_id: &str,
env: ExplorerEnv<'_>,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let title = state
.tags
.iter()
.find(|(id, _)| id == tag_id)
.map(|(_, name)| format!("#{name}"))
.unwrap_or_else(|| format!("#{tag_id}"));
let docs: Vec<(String, String)> = state
.docs
.iter()
.filter(|d| !d.trashed && d.tags.iter().any(|t| t == tag_id))
.map(|d| (d.id.clone(), d.title.clone()))
.collect();
render_doc_list_drilldown(
title,
NavTarget::Tag(String::new()),
env.strings.tags.to_string(),
docs,
env,
cx,
)
}
fn render_trash_drilldown(
state: &MobileAppState,
env: ExplorerEnv<'_>,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let docs: Vec<(String, String)> = state
.docs
.iter()
.filter(|d| d.trashed)
.map(|d| (d.id.clone(), d.title.clone()))
.collect();
render_doc_list_drilldown(
env.strings.trash.to_string(),
NavTarget::AllDocs,
env.strings.tab_explorer.to_string(),
docs,
env,
cx,
)
}
fn render_doc_list_drilldown(
title: String,
parent_target: NavTarget,
back_label: String,
docs: Vec<(String, String)>,
env: ExplorerEnv<'_>,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let (palette, dir) = (env.palette, env.dir);
let mut list = div()
.w_full()
.rounded(px(12.0))
.bg(palette.bg_surface)
.border_1()
.border_color(palette.border)
.flex()
.flex_col()
.overflow_hidden();
for (idx, (doc_id, doc_title)) in docs.into_iter().enumerate() {
let row_id = format!("mobile.explorer.doc.{doc_id}");
let mut row = row_dir(dir)
.id(row_id.clone())
.snapshot(row_id.clone(), Some("mobile.shell.root"))
.relative()
.w_full()
.h(px(46.0))
.ps(px(14.0), dir)
.pe(px(14.0), dir)
.on_click(cx.listener(move |this, _, _, cx| {
let origin = derive_explorer_doc_origin(&mut this.state, &doc_id);
this.state.open_doc(&doc_id, origin);
cx.notify();
}))
.child(a11y_bounds_probe(row_id, env.a11y_bounds.clone()))
.child(
div()
.flex_1()
.min_w(px(0.0))
.text_size(px(14.0))
.text_color(palette.text_primary)
.align_start_for(dir)
.child(doc_title),
);
if idx > 0 {
row = row.border_t(px(1.0)).border_color(palette.border);
}
list = list.child(row);
}
div()
.size_full()
.flex()
.flex_col()
.overflow_hidden()
.child(drilldown_header(title, parent_target, back_label, env, cx))
.child(div().flex_1().min_h(px(0.0)).p(px(16.0)).child(list))
}
#[allow(clippy::too_many_arguments)]
fn explorer_meta_row(
id: &'static str,
label: &'static str,
count: usize,
target: NavTarget,
env: ExplorerEnv<'_>,
top_border: bool,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let (palette, dir) = (env.palette, env.dir);
let mut row = row_dir(dir)
.id(id)
.snapshot(id, Some("mobile.shell.root"))
.relative()
.w_full()
.h(px(46.0))
.justify_between()
.ps(px(14.0), dir)
.pe(px(14.0), dir)
.on_click(cx.listener(move |this, _, _, cx| {
this.state
.navigate_target(target.clone(), Origin::Direct(DirectKind::AllDocs));
cx.notify();
}))
.child(a11y_bounds_probe(id, env.a11y_bounds.clone()))
.child(
div()
.text_size(px(14.0))
.text_color(palette.text_primary)
.child(label),
)
.child(
div()
.px(px(8.0))
.py(px(2.0))
.rounded(px(8.0))
.bg(palette.bg_pill)
.text_size(px(12.0))
.text_color(palette.text_secondary)
.child(count.to_string()),
);
if top_border {
row = row.border_t(px(1.0)).border_color(palette.border);
}
row
.child(explorer_scroll_viewport(scroll_y, max_scroll, inner, cx))
}
@@ -0,0 +1,480 @@
//! Reusable row and header builders for the mobile `Explorer` (`All Docs`) route.
use affine_client::{DirectKind, NavTarget, Origin};
use ui::{
Context, Direction, InteractiveElement, IntoElement, ParentElement, StatefulInteractiveElement,
Styled, div, px, svg,
};
use ui_kit::LogicalStyled;
use crate::{a11y::derive_explorer_doc_origin, state::MobileAppState, strings::MobileStrings};
use super::{
A11yBoundsMap, CHEVRON_LEFT_SVG, MobileFlexExt, MobilePalette, MobileShellView, PLUS_ICON_SVG,
a11y_bounds_probe,
};
#[derive(Clone, Copy)]
pub(super) struct ExplorerEnv<'a> {
pub palette: MobilePalette,
pub dir: Direction,
pub strings: &'static MobileStrings,
pub a11y_bounds: &'a A11yBoundsMap,
}
pub(super) fn row_dir(dir: Direction) -> ui::Div {
let d = div().flex().flex_row().items_center();
if dir.is_rtl() {
d.dir_rtl()
} else {
d.dir_ltr()
}
}
pub(super) fn new_doc_button(
folder_id: Option<String>,
env: ExplorerEnv<'_>,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let palette = env.palette;
div()
.id("mobile.explorer.new_doc_btn")
.snapshot("mobile.explorer.new_doc_btn", Some("mobile.shell.root"))
.relative()
.w(px(44.0))
.h(px(44.0))
.flex_shrink(0.0)
.rounded(px(10.0))
.bg(palette.accent_soft)
.flex()
.items_center()
.justify_center()
.on_click(cx.listener(move |this, _, _, cx| {
let t = this.now_ms(cx);
this.state.create_doc(folder_id.as_deref(), t);
cx.notify();
}))
.child(a11y_bounds_probe(
"mobile.explorer.new_doc_btn",
env.a11y_bounds.clone(),
))
.child(
svg()
.data(PLUS_ICON_SVG)
.w(px(18.0))
.h(px(18.0))
.text_color(palette.accent),
)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn explorer_doc_row(
ws_id: &str,
doc_id: String,
doc_title: String,
row_h: f32,
top_border: bool,
publish_visible: bool,
env: ExplorerEnv<'_>,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let (palette, dir) = (env.palette, env.dir);
let row_id = format!(
"mobile.explorer.doc.{}",
crate::encode_scoped_doc_target(ws_id, &doc_id)
);
let mut row = row_dir(dir)
.id(row_id.clone())
.relative()
.w_full()
.h(px(row_h))
.flex_shrink(0.0)
.ps(px(14.0), dir)
.pe(px(14.0), dir)
.overflow_hidden()
.on_click(cx.listener(move |this, _, _, cx| {
let origin = derive_explorer_doc_origin(&mut this.state, &doc_id);
this.state.open_doc(&doc_id, origin);
cx.notify();
}))
.child(
div()
.flex_1()
.min_w(px(0.0))
.text_size(px(14.0))
.text_color(palette.text_primary)
.align_start_for(dir)
.overflow_hidden()
.child(doc_title),
);
if publish_visible {
row = row
.snapshot(row_id.clone(), Some("mobile.shell.root"))
.child(a11y_bounds_probe(row_id, env.a11y_bounds.clone()));
}
if top_border {
row = row.border_t(px(1.0)).border_color(palette.border);
}
row
}
/// Vertical scrollable viewport for Explorer content with wheel and pointer-drag scrolling.
pub(super) fn explorer_scroll_viewport(
scroll_y: f32,
max_scroll: f32,
inner: ui::AnyElement,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
div()
.id("mobile.explorer.scroll_viewport")
.flex_1()
.min_h(px(0.0))
.w_full()
.relative()
.overflow_hidden()
.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.scroll_explorer_by(-dy, max_scroll);
cx.notify();
}
}))
.child(div().w_full().mt(px(-scroll_y)).child(inner))
}
pub(super) fn drilldown_header(
title: String,
parent_target: NavTarget,
back_label: String,
new_doc_folder_id: Option<String>,
env: ExplorerEnv<'_>,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let (palette, dir) = (env.palette, env.dir);
let mut bar = row_dir(dir)
.id("mobile.explorer.header")
.snapshot("mobile.explorer.header", Some("mobile.shell.root"))
.w_full()
.h(px(56.0))
.flex_shrink(0.0)
.bg(palette.bg_surface)
.border_b_1()
.border_color(palette.border)
.ps(px(8.0), dir)
.pe(px(12.0), dir)
.gap(px(8.0))
.child(
row_dir(dir)
.id("mobile.explorer.back_btn")
.snapshot("mobile.explorer.back_btn", Some("mobile.shell.root"))
.relative()
.h(px(44.0))
.min_w(px(64.0))
.gap(px(4.0))
.ps(px(4.0), dir)
.pe(px(8.0), dir)
.on_click(cx.listener(move |this, _, _, cx| {
let t = this.now_ms(cx);
this.state
.navigate_back_or_replace(parent_target.clone(), t);
cx.notify();
}))
.child(a11y_bounds_probe(
"mobile.explorer.back_btn",
env.a11y_bounds.clone(),
))
.child(
svg()
.data(CHEVRON_LEFT_SVG)
.mirror_in_rtl(true)
.w(px(15.0))
.h(px(15.0))
.text_color(palette.accent),
)
.child(
div()
.text_size(px(14.0))
.text_color(palette.accent)
.child(back_label),
),
)
.child(
div()
.flex_1()
.min_w(px(0.0))
.text_size(px(16.0))
.text_color(palette.text_primary)
.align_start_for(dir)
.child(title),
);
if let Some(fid) = new_doc_folder_id {
bar = bar.child(new_doc_button(Some(fid), env, cx));
}
bar
}
#[allow(clippy::too_many_arguments)]
pub(super) fn explorer_meta_row(
id: &'static str,
label: &'static str,
count: usize,
target: NavTarget,
row_h: f32,
publish_visible: bool,
env: ExplorerEnv<'_>,
top_border: bool,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let (palette, dir) = (env.palette, env.dir);
let mut row = row_dir(dir)
.id(id)
.relative()
.w_full()
.h(px(row_h))
.flex_shrink(0.0)
.justify_between()
.ps(px(14.0), dir)
.pe(px(14.0), dir)
.on_click(cx.listener(move |this, _, _, cx| {
this.state
.navigate_target(target.clone(), Origin::Direct(DirectKind::AllDocs));
cx.notify();
}))
.child(
div()
.text_size(px(14.0))
.text_color(palette.text_primary)
.child(label),
)
.child(
div()
.px(px(8.0))
.py(px(2.0))
.rounded(px(8.0))
.bg(palette.bg_pill)
.text_size(px(12.0))
.text_color(palette.text_secondary)
.child(count.to_string()),
);
if publish_visible {
row = row
.snapshot(id, Some("mobile.shell.root"))
.child(a11y_bounds_probe(id, env.a11y_bounds.clone()));
}
if top_border {
row = row.border_t(px(1.0)).border_color(palette.border);
}
row
}
#[allow(clippy::too_many_arguments)]
pub(super) fn explorer_compact_meta_cell(
id: &'static str,
label: &'static str,
count: usize,
target: NavTarget,
env: ExplorerEnv<'_>,
leading_border: bool,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let (palette, dir) = (env.palette, env.dir);
let mut cell = row_dir(dir)
.id(id)
.snapshot(id, Some("mobile.shell.root"))
.relative()
.flex_1()
.min_w(px(0.0))
.h(px(44.0))
.justify_center()
.gap(px(4.0))
.px(px(6.0))
.overflow_hidden()
.on_click(cx.listener(move |this, _, _, cx| {
this.state
.navigate_target(target.clone(), Origin::Direct(DirectKind::AllDocs));
cx.notify();
}))
.child(a11y_bounds_probe(id, env.a11y_bounds.clone()))
.child(
div()
.text_size(px(12.0))
.text_color(palette.text_primary)
.overflow_hidden()
.child(label),
)
.child(
div()
.text_size(px(11.0))
.text_color(palette.text_secondary)
.child(count.to_string()),
);
if leading_border {
cell = if dir.is_rtl() {
cell.border_r(px(1.0)).border_color(palette.border)
} else {
cell.border_l(px(1.0)).border_color(palette.border)
};
}
cell
}
pub(super) fn render_collection_drilldown(
state: &mut MobileAppState,
col_id: &str,
viewport_h: f32,
env: ExplorerEnv<'_>,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let locale = state.locale();
let ws_id = state.active_workspace_id().to_string();
let col = state.collections.iter().find(|c| c.id == col_id);
let title = col
.map(|c| c.name.clone())
.unwrap_or_else(|| env.strings.collections.to_string());
let docs: Vec<(String, String)> = match col {
Some(c) => state
.docs
.iter()
.filter(|d| !d.trashed && c.doc_ids.iter().any(|id| id == &d.id))
.map(|d| (d.id.clone(), d.display_title(locale)))
.collect(),
None => Vec::new(),
};
render_doc_list_drilldown(
state,
ws_id,
title,
NavTarget::Collection(String::new()),
env.strings.collections.to_string(),
docs,
viewport_h,
env,
cx,
)
}
pub(super) fn render_tag_drilldown(
state: &mut MobileAppState,
tag_id: &str,
viewport_h: f32,
env: ExplorerEnv<'_>,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let locale = state.locale();
let ws_id = state.active_workspace_id().to_string();
let title = state
.tags
.iter()
.find(|(id, _)| id == tag_id)
.map(|(_, name)| format!("#{name}"))
.unwrap_or_else(|| format!("#{tag_id}"));
let docs: Vec<(String, String)> = state
.docs
.iter()
.filter(|d| !d.trashed && d.tags.iter().any(|t| t == tag_id))
.map(|d| (d.id.clone(), d.display_title(locale)))
.collect();
render_doc_list_drilldown(
state,
ws_id,
title,
NavTarget::Tag(String::new()),
env.strings.tags.to_string(),
docs,
viewport_h,
env,
cx,
)
}
pub(super) fn render_trash_drilldown(
state: &mut MobileAppState,
viewport_h: f32,
env: ExplorerEnv<'_>,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let locale = state.locale();
let ws_id = state.active_workspace_id().to_string();
let docs: Vec<(String, String)> = state
.docs
.iter()
.filter(|d| d.trashed)
.map(|d| (d.id.clone(), d.display_title(locale)))
.collect();
render_doc_list_drilldown(
state,
ws_id,
env.strings.trash.to_string(),
NavTarget::AllDocs,
env.strings.tab_explorer.to_string(),
docs,
viewport_h,
env,
cx,
)
}
#[allow(clippy::too_many_arguments)]
fn render_doc_list_drilldown(
state: &mut MobileAppState,
ws_id: String,
title: String,
parent_target: NavTarget,
back_label: String,
docs: Vec<(String, String)>,
viewport_h: f32,
env: ExplorerEnv<'_>,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let palette = env.palette;
let avail_h = (viewport_h - 56.0 - 64.0).max(44.0);
let content_h = 32.0 + (docs.len() as f32) * 46.0 + 2.0;
let max_scroll = (content_h - avail_h).max(0.0);
state.explorer_scroll_y = state.explorer_scroll_y.clamp(0.0, max_scroll);
let scroll_y = state.explorer_scroll_y;
let inner: ui::AnyElement = if docs.is_empty() {
div().w_full().p(px(16.0)).into_any_element()
} else {
let mut list = div()
.w_full()
.rounded(px(12.0))
.bg(palette.bg_surface)
.border_1()
.border_color(palette.border)
.flex()
.flex_col()
.overflow_hidden();
for (idx, (doc_id, doc_title)) in docs.into_iter().enumerate() {
let top = 17.0 + (idx as f32) * 46.0 - scroll_y;
let row_vis = top >= -1.0 && top + 46.0 <= avail_h + 1.0;
list = list.child(explorer_doc_row(
&ws_id,
doc_id,
doc_title,
46.0,
idx > 0,
row_vis,
env,
cx,
));
}
div().w_full().p(px(16.0)).child(list).into_any_element()
};
div()
.size_full()
.flex()
.flex_col()
.overflow_hidden()
.child(drilldown_header(
title,
parent_target,
back_label,
None,
env,
cx,
))
.child(explorer_scroll_viewport(scroll_y, max_scroll, inner, cx))
}
+22 -5
View File
@@ -2,12 +2,15 @@
//! `Focusable` + `EntityInputHandler` for Search IME, and live `AccessibilityTree` publication).
mod explorer;
mod explorer_rows;
mod page;
mod search;
mod settings;
mod sheet;
mod tabs;
pub(crate) use tabs::week_days_for_date;
use std::{
cell::RefCell,
collections::HashMap,
@@ -38,7 +41,8 @@ pub(super) const HOME_ICON_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/s
pub(super) const EXPLORER_ICON_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"><path d="M3 6.5H9.5L11.5 9H21V19H3V6.5Z" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/></svg>"#;
pub(super) const JOURNALS_ICON_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"><rect x="4" y="5" width="16" height="15" rx="2" stroke="currentColor" stroke-width="1.8"/><path d="M4 10H20M8 3V6M16 3V6" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>"#;
pub(super) const SEARCH_ICON_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"><circle cx="10.5" cy="10.5" r="6" stroke="currentColor" stroke-width="1.8"/><path d="M15.2 15.2L20 20" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>"#;
pub(super) const SETTINGS_ICON_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="3" stroke="currentColor" stroke-width="1.8"/><path d="M12 3V5.5M12 18.5V21M3 12H5.5M18.5 12H21M5.6 5.6L7.4 7.4M16.6 16.6L18.4 18.4M18.4 5.6L16.6 7.4M7.4 16.6L5.6 18.4" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>"#;
pub(super) const SETTINGS_ICON_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"><path d="M10.6 2.8H13.4L13.9 5.2L17.0 7.1L19.2 6.2L20.6 8.6L18.8 10.1V13.9L20.6 15.4L19.2 17.8L17.0 16.9L13.9 18.8L13.4 21.2H10.6L10.1 18.8L7.0 16.9L4.8 17.8L3.4 15.4L5.2 13.9V10.1L3.4 8.6L4.8 6.2L7.0 7.1L10.1 5.2L10.6 2.8Z" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/><circle cx="12" cy="12" r="3" stroke="currentColor" stroke-width="1.8"/></svg>"#;
pub(super) const PLUS_ICON_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"><path d="M12 5V19M5 12H19" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>"#;
pub(super) const CHEVRON_LEFT_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none"><path d="M10 3.5L5.5 8L10 12.5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>"#;
pub(super) const CHEVRON_RIGHT_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none"><path d="M6 3.5L10.5 8L6 12.5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>"#;
pub(super) const CHEVRON_DOWN_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none"><path d="M4 6L8 10L12 6" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>"#;
@@ -80,6 +84,11 @@ pub(super) trait MobileFlexExt: Styled {
self
}
fn items_stretch(mut self) -> Self {
self.style().align_items = Some(ui::AlignItems::Stretch);
self
}
fn max_h(mut self, height: impl Into<ui::Length>) -> Self {
self.style().max_size.height = Some(height.into());
self
@@ -486,6 +495,7 @@ impl EntityInputHandler for MobileShellView {
impl Render for MobileShellView {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
window.set_touch_gestures_enabled(true);
let now_ms = self.now_ms(cx);
self.state.settle_animations(now_ms);
@@ -525,6 +535,17 @@ impl Render for MobileShellView {
.into_any_element(),
MobileRoute::Explorer => explorer::render_explorer(
&mut self.state,
(viewport_h - safe_metrics.top - safe_metrics.bottom).max(160.0),
palette,
dir,
strings,
&a11y_bounds,
cx,
)
.into_any_element(),
MobileRoute::Journals => tabs::render_journals(
&self.state,
content_w,
viewport_h,
palette,
dir,
@@ -533,10 +554,6 @@ impl Render for MobileShellView {
cx,
)
.into_any_element(),
MobileRoute::Journals => {
tabs::render_journals(&self.state, viewport_h, palette, dir, strings, cx)
.into_any_element()
}
MobileRoute::Search => search::render_search(
&self.state,
self.search_focus.clone(),
+168 -13
View File
@@ -45,14 +45,16 @@ pub(super) fn render_page(
) -> (impl IntoElement, Option<BreadcrumbBarLayout>) {
let locale = state.locale();
let font_scale = state.font_scale.max(0.5);
let doc_opt = state.doc_by_id(doc_id).cloned();
let ws_id = state.active_workspace_id().to_string();
let derivation = state.derive_breadcrumb();
let backlinks = state.backlinks_for(doc_id);
let doc_title = state
.doc_by_id(doc_id)
.map(|d| d.title.clone())
.unwrap_or_else(|| "Untitled".to_string());
let doc_body = state
.doc_by_id(doc_id)
let doc_title = doc_opt
.as_ref()
.map(|d| d.display_title(locale))
.unwrap_or_else(|| strings.doc_not_found_title.to_string());
let doc_body = doc_opt
.as_ref()
.map(|d| d.body_preview.clone())
.unwrap_or_default();
@@ -155,6 +157,16 @@ pub(super) fn render_page(
.map(|c| {
let label = if c.is_switcher {
match &derivation.context {
ContextState::MultiLocation {
count,
owner_doc_id,
owner_doc_title,
..
} if owner_doc_id != doc_id => strings.compact_owner_multi_location_label(
locale,
owner_doc_title,
*count,
),
ContextState::MultiLocation { count, .. } => {
strings.multi_location_label(locale, *count)
}
@@ -342,18 +354,161 @@ pub(super) fn render_page(
.gap(px(12.0))
.overflow_hidden();
if doc_opt.is_none() {
let not_found_body = div()
.id("mobile.page.not_found")
.snapshot("mobile.page.not_found", Some("mobile.shell.root"))
.flex_1()
.min_h(px(0.0))
.p(px(24.0))
.flex()
.flex_col()
.items_center()
.justify_center()
.gap(px(12.0))
.child(
div()
.text_size(px(18.0 * font_scale))
.text_color(palette.text_primary)
.child(strings.doc_not_found_title),
)
.child(
div()
.text_size(px(13.0 * font_scale))
.text_color(palette.text_secondary)
.child(strings.doc_not_found_body),
)
.child(
div()
.id("mobile.page.not_found_back_btn")
.snapshot("mobile.page.not_found_back_btn", Some("mobile.shell.root"))
.relative()
.h(px(44.0))
.min_w(px(120.0))
.px(px(16.0))
.rounded(px(10.0))
.bg(palette.accent)
.text_color(ui::hsla(0.0, 0.0, 1.0, 1.0))
.text_size(px(14.0 * font_scale))
.flex()
.items_center()
.justify_center()
.on_click(cx.listener(|this, _, _, cx| {
let t = this.now_ms(cx);
MobileBackCoordinator::handle_back(&mut this.state, t);
cx.notify();
}))
.child(a11y_bounds_probe(
"mobile.page.not_found_back_btn",
a11y_bounds.clone(),
))
.child(strings.back_label),
);
return (page_col.child(not_found_body), measured_layout);
}
if derivation.in_trash {
body = body.child(
div()
let scoped = crate::encode_scoped_doc_target(&ws_id, doc_id);
let restore_ws = ws_id.clone();
let restore_doc_id = doc_id.to_string();
let restore_id = format!("mobile.page.trash_restore_btn.{scoped}");
let delete_ws = ws_id.clone();
let delete_doc_id = doc_id.to_string();
let delete_id = format!("mobile.page.trash_delete_btn.{scoped}");
let delete_trigger = delete_id.clone();
let restore_btn = div()
.id(restore_id.clone())
.snapshot(restore_id.clone(), Some("mobile.shell.root"))
.relative()
.h(px(44.0))
.min_w(px(64.0))
.px(px(10.0))
.rounded(px(8.0))
.bg(palette.bg_surface)
.border_1()
.border_color(palette.border)
.flex()
.items_center()
.justify_center()
.text_size(px(12.0 * font_scale))
.text_color(palette.text_primary)
.on_click(cx.listener(move |this, _, _, cx| {
this.state.restore_doc_scoped(&restore_ws, &restore_doc_id);
cx.notify();
}))
.child(a11y_bounds_probe_border(
restore_id,
a11y_bounds.clone(),
1.0,
))
.child(strings.restore_doc_label);
let delete_btn = div()
.id(delete_id.clone())
.snapshot(delete_id.clone(), Some("mobile.shell.root"))
.relative()
.h(px(44.0))
.min_w(px(88.0))
.px(px(10.0))
.rounded(px(8.0))
.bg(palette.danger)
.flex()
.items_center()
.justify_center()
.text_size(px(12.0 * font_scale))
.text_color(ui::hsla(0.0, 0.0, 1.0, 1.0))
.on_click(cx.listener(move |this, _, _, cx| {
let t = this.now_ms(cx);
this.state.request_delete_doc_scoped(
&delete_ws,
&delete_doc_id,
Some(&delete_trigger),
t,
);
cx.notify();
}))
.child(a11y_bounds_probe(delete_id, a11y_bounds.clone()))
.child(strings.delete_permanently_label);
let actions = row_dir(dir)
.gap(px(8.0))
.child(restore_btn)
.child(delete_btn);
let badge = div()
.text_size(px(12.0 * font_scale))
.text_color(palette.danger)
.align_start_for(dir)
.child(strings.in_trash_badge);
let banner = if viewport_w >= 360.0 {
row_dir(dir)
.id("mobile.page.trash_banner")
.snapshot("mobile.page.trash_banner", Some("mobile.shell.root"))
.w_full()
.p(px(10.0))
.rounded(px(10.0))
.bg(palette.danger_soft)
.text_size(px(12.0 * font_scale))
.text_color(palette.danger)
.align_start_for(dir)
.child(strings.in_trash_badge),
);
.justify_between()
.gap(px(8.0))
.child(badge)
.child(actions)
.into_any_element()
} else {
div()
.id("mobile.page.trash_banner")
.snapshot("mobile.page.trash_banner", Some("mobile.shell.root"))
.w_full()
.p(px(10.0))
.rounded(px(10.0))
.bg(palette.danger_soft)
.flex()
.flex_col()
.gap(px(8.0))
.child(badge)
.child(actions)
.into_any_element()
};
body = body.child(banner);
}
body = body
+107 -73
View File
@@ -116,85 +116,119 @@ pub(super) fn render_search(
);
}
let mut list = div()
.w_full()
.rounded(px(12.0))
.bg(palette.bg_surface)
.border_1()
.border_color(palette.border)
.flex()
.flex_col()
.overflow_hidden();
for (idx, hit) in hits.iter().take(max_hits).enumerate() {
let doc_id = hit.doc_id.clone();
let body_preview = state
.doc_by_id(&doc_id)
.map(|d| d.body_preview.clone())
.unwrap_or_default();
let mut row = div()
.id(format!("mobile.search.hit.{doc_id}"))
.snapshot(
format!("mobile.search.hit.{doc_id}"),
Some("mobile.shell.root"),
)
.w_full()
.min_h(px(64.0))
.p(px(12.0))
.flex()
.flex_col()
.gap(px(4.0))
.overflow_hidden()
.on_click(cx.listener(move |this, _, _, cx| {
this.state
.open_doc(&doc_id, Origin::Direct(DirectKind::Search));
cx.notify();
}));
if idx > 0 {
row = row.border_t(px(1.0)).border_color(palette.border);
}
let title_spans: Vec<(usize, usize)> = hit
.title_highlights
.iter()
.map(|s| (s.start, s.end))
.collect();
let body_spans: Vec<(usize, usize)> = hit
.body_highlights
.iter()
.map(|s| (s.start, s.end))
.collect();
let (snippet_text, snippet_spans) = snippet_window_utf16(&body_preview, &body_spans, 44);
row = row
.child(render_highlighted_line(
&hit.title,
&title_spans,
14.0,
palette.text_primary,
palette.accent,
palette.accent_soft,
dir,
))
.child(render_highlighted_line(
&snippet_text,
&snippet_spans,
12.0,
palette.text_secondary,
palette.accent,
palette.accent_soft,
dir,
));
list = list.child(row);
}
div()
let mut root = div()
.size_full()
.flex()
.flex_col()
.p(px(16.0))
.gap(px(12.0))
.overflow_hidden()
.child(search_bar)
.child(list)
.child(search_bar);
if !hits.is_empty() {
let mut list = div()
.id("mobile.search.results")
.snapshot("mobile.search.results", Some("mobile.shell.root"))
.w_full()
.rounded(px(12.0))
.bg(palette.bg_surface)
.border_1()
.border_color(palette.border)
.flex()
.flex_col()
.overflow_hidden();
for (idx, hit) in hits.iter().take(max_hits).enumerate() {
let doc_id = hit.doc_id.clone();
let body_preview = state
.doc_by_id(&doc_id)
.map(|d| d.body_preview.clone())
.unwrap_or_default();
let mut row = div()
.id(format!("mobile.search.hit.{doc_id}"))
.snapshot(
format!("mobile.search.hit.{doc_id}"),
Some("mobile.shell.root"),
)
.w_full()
.min_h(px(64.0))
.p(px(12.0))
.flex()
.flex_col()
.gap(px(4.0))
.overflow_hidden()
.on_click(cx.listener(move |this, _, _, cx| {
this.state
.open_doc(&doc_id, Origin::Direct(DirectKind::Search));
cx.notify();
}));
if idx > 0 {
row = row.border_t(px(1.0)).border_color(palette.border);
}
let title_spans: Vec<(usize, usize)> = hit
.title_highlights
.iter()
.map(|s| (s.start, s.end))
.collect();
let body_spans: Vec<(usize, usize)> = hit
.body_highlights
.iter()
.map(|s| (s.start, s.end))
.collect();
let (snippet_text, snippet_spans) =
snippet_window_utf16(&body_preview, &body_spans, 44);
row = row
.child(render_highlighted_line(
&hit.title,
&title_spans,
14.0,
palette.text_primary,
palette.accent,
palette.accent_soft,
dir,
))
.child(render_highlighted_line(
&snippet_text,
&snippet_spans,
12.0,
palette.text_secondary,
palette.accent,
palette.accent_soft,
dir,
));
list = list.child(row);
}
root = root.child(list);
} else if !state.search_query.is_empty() {
root = root.child(
div()
.id("mobile.search.empty_state")
.snapshot("mobile.search.empty_state", Some("mobile.shell.root"))
.flex_1()
.w_full()
.flex()
.flex_col()
.items_center()
.justify_center()
.gap(px(10.0))
.child(
svg()
.data(SEARCH_ICON_SVG)
.mirror_in_rtl(true)
.w(px(28.0))
.h(px(28.0))
.text_color(palette.text_muted),
)
.child(
div()
.text_size(px(14.0))
.text_color(palette.text_secondary)
.child(strings.search_no_results),
),
);
}
root
}
fn render_highlighted_line(
+69 -57
View File
@@ -8,8 +8,11 @@ use ui::{
use ui_kit::{LogicalStyled, bidi_isolate};
use crate::{
state::{MobileAppState, MobileBackCoordinator, SettingsGroupId, ThemePreference},
strings::{MobileLocale, MobileStrings},
state::{
MobileAppState, MobileBackCoordinator, SettingRowInteraction, SettingsGroupId,
ThemePreference,
},
strings::MobileStrings,
};
use super::{
@@ -89,16 +92,6 @@ pub(super) fn render_settings(
.text_color(palette.text_primary)
.child(strings.settings_title),
),
)
.child(
div()
.px(px(8.0))
.py(px(3.0))
.rounded(px(6.0))
.bg(palette.bg_pill)
.text_size(px(11.0))
.text_color(palette.text_secondary)
.child(strings.about_version_label),
);
let theme_label = match state.settings.theme_preference {
@@ -119,21 +112,21 @@ pub(super) fn render_settings(
SettingsGroupId::Account => state.settings.account_email.clone(),
SettingsGroupId::Workspace => state.active_workspace().name.clone(),
SettingsGroupId::Appearance => theme_label.to_string(),
SettingsGroupId::Language => state.settings.locale.code().to_string(),
SettingsGroupId::Language => state.settings.locale.display_name().to_string(),
SettingsGroupId::Editor => format!("{}%", state.settings.editor_font_scale_pct),
SettingsGroupId::SyncOffline => {
if state.settings.offline_sync_enabled {
"On".to_string()
strings.toggle_on.to_string()
} else {
"Off".to_string()
strings.toggle_off.to_string()
}
}
SettingsGroupId::Storage => format!("{} MB", state.settings.cache_size_mb),
SettingsGroupId::Notifications => {
if state.settings.push_notifications {
"On".to_string()
strings.toggle_on.to_string()
} else {
"Off".to_string()
strings.toggle_off.to_string()
}
}
SettingsGroupId::Experimental => {
@@ -147,12 +140,57 @@ pub(super) fn render_settings(
value
};
let interaction = group.interaction();
let toggle_enabled = match group {
SettingsGroupId::SyncOffline => state.settings.offline_sync_enabled,
SettingsGroupId::Notifications => state.settings.push_notifications,
_ => false,
};
let trailing: ui::AnyElement = match interaction {
SettingRowInteraction::Toggle => div()
.px(px(10.0))
.py(px(4.0))
.rounded(px(999.0))
.bg(if toggle_enabled {
palette.accent
} else {
palette.bg_pill
})
.text_size(px(12.0))
.text_color(if toggle_enabled {
ui::hsla(0.0, 0.0, 1.0, 1.0)
} else {
palette.text_secondary
})
.child(display_value)
.into_any_element(),
SettingRowInteraction::Cycle => div()
.px(px(10.0))
.py(px(4.0))
.rounded(px(8.0))
.bg(palette.bg_pill)
.border_1()
.border_color(palette.border)
.text_size(px(12.0))
.text_color(palette.text_primary)
.child(display_value)
.into_any_element(),
SettingRowInteraction::Info => div()
.text_size(px(12.0))
.text_color(palette.text_secondary)
.child(display_value)
.into_any_element(),
};
let row_id = if interaction == SettingRowInteraction::Info {
format!("mobile.settings.group.{idx}")
} else {
format!("mobile.settings.row.{}", group.a11y_key())
};
let mut row = row_dir(dir)
.id(format!("mobile.settings.group.{idx}"))
.snapshot(
format!("mobile.settings.group.{idx}"),
Some("mobile.shell.root"),
)
.id(row_id.clone())
.snapshot(row_id.clone(), Some("mobile.shell.root"))
.relative()
.w_full()
.h(px(44.0))
.flex_shrink(0.0)
@@ -160,47 +198,21 @@ pub(super) fn render_settings(
.pe(px(14.0), dir)
.justify_between()
.overflow_hidden()
.on_click(cx.listener(move |this, _, _, cx| {
match group {
SettingsGroupId::Appearance => {
this.state.settings.theme_preference =
match this.state.settings.theme_preference {
ThemePreference::Light => ThemePreference::Dark,
ThemePreference::Dark => ThemePreference::System,
ThemePreference::System => ThemePreference::Light,
};
}
SettingsGroupId::Language => {
this.state.settings.locale = match this.state.settings.locale {
MobileLocale::En => MobileLocale::ZhHans,
MobileLocale::ZhHans => MobileLocale::Ar,
MobileLocale::Ar => MobileLocale::En,
};
}
SettingsGroupId::SyncOffline => {
this.state.settings.offline_sync_enabled =
!this.state.settings.offline_sync_enabled;
}
SettingsGroupId::Notifications => {
this.state.settings.push_notifications =
!this.state.settings.push_notifications;
}
_ => {}
}
cx.notify();
}))
.child(
div()
.text_size(px(13.0))
.text_color(palette.text_primary)
.child(title),
)
.child(
div()
.text_size(px(12.0))
.text_color(palette.text_secondary)
.child(display_value),
);
.child(trailing);
if interaction != SettingRowInteraction::Info {
row = row
.child(a11y_bounds_probe(row_id, a11y_bounds.clone()))
.on_click(cx.listener(move |this, _, _, cx| {
this.state.activate_setting(group);
cx.notify();
}));
}
if top_border {
row = row.border_t(px(1.0)).border_color(palette.border);
}
+109 -1
View File
@@ -43,6 +43,7 @@ pub(super) fn render_active_sheet(
MobileSheet::WorkspaceSelector => strings.switch_workspace,
MobileSheet::LocationAndTrail => strings.location_trail_title,
MobileSheet::Backlinks => strings.backlinks_label,
MobileSheet::ConfirmDeleteDoc => strings.confirm_delete_title,
MobileSheet::None => "",
};
@@ -407,7 +408,7 @@ pub(super) fn render_active_sheet(
let block_id = item.source_block_id.clone();
let src_title = state
.doc_by_id(&src_id)
.map(|d| d.title.clone())
.map(|d| d.display_title(state.locale()))
.unwrap_or_else(|| src_id.clone());
let bl_id = format!("mobile.sheet.backlink.{idx}");
let mut row = row_dir(dir)
@@ -446,6 +447,113 @@ pub(super) fn render_active_sheet(
}
content = content.child(bl_box);
}
MobileSheet::ConfirmDeleteDoc => {
let (ws_id, doc_id) = state
.pending_delete_target
.clone()
.unwrap_or_else(|| (state.active_workspace_id().to_string(), String::new()));
let doc_title = state
.doc_by_id(&doc_id)
.map(|d| d.display_title(state.locale()))
.unwrap_or_else(|| doc_id.clone());
let scoped = crate::encode_scoped_doc_target(&ws_id, &doc_id);
let cancel_id = format!("app.sheet.delete_cancel.{scoped}");
let confirm_id = format!("app.sheet.delete_confirm.{scoped}");
let mut cancel_btn = div()
.id(cancel_id.clone())
.snapshot(cancel_id.clone(), Some("mobile.sheet.panel"))
.relative()
.flex_1()
.h(px(44.0))
.min_w(px(44.0))
.rounded(px(10.0))
.bg(palette.bg_canvas)
.border_1()
.border_color(palette.border)
.flex()
.items_center()
.justify_center()
.text_size(px(14.0))
.text_color(palette.text_primary)
.child(crate::a11y::a11y_bounds_probe_border(
cancel_id,
a11y_bounds.clone(),
1.0,
))
.child(strings.cancel_label);
if accepts_input {
cancel_btn = cancel_btn.on_click(cx.listener(|this, _, _, cx| {
let t = this.now_ms(cx);
this.state.close_sheet(t);
cx.notify();
}));
}
let confirm_ws = ws_id.clone();
let confirm_doc = doc_id.clone();
let mut confirm_btn = div()
.id(confirm_id.clone())
.snapshot(confirm_id.clone(), Some("mobile.sheet.panel"))
.relative()
.flex_1()
.h(px(44.0))
.min_w(px(44.0))
.rounded(px(10.0))
.bg(palette.danger)
.flex()
.items_center()
.justify_center()
.text_size(px(14.0))
.text_color(ui::hsla(0.0, 0.0, 1.0, 1.0))
.child(a11y_bounds_probe(confirm_id, a11y_bounds.clone()))
.child(strings.delete_permanently_label);
if accepts_input {
confirm_btn = confirm_btn.on_click(cx.listener(move |this, _, _, cx| {
let t = this.now_ms(cx);
this.state
.delete_doc_permanently_scoped(&confirm_ws, &confirm_doc, t);
cx.notify();
}));
}
content = content
.child(
div()
.w_full()
.p(px(12.0))
.rounded(px(10.0))
.bg(palette.bg_canvas)
.border_1()
.border_color(palette.border)
.flex()
.flex_col()
.gap(px(6.0))
.child(
div()
.w_full()
.text_size(px(14.0))
.text_color(palette.text_primary)
.align_start_for(dir)
.child(doc_title),
)
.child(
div()
.w_full()
.text_size(px(13.0))
.text_color(palette.text_secondary)
.align_start_for(dir)
.child(strings.confirm_delete_body),
),
)
.child(
row_dir(dir)
.w_full()
.gap(px(10.0))
.child(cancel_btn)
.child(confirm_btn),
);
}
MobileSheet::None => {}
}
+247 -127
View File
@@ -15,8 +15,8 @@ use crate::{
use super::{
A11yBoundsMap, CHEVRON_DOWN_SVG, EXPLORER_ICON_SVG, HOME_ICON_SVG, JOURNALS_ICON_SVG,
MobileFlexExt, MobilePalette, MobileShellView, SEARCH_ICON_SVG, SETTINGS_ICON_SVG,
STAR_ICON_SVG, a11y_bounds_probe,
MobileFlexExt, MobilePalette, MobileShellView, PLUS_ICON_SVG, SEARCH_ICON_SVG,
SETTINGS_ICON_SVG, STAR_ICON_SVG, a11y_bounds_probe, a11y_bounds_probe_border,
};
fn row_dir(dir: Direction) -> ui::Div {
@@ -38,6 +38,7 @@ pub(super) fn render_home(
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let ws = state.active_workspace();
let locale = state.locale();
let compact = viewport_h < 460.0;
let header = row_dir(dir)
@@ -101,30 +102,68 @@ pub(super) fn render_home(
),
)
.child(
div()
.id("mobile.home.settings_btn")
.snapshot("mobile.home.settings_btn", Some("mobile.shell.root"))
.w(px(44.0))
.h(px(44.0))
.rounded(px(10.0))
.bg(palette.bg_pill)
.flex()
.items_center()
.justify_center()
.on_click(cx.listener(|this, _, _, cx| {
this.state.open_settings();
cx.notify();
}))
row_dir(dir)
.flex_shrink(0.0)
.gap(px(8.0))
.child(
svg()
.data(SETTINGS_ICON_SVG)
.w(px(18.0))
.h(px(18.0))
.text_color(palette.text_secondary),
div()
.id("mobile.home.new_doc_btn")
.snapshot("mobile.home.new_doc_btn", Some("mobile.shell.root"))
.relative()
.w(px(44.0))
.h(px(44.0))
.rounded(px(10.0))
.bg(palette.accent_soft)
.flex()
.items_center()
.justify_center()
.on_click(cx.listener(|this, _, _, cx| {
let t = this.now_ms(cx);
this.state.create_doc(None, t);
cx.notify();
}))
.child(a11y_bounds_probe(
"mobile.home.new_doc_btn",
a11y_bounds.clone(),
))
.child(
svg()
.data(PLUS_ICON_SVG)
.w(px(18.0))
.h(px(18.0))
.text_color(palette.accent),
),
)
.child(
div()
.id("mobile.home.settings_btn")
.snapshot("mobile.home.settings_btn", Some("mobile.shell.root"))
.w(px(44.0))
.h(px(44.0))
.rounded(px(10.0))
.bg(palette.bg_pill)
.flex()
.items_center()
.justify_center()
.on_click(cx.listener(|this, _, _, cx| {
this.state.open_settings();
cx.notify();
}))
.child(
svg()
.data(SETTINGS_ICON_SVG)
.w(px(18.0))
.h(px(18.0))
.text_color(palette.text_secondary),
),
),
);
let mut fav_row = row_dir(dir).w_full().flex_shrink(0.0).gap(px(10.0));
let mut fav_row = row_dir(dir)
.w_full()
.flex_shrink(0.0)
.items_stretch()
.gap(px(10.0));
for doc in state
.docs
.iter()
@@ -170,7 +209,7 @@ pub(super) fn render_home(
.text_color(palette.text_primary)
.align_start_for(dir)
.overflow_hidden()
.child(doc.title.clone()),
.child(doc.display_title(locale)),
),
);
}
@@ -228,7 +267,7 @@ pub(super) fn render_home(
.text_color(palette.text_primary)
.align_start_for(dir)
.overflow_hidden()
.child(doc.title.clone()),
.child(doc.display_title(locale)),
);
if !compact {
row = row.child(
@@ -308,14 +347,18 @@ pub(super) fn render_home(
.child(body)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn render_journals(
state: &MobileAppState,
_viewport_h: f32,
viewport_w: f32,
viewport_h: f32,
palette: MobilePalette,
dir: Direction,
strings: &'static MobileStrings,
a11y_bounds: &A11yBoundsMap,
cx: &mut Context<MobileShellView>,
) -> impl IntoElement {
let selected_date = state.selected_journal_date.clone();
let header = row_dir(dir)
.id("mobile.journals.header")
.snapshot("mobile.journals.header", Some("mobile.shell.root"))
@@ -342,24 +385,34 @@ pub(super) fn render_journals(
.bg(palette.accent_soft)
.text_size(px(12.0))
.text_color(palette.accent)
.child(state.today_date.clone()),
.child(selected_date.clone()),
);
let compact = viewport_h < 460.0;
let day_pill_h = if compact { 44.0 } else { 52.0 };
let week = week_days_for_date(&state.today_date);
let mut day_strip = row_dir(dir).w_full().justify_between().gap(px(4.0));
for (day_lbl, day_num, is_today) in week {
day_strip = day_strip.child(
let make_day_pill =
|idx: usize, day_num: String, iso_date: String, cx: &mut Context<MobileShellView>| {
let day_lbl = strings.weekday_short[idx];
let is_selected = iso_date == selected_date;
let is_today = iso_date == state.today_date;
let day_id = format!("mobile.journals.day.{iso_date}");
let click_date = iso_date.clone();
div()
.id(day_id.clone())
.snapshot(day_id.clone(), Some("mobile.shell.root"))
.relative()
.flex_1()
.h(px(52.0))
.min_w(px(44.0))
.h(px(day_pill_h))
.rounded(px(10.0))
.bg(if is_today {
.bg(if is_selected {
palette.accent
} else {
palette.bg_surface
})
.border_1()
.border_color(if is_today {
.border_color(if is_selected || is_today {
palette.accent
} else {
palette.border
@@ -369,10 +422,15 @@ pub(super) fn render_journals(
.items_center()
.justify_center()
.gap(px(2.0))
.on_click(cx.listener(move |this, _, _, cx| {
this.state.select_journal_date(&click_date);
cx.notify();
}))
.child(a11y_bounds_probe_border(day_id, a11y_bounds.clone(), 1.0))
.child(
div()
.text_size(px(10.0))
.text_color(if is_today {
.text_color(if is_selected {
ui::hsla(0.0, 0.0, 1.0, 0.85)
} else {
palette.text_secondary
@@ -382,24 +440,154 @@ pub(super) fn render_journals(
.child(
div()
.text_size(px(13.0))
.text_color(if is_today {
.text_color(if is_selected {
ui::hsla(0.0, 0.0, 1.0, 1.0)
} else {
palette.text_primary
})
.child(day_num),
),
);
}
)
};
let today_doc = state
let day_strip: ui::AnyElement = if viewport_w < 364.0 {
let mut top_row = row_dir(dir).w_full().gap(px(4.0));
let mut bottom_row = row_dir(dir).w_full().gap(px(4.0));
for (idx, (_, day_num, iso_date)) in week.into_iter().enumerate() {
let pill = make_day_pill(idx, day_num, iso_date, cx);
if idx < 4 {
top_row = top_row.child(pill);
} else {
bottom_row = bottom_row.child(pill);
}
}
div()
.w_full()
.flex()
.flex_col()
.gap(px(6.0))
.child(top_row)
.child(bottom_row)
.into_any_element()
} else {
let mut single_row = row_dir(dir).w_full().justify_between().gap(px(4.0));
for (idx, (_, day_num, iso_date)) in week.into_iter().enumerate() {
single_row = single_row.child(make_day_pill(idx, day_num, iso_date, cx));
}
single_row.into_any_element()
};
let selected_doc = state
.docs
.iter()
.find(|d| d.journal_date.as_deref() == Some(state.today_date.as_str()));
let today_doc_id = today_doc
.map(|d| d.id.clone())
.unwrap_or_else(|| "doc-journal".to_string());
let create_doc_id = today_doc_id.clone();
.find(|d| !d.trashed && d.journal_date.as_deref() == Some(selected_date.as_str()));
let has_entry = selected_doc.is_some();
let card_eyebrow = if selected_date == state.today_date {
strings.today_journal.to_string()
} else {
selected_date.clone()
};
let card_title = selected_doc
.map(|d| d.title.clone())
.unwrap_or_else(|| format!("Journal {selected_date}"));
let card_preview = selected_doc
.map(|d| d.body_preview.clone())
.unwrap_or_else(|| strings.no_journal_for_date.to_string());
let cta_label = if has_entry {
strings.open_journal
} else {
strings.create_journal
};
let card_date = selected_date.clone();
let btn_date = selected_date;
let today_card = div()
.id("mobile.journals.today_card")
.snapshot("mobile.journals.today_card", Some("mobile.shell.root"))
.w_full()
.p(px(if compact { 10.0 } else { 14.0 }))
.rounded(px(12.0))
.bg(palette.bg_surface)
.border_1()
.border_color(palette.border)
.flex()
.flex_col()
.gap(px(if compact { 3.0 } else { 6.0 }))
.on_click(cx.listener(move |this, _, _, cx| {
let t = this.now_ms(cx);
this.state.open_or_create_journal_for_date(&card_date, t);
cx.notify();
}))
.child(
div()
.w_full()
.text_size(px(12.0))
.text_color(palette.accent)
.align_start_for(dir)
.child(card_eyebrow),
)
.child(
div()
.w_full()
.text_size(px(15.0))
.text_color(palette.text_primary)
.align_start_for(dir)
.child(card_title),
)
.child(
div()
.w_full()
.text_size(px(13.0))
.text_color(palette.text_secondary)
.align_start_for(dir)
.child(card_preview),
);
let create_btn = div()
.id("mobile.journals.create_btn")
.snapshot("mobile.journals.create_btn", Some("mobile.shell.root"))
.relative()
.w_full()
.h(px(46.0))
.px(px(14.0))
.rounded(px(12.0))
.bg(palette.accent)
.text_color(ui::hsla(0.0, 0.0, 1.0, 1.0))
.text_size(px(14.0))
.flex()
.items_center()
.justify_center()
.on_click(cx.listener(move |this, _, _, cx| {
let t = this.now_ms(cx);
this.state.open_or_create_journal_for_date(&btn_date, t);
cx.notify();
}))
.child(a11y_bounds_probe(
"mobile.journals.create_btn",
a11y_bounds.clone(),
))
.child(cta_label);
let mut content = div()
.flex_1()
.min_h(px(0.0))
.p(px(if compact { 10.0 } else { 16.0 }))
.flex()
.flex_col()
.gap(px(if compact { 10.0 } else { 14.0 }))
.overflow_hidden()
.child(day_strip);
if compact {
content = content.child(
row_dir(dir)
.w_full()
.gap(px(10.0))
.items_center()
.child(div().flex_1().min_w(px(0.0)).child(today_card))
.child(div().w(px(184.0)).flex_shrink(0.0).child(create_btn)),
);
} else {
content = content.child(today_card).child(create_btn);
}
div()
.size_full()
@@ -407,90 +595,18 @@ pub(super) fn render_journals(
.flex_col()
.overflow_hidden()
.child(header)
.child(
div()
.flex_1()
.min_h(px(0.0))
.p(px(16.0))
.flex()
.flex_col()
.gap(px(14.0))
.overflow_hidden()
.child(day_strip)
.child(
div()
.id("mobile.journals.today_card")
.snapshot("mobile.journals.today_card", Some("mobile.shell.root"))
.w_full()
.p(px(14.0))
.rounded(px(12.0))
.bg(palette.bg_surface)
.border_1()
.border_color(palette.border)
.flex()
.flex_col()
.gap(px(6.0))
.on_click(cx.listener(move |this, _, _, cx| {
this.state.open_doc(&today_doc_id, Origin::Journal);
cx.notify();
}))
.child(
div()
.text_size(px(12.0))
.text_color(palette.accent)
.child(strings.today_journal),
)
.child(
div()
.text_size(px(15.0))
.text_color(palette.text_primary)
.child(
today_doc
.map(|d| d.title.clone())
.unwrap_or_else(|| state.today_date.clone()),
),
)
.child(
div()
.text_size(px(13.0))
.text_color(palette.text_secondary)
.child(
today_doc
.map(|d| d.body_preview.clone())
.unwrap_or_default(),
),
),
)
.child(
div()
.id("mobile.journals.create_btn")
.snapshot("mobile.journals.create_btn", Some("mobile.shell.root"))
.w_full()
.h(px(46.0))
.rounded(px(12.0))
.bg(palette.accent)
.text_color(ui::hsla(0.0, 0.0, 1.0, 1.0))
.text_size(px(14.0))
.flex()
.items_center()
.justify_center()
.on_click(cx.listener(move |this, _, _, cx| {
this.state.open_doc(&create_doc_id, Origin::Journal);
cx.notify();
}))
.child(strings.create_journal),
),
)
.child(content)
}
/// Pure calendar week derivation (Monday..Sunday) from an ISO `YYYY-MM-DD` date string.
pub(crate) fn week_days_for_date(iso_date: &str) -> Vec<(&'static str, String, bool)> {
/// Returns `(weekday_short, day_number, full_iso_date)` for each of the 7 days.
pub(crate) fn week_days_for_date(iso_date: &str) -> Vec<(&'static str, String, String)> {
const LABELS: [&str; 7] = ["M", "T", "W", "T", "F", "S", "S"];
let Some((y, m, d)) = parse_iso_date(iso_date) else {
return LABELS
.iter()
.enumerate()
.map(|(i, lbl)| (*lbl, (i + 1).to_string(), i == 0))
.map(|(i, lbl)| (*lbl, (i + 1).to_string(), format!("2026-01-{:02}", i + 1)))
.collect();
};
let z = days_from_civil(y, m, d);
@@ -500,8 +616,12 @@ pub(crate) fn week_days_for_date(iso_date: &str) -> Vec<(&'static str, String, b
(0..7)
.map(|offset| {
let day_z = monday + offset;
let (_, _, day_num) = civil_from_days(day_z);
(LABELS[offset as usize], day_num.to_string(), day_z == z)
let (dy, dm, dd) = civil_from_days(day_z);
(
LABELS[offset as usize],
dd.to_string(),
format!("{dy:04}-{dm:02}-{dd:02}"),
)
})
.collect()
}
@@ -659,14 +779,14 @@ mod tests {
// 2026-11-25 is Wednesday -> Monday Nov 23 .. Sunday Nov 29.
let week = week_days_for_date("2026-11-25");
assert_eq!(week.len(), 7);
assert_eq!(week[0], ("M", "23".to_string(), false));
assert_eq!(week[2], ("W", "25".to_string(), true));
assert_eq!(week[6], ("S", "29".to_string(), false));
assert_eq!(week[0], ("M", "23".to_string(), "2026-11-23".to_string()));
assert_eq!(week[2], ("W", "25".to_string(), "2026-11-25".to_string()));
assert_eq!(week[6], ("S", "29".to_string(), "2026-11-29".to_string()));
// 2024-02-29 (leap day, Thursday) -> Monday Feb 26 .. Sunday Mar 3.
let leap = week_days_for_date("2024-02-29");
assert_eq!(leap[0], ("M", "26".to_string(), false));
assert_eq!(leap[3], ("T", "29".to_string(), true));
assert_eq!(leap[4], ("F", "1".to_string(), false));
assert_eq!(leap[0], ("M", "26".to_string(), "2024-02-26".to_string()));
assert_eq!(leap[3], ("T", "29".to_string(), "2024-02-29".to_string()));
assert_eq!(leap[4], ("F", "1".to_string(), "2024-03-01".to_string()));
}
}
+516 -9
View File
@@ -386,6 +386,45 @@ fn all_published_interactive_a11y_nodes_activate_and_modal_blocks_background() {
s
}),
),
(
"explorer-root",
Box::new(|| {
let mut s = seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-11-25");
s.switch_tab(MobileTab::Explorer, 0.0);
s
}),
),
(
"journals",
Box::new(|| {
let mut s = seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-11-25");
s.switch_tab(MobileTab::Journals, 0.0);
s
}),
),
(
"page-trash",
Box::new(|| {
let mut s = seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-11-25");
s.open_doc("doc-trash", Origin::Direct(DirectKind::AllDocs));
s
}),
),
(
"confirm-delete-sheet",
Box::new(|| {
let mut s = seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-11-25");
s.open_doc("doc-trash", Origin::Direct(DirectKind::AllDocs));
s.request_delete_doc_scoped(
"ws-mobile-rust",
"doc-trash",
Some("mobile.page.trash_delete_btn.14:ws-mobile-rustdoc-trash"),
0.0,
);
s.settle_animations(500.0);
s
}),
),
];
for (name, make_state) in factories {
@@ -600,7 +639,7 @@ fn explorer_a11y_drilldown_and_origins_match_clicks_across_folder_collection_tag
for id in [
"mobile.explorer.folder.f-eng",
"mobile.explorer.folder.f-mobile",
"mobile.explorer.doc.doc-arch",
"mobile.explorer.doc.14:ws-mobile-rustdoc-arch",
] {
click_app.click_id(id);
}
@@ -623,7 +662,7 @@ fn explorer_a11y_drilldown_and_origins_match_clicks_across_folder_collection_tag
for id in [
"mobile.explorer.folder.f-eng",
"mobile.explorer.folder.f-mobile",
"mobile.explorer.doc.doc-arch",
"mobile.explorer.doc.14:ws-mobile-rustdoc-arch",
] {
assert!(perform_a11y_action(
&mut a11y_state,
@@ -658,7 +697,7 @@ fn explorer_a11y_drilldown_and_origins_match_clicks_across_folder_collection_tag
(
"folder",
NavTarget::Folder("f-mobile".into()),
"mobile.explorer.doc.doc-arch",
"mobile.explorer.doc.14:ws-mobile-rustdoc-arch",
Origin::Placement {
link_id: "l-arch-eng".into(),
},
@@ -666,13 +705,13 @@ fn explorer_a11y_drilldown_and_origins_match_clicks_across_folder_collection_tag
(
"collection",
NavTarget::Collection("col-sync".into()),
"mobile.explorer.doc.doc-sync",
"mobile.explorer.doc.14:ws-mobile-rustdoc-sync",
Origin::Collection("col-sync".into()),
),
(
"tag",
NavTarget::Tag("rust".into()),
"mobile.explorer.doc.doc-arch",
"mobile.explorer.doc.14:ws-mobile-rustdoc-arch",
Origin::Tag("rust".into()),
),
];
@@ -979,14 +1018,14 @@ fn stale_explorer_doc_action_from_previous_workspace_is_rejected() {
let app = ParityApp::launch_with_state(390, 844, init);
app.headless_win.request_frame();
// Confirm `mobile.explorer.doc.doc-arch` is published in AFFiNE Core's Mobile Rust folder.
// Confirm `mobile.explorer.doc.14:ws-mobile-rustdoc-arch` is published in AFFiNE Core's Mobile Rust folder.
let present_in_core = app
.app
.update(|cx| {
app.window_handle.update(cx, |v, _, _| {
v.published_a11y_tree()
.nodes
.contains_key("mobile.explorer.doc.doc-arch")
.contains_key("mobile.explorer.doc.14:ws-mobile-rustdoc-arch")
})
})
.unwrap();
@@ -1019,7 +1058,7 @@ fn stale_explorer_doc_action_from_previous_workspace_is_rejected() {
assert!(
!v.published_a11y_tree()
.nodes
.contains_key("mobile.explorer.doc.doc-arch")
.contains_key("mobile.explorer.doc.14:ws-mobile-rustdoc-arch")
);
let ws_before = v.state.scope.workspace_id.clone();
let route_before = v.state.route.clone();
@@ -1032,7 +1071,7 @@ fn stale_explorer_doc_action_from_previous_workspace_is_rejected() {
.collect();
assert!(!v.perform_a11y_action(
"mobile.explorer.doc.doc-arch",
"mobile.explorer.doc.14:ws-mobile-rustdoc-arch",
MobileA11yAction::Activate,
cx
));
@@ -1140,3 +1179,471 @@ fn stale_breadcrumb_ellipsis_action_after_widening_viewport_is_rejected() {
})
.unwrap();
}
#[test]
fn dotted_workspace_and_doc_ids_do_not_collide_in_scoped_actions() {
let enc_a = affine_mobile::encode_scoped_doc_target("team.eu", "notes");
let enc_b = affine_mobile::encode_scoped_doc_target("team", "eu.notes");
assert_ne!(enc_a, enc_b);
assert_eq!(
affine_mobile::decode_scoped_doc_target(&enc_a),
Some(("team.eu", "notes"))
);
assert_eq!(
affine_mobile::decode_scoped_doc_target(&enc_b),
Some(("team", "eu.notes"))
);
let mut state = seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-11-25");
state.workspaces[0].id = "team.eu".into();
state.workspace_store[0].summary.id = "team.eu".into();
state.workspace_store[0].scope.workspace_id = "team.eu".into();
state.scope.workspace_id = "team.eu".into();
state.docs.push(affine_mobile::MobileDocRecord {
id: "notes".into(),
title: "EU Team Notes".into(),
body_preview: "EU workspace doc".into(),
tags: Vec::new(),
updated_at_ms: 1_764_000_500,
is_favorite: false,
trashed: true,
journal_date: None,
clock: 1,
outgoing_edges: Vec::new(),
});
state.workspace_store[0].docs = state.docs.clone();
state.workspaces[1].id = "team".into();
state.workspace_store[1].summary.id = "team".into();
state.workspace_store[1].scope.workspace_id = "team".into();
state.workspace_store[1]
.docs
.push(affine_mobile::MobileDocRecord {
id: "eu.notes".into(),
title: "Team EU Subnotes".into(),
body_preview: "Team workspace doc".into(),
tags: Vec::new(),
updated_at_ms: 1_764_000_501,
is_favorite: false,
trashed: true,
journal_date: None,
clock: 1,
outgoing_edges: Vec::new(),
});
// Open & restore `(team.eu, notes)` via scoped a11y actions.
state.switch_tab(affine_mobile::MobileTab::Explorer, 0.0);
state.navigate_target(NavTarget::Trash, Origin::Direct(DirectKind::AllDocs));
let open_a = format!("mobile.explorer.doc.{enc_a}");
assert!(affine_mobile::perform_a11y_action(
&mut state,
&open_a,
MobileA11yAction::Activate,
10.0,
));
assert_eq!(state.route, MobileRoute::Page("notes".into()));
let restore_a = format!("mobile.page.trash_restore_btn.{enc_a}");
assert!(affine_mobile::perform_a11y_action(
&mut state,
&restore_a,
MobileA11yAction::Activate,
20.0,
));
assert!(!state.doc_by_id("notes").unwrap().trashed);
// Switch to `team`, open `(team, eu.notes)` delete confirmation sheet, and replay stale
// `(team.eu, notes)` delete_confirm -> must return false and preserve `(team, eu.notes)`.
state.select_workspace(1, 30.0);
state.settle_animations(600.0);
state.switch_tab(affine_mobile::MobileTab::Explorer, 610.0);
state.navigate_target(NavTarget::Trash, Origin::Direct(DirectKind::AllDocs));
let open_b = format!("mobile.explorer.doc.{enc_b}");
assert!(affine_mobile::perform_a11y_action(
&mut state,
&open_b,
MobileA11yAction::Activate,
620.0,
));
assert_eq!(state.route, MobileRoute::Page("eu.notes".into()));
let del_btn_b = format!("mobile.page.trash_delete_btn.{enc_b}");
assert!(affine_mobile::perform_a11y_action(
&mut state,
&del_btn_b,
MobileA11yAction::Activate,
630.0,
));
assert_eq!(state.active_sheet, MobileSheet::ConfirmDeleteDoc);
let stale_confirm_a = format!("app.sheet.delete_confirm.{enc_a}");
assert!(
!affine_mobile::perform_a11y_action(
&mut state,
&stale_confirm_a,
MobileA11yAction::Activate,
640.0,
),
"stale delete_confirm from (team.eu, notes) must be rejected when (team, eu.notes) is open"
);
assert!(
state.doc_by_id("eu.notes").is_some(),
"(team, eu.notes) must remain intact after rejected cross-workspace confirm"
);
let confirm_b = format!("app.sheet.delete_confirm.{enc_b}");
assert!(affine_mobile::perform_a11y_action(
&mut state,
&confirm_b,
MobileA11yAction::Activate,
650.0,
));
assert!(state.doc_by_id("eu.notes").is_none());
}
#[test]
fn screen_reader_scroll_actions_reach_34th_doc_and_30th_collection_and_tag() {
// 1. 34 docs across both 390x844 and 320x568 viewports reachable via ScrollForward + Activate.
for (w, h) in [(390u32, 844u32), (320u32, 568u32)] {
let mut init = seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-11-25");
for i in 1..=34 {
init.docs.push(affine_mobile::MobileDocRecord {
id: format!("doc-a11y-{i}"),
title: format!("A11y Document {i}"),
body_preview: format!("Body {i}"),
tags: Vec::new(),
updated_at_ms: 1_764_000_000 + i as i64,
is_favorite: false,
trashed: false,
journal_date: None,
clock: 1,
outgoing_edges: Vec::new(),
});
}
init.switch_tab(affine_mobile::MobileTab::Explorer, 0.0);
let app = ParityApp::launch_with_state(w, h, init);
app.headless_win.request_frame();
// At top, ScrollBackward returns false.
let top_back = app
.app
.update(|cx| {
app.window_handle.update(cx, |v, _, cx| {
v.perform_a11y_action(
"mobile.explorer.scroll_viewport",
MobileA11yAction::ScrollBackward,
cx,
)
})
})
.unwrap();
assert!(
!top_back,
"{w}x{h}: ScrollBackward at top must return false"
);
let target_id = format!(
"mobile.explorer.doc.{}",
affine_mobile::encode_scoped_doc_target("ws-mobile-rust", "doc-a11y-34")
);
let mut found = false;
for _ in 0..20 {
let visible = app
.app
.update(|cx| {
app.window_handle.update(cx, |v, _, _| {
v.published_a11y_tree().nodes.contains_key(&target_id)
})
})
.unwrap();
if visible {
found = true;
break;
}
let moved = app
.app
.update(|cx| {
app.window_handle.update(cx, |v, _, cx| {
v.perform_a11y_action(
"mobile.explorer.scroll_viewport",
MobileA11yAction::ScrollForward,
cx,
)
})
})
.unwrap();
app.platform.run_until_parked();
app.headless_win.request_frame();
if !moved {
break;
}
}
assert!(
found,
"{w}x{h}: 34th doc must become reachable via ScrollForward"
);
// Scroll to absolute bottom and assert next ScrollForward returns false.
for _ in 0..10 {
let moved = app
.app
.update(|cx| {
app.window_handle.update(cx, |v, _, cx| {
v.perform_a11y_action(
"mobile.explorer.scroll_viewport",
MobileA11yAction::ScrollForward,
cx,
)
})
})
.unwrap();
app.platform.run_until_parked();
app.headless_win.request_frame();
if !moved {
break;
}
}
let bottom_fwd = app
.app
.update(|cx| {
app.window_handle.update(cx, |v, _, cx| {
v.perform_a11y_action(
"mobile.explorer.scroll_viewport",
MobileA11yAction::ScrollForward,
cx,
)
})
})
.unwrap();
assert!(
!bottom_fwd,
"{w}x{h}: ScrollForward at bottom must return false"
);
let activated = app
.app
.update(|cx| {
app.window_handle.update(cx, |v, _, cx| {
v.perform_a11y_action(&target_id, MobileA11yAction::Activate, cx)
})
})
.unwrap();
assert!(activated, "{w}x{h}: Activate on 34th doc must succeed");
let route = app
.app
.update(|cx| {
app.window_handle
.update(cx, |v, _, _| v.state.route.clone())
})
.unwrap();
assert_eq!(route, MobileRoute::Page("doc-a11y-34".into()));
}
// 2. 30 collections and 30 tags scroll to bottom and activate 30th item.
let mut init = seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-11-25");
init.collections.clear();
init.tags.clear();
for i in 1..=30 {
init.collections.push(affine_mobile::MobileCollection {
id: format!("col-bulk-{i}"),
name: format!("Collection #{i}"),
doc_ids: vec!["doc-arch".into()],
});
init.tags
.push((format!("tag-bulk-{i}"), format!("tag-{i}")));
}
init.switch_tab(affine_mobile::MobileTab::Explorer, 0.0);
init.navigate_target(
NavTarget::Collection(String::new()),
Origin::Direct(DirectKind::AllDocs),
);
let app = ParityApp::launch_with_state(390, 844, init);
app.headless_win.request_frame();
for _ in 0..10 {
let moved = app
.app
.update(|cx| {
app.window_handle.update(cx, |v, _, cx| {
v.perform_a11y_action(
"mobile.explorer.scroll_viewport",
MobileA11yAction::ScrollForward,
cx,
)
})
})
.unwrap();
app.platform.run_until_parked();
app.headless_win.request_frame();
if !moved {
break;
}
}
let col30_ok = app
.app
.update(|cx| {
app.window_handle.update(cx, |v, _, cx| {
assert!(
v.published_a11y_tree()
.nodes
.contains_key("mobile.explorer.collection.col-bulk-30")
);
v.perform_a11y_action(
"mobile.explorer.collection.col-bulk-30",
MobileA11yAction::Activate,
cx,
)
})
})
.unwrap();
assert!(col30_ok);
let col_target = app
.app
.update(|cx| {
app.window_handle.update(cx, |v, _, _| {
v.state.history.current().unwrap().target.clone()
})
})
.unwrap();
assert_eq!(col_target, NavTarget::Collection("col-bulk-30".into()));
// Navigate to Tags index, scroll to bottom, verify and activate 30th tag.
app.app
.update(|cx| {
app.window_handle.update(cx, |v, _, cx| {
v.state.navigate_target(
NavTarget::Tag(String::new()),
Origin::Direct(DirectKind::AllDocs),
);
cx.notify();
})
})
.unwrap();
app.platform.run_until_parked();
app.headless_win.request_frame();
for _ in 0..10 {
let moved = app
.app
.update(|cx| {
app.window_handle.update(cx, |v, _, cx| {
v.perform_a11y_action(
"mobile.explorer.scroll_viewport",
MobileA11yAction::ScrollForward,
cx,
)
})
})
.unwrap();
app.platform.run_until_parked();
app.headless_win.request_frame();
if !moved {
break;
}
}
let tag30_ok = app
.app
.update(|cx| {
app.window_handle.update(cx, |v, _, cx| {
assert!(
v.published_a11y_tree()
.nodes
.contains_key("mobile.explorer.tag.tag-bulk-30")
);
v.perform_a11y_action(
"mobile.explorer.tag.tag-bulk-30",
MobileA11yAction::Activate,
cx,
)
})
})
.unwrap();
assert!(tag30_ok);
let tag_target = app
.app
.update(|cx| {
app.window_handle.update(cx, |v, _, _| {
v.state.history.current().unwrap().target.clone()
})
})
.unwrap();
assert_eq!(tag_target, NavTarget::Tag("tag-bulk-30".into()));
}
#[test]
fn empty_title_uses_localized_untitled_in_main_landmark_and_backlinks_sheet() {
let mut init = seed_showcase_state(MobileLocale::ZhHans, ThemeMode::Light, "2026-11-25");
let new_doc_id = init.create_doc(None, 100.0);
assert!(init.doc_by_id(&new_doc_id).unwrap().title.is_empty());
let app = ParityApp::launch_with_state(390, 844, init);
app.headless_win.request_frame();
let main_name = app
.app
.update(|cx| {
app.window_handle.update(cx, |v, _, _| {
v.published_a11y_tree().nodes["app.main"].name.clone()
})
})
.unwrap();
assert_eq!(main_name, "无标题");
// Link the untitled doc to `doc-arch`, open `doc-arch`, and open Backlinks sheet.
let src_id = new_doc_id.clone();
app.app
.update(|cx| {
app.window_handle.update(cx, |v, _, cx| {
let edge = blocksuite_playground_doc::refs::DocRefEdge {
source_doc_id: src_id.clone(),
source_block_id: "b-untitled".into(),
target_doc_id: "doc-arch".into(),
kind: blocksuite_playground_doc::refs::OutboundRefKind::InlineMention,
};
if let Some(d) = v.state.docs.iter_mut().find(|d| d.id == src_id) {
d.outgoing_edges.push(edge.clone());
}
v.state.link_graph.replace_edges(&src_id, vec![edge], 1);
v.state
.open_doc("doc-arch", Origin::Direct(DirectKind::Home));
v.state
.open_sheet_from(MobileSheet::Backlinks, Some("page.backlinks.pill"), 200.0);
v.state.settle_animations(700.0);
cx.notify();
})
})
.unwrap();
app.platform.run_until_parked();
app.headless_win.request_frame();
let (has_untitled_a11y, has_bl_snapshot) = app
.app
.update(|cx| {
app.window_handle.update(cx, |v, window, _| {
let tree = v.published_a11y_tree();
let bl_nodes: Vec<_> = tree
.nodes
.iter()
.filter(|(id, _)| id.starts_with("mobile.sheet.backlink."))
.collect();
let has_untitled = bl_nodes.iter().any(|(_, n)| n.name == "无标题");
let no_empty = bl_nodes.iter().all(|(_, n)| !n.name.is_empty());
assert!(no_empty, "no backlink row may have an empty a11y name");
let snap = window.frame_snapshot();
let has_snap = bl_nodes
.iter()
.any(|(id, _)| snap.elements.contains_key(id.as_str()));
(has_untitled, has_snap)
})
})
.unwrap();
assert!(
has_untitled_a11y,
"backlinks sheet a11y row must show localized 无标题 for untitled source doc"
);
assert!(
has_bl_snapshot,
"backlinks sheet visual snapshot must contain the untitled source doc row"
);
}
@@ -214,7 +214,7 @@ fn explorer_drilldown_and_breadcrumb_folder_navigation_roundtrip() {
t.click_id("mobile.tab.explorer");
t.click_id("mobile.explorer.folder.f-eng");
t.click_id("mobile.explorer.folder.f-mobile");
t.click_id("mobile.explorer.doc.doc-arch");
t.click_id("mobile.explorer.doc.14:ws-mobile-rustdoc-arch");
let route = t
.app
@@ -544,10 +544,12 @@ fn explorer_collections_and_tags_index_filter_exact_members() {
t.window_handle.update(cx, |_, window, _| {
let snap = window.frame_snapshot();
(
snap.elements.contains_key("mobile.explorer.doc.doc-sync"),
snap.elements
.contains_key("mobile.explorer.doc.doc-journal"),
snap.elements.contains_key("mobile.explorer.doc.doc-arch"),
.contains_key("mobile.explorer.doc.14:ws-mobile-rustdoc-sync"),
snap.elements
.contains_key("mobile.explorer.doc.14:ws-mobile-rustdoc-journal"),
snap.elements
.contains_key("mobile.explorer.doc.14:ws-mobile-rustdoc-arch"),
)
})
})
@@ -578,8 +580,10 @@ fn explorer_collections_and_tags_index_filter_exact_members() {
t.window_handle.update(cx, |_, window, _| {
let snap = window.frame_snapshot();
(
snap.elements.contains_key("mobile.explorer.doc.doc-sync"),
snap.elements.contains_key("mobile.explorer.doc.doc-arch"),
snap.elements
.contains_key("mobile.explorer.doc.14:ws-mobile-rustdoc-sync"),
snap.elements
.contains_key("mobile.explorer.doc.14:ws-mobile-rustdoc-arch"),
)
})
})
@@ -774,3 +778,649 @@ fn single_click_sheet_animation_completes_via_request_animation_frame_without_ex
assert!(close_done);
assert!(!panel_mounted);
}
#[test]
fn create_doc_from_home_explorer_root_and_folder_opens_with_expected_origin() {
let t = TestApp::launch(390, 844, MobileLocale::ZhHans);
// 1. Create doc from Home `+` button -> empty stored title, localized display_title,
// workspace-scoped id, Origin::Direct(AllDocs).
t.click_id("mobile.home.new_doc_btn");
let (route1, stored_title1, display_zh, display_en, origin1) = t
.app
.update(|cx| {
t.window_handle.update(cx, |v, _, _| {
let id = match &v.state.route {
MobileRoute::Page(id) => id.clone(),
other => panic!("expected Page route, got {other:?}"),
};
let doc = v.state.doc_by_id(&id).unwrap();
let origin = v.state.history.current().unwrap().origin.clone();
(
id,
doc.title.clone(),
doc.display_title(MobileLocale::ZhHans),
doc.display_title(MobileLocale::En),
origin,
)
})
})
.unwrap();
assert_eq!(route1, "doc-ws-mobile-rust-new-1");
assert!(
stored_title1.is_empty(),
"new doc stored title must stay empty so locale switches update display_title"
);
assert_eq!(display_zh, "无标题");
assert_eq!(display_en, "Untitled");
assert_eq!(origin1, Origin::Direct(DirectKind::AllDocs));
// 2. Return to Home, go to All Docs root -> newly created doc and unfiled journal are listed.
t.click_id("mobile.page.back_btn");
t.click_id("mobile.tab.explorer");
let (has_new_doc, has_journal) = t
.app
.update(|cx| {
t.window_handle.update(cx, |_, window, _| {
let snap = window.frame_snapshot();
(
snap.elements.contains_key(
"mobile.explorer.doc.14:ws-mobile-rustdoc-ws-mobile-rust-new-1",
),
snap.elements
.contains_key("mobile.explorer.doc.14:ws-mobile-rustdoc-journal"),
)
})
})
.unwrap();
assert!(
has_new_doc,
"new doc must appear in All Docs Documents list"
);
assert!(
has_journal,
"unfiled journal doc must appear in All Docs Documents list"
);
// 3. Drill into folder `f-eng` and click `+` -> creates doc mounted in `f-eng` with valid fractional index.
t.click_id("mobile.explorer.folder.f-eng");
t.click_id("mobile.explorer.new_doc_btn");
let (route2, origin2, folder_index) = t
.app
.update(|cx| {
t.window_handle.update(cx, |v, _, _| {
let id = match &v.state.route {
MobileRoute::Page(id) => id.clone(),
other => panic!("expected Page route, got {other:?}"),
};
let origin = v.state.history.current().unwrap().origin.clone();
let idx = v
.state
.folder_rows
.iter()
.find(|r| {
r.folder_type == "doc"
&& r.data == id
&& r.parent_id.as_deref() == Some("f-eng")
})
.map(|r| r.index.clone());
(id, origin, idx)
})
})
.unwrap();
assert_eq!(route2, "doc-ws-mobile-rust-new-2");
assert!(matches!(origin2, Origin::Placement { .. }));
let idx = folder_index.expect("new folder doc must be linked under f-eng");
assert!(
idx.as_str() > "a0" && !idx.starts_with("z9"),
"folder doc index {idx:?} must be a valid fractional index after existing siblings"
);
// 4. Opening a nonexistent doc renders explicit `Document not found` empty state.
t.app
.update(|cx| {
t.window_handle.update(cx, |v, _, cx| {
v.state.route = MobileRoute::Page("doc-does-not-exist".into());
cx.notify();
})
})
.unwrap();
t.platform.run_until_parked();
t.headless_win.request_frame();
let has_not_found = t
.app
.update(|cx| {
t.window_handle.update(cx, |_, window, _| {
let snap = window.frame_snapshot();
snap.elements.contains_key("mobile.page.not_found")
&& snap.elements.contains_key("mobile.page.not_found_back_btn")
})
})
.unwrap();
assert!(
has_not_found,
"missing doc id must render explicit Document not found state"
);
}
#[test]
fn search_no_results_omits_bordered_list_and_shows_empty_state() {
let t = TestApp::launch(390, 844, MobileLocale::En);
t.click_id("mobile.tab.search");
t.app
.update(|cx| {
t.window_handle.update(cx, |v, _, cx| {
v.state.search_query = "NonexistentQuery".to_string();
cx.notify();
})
})
.unwrap();
t.platform.run_until_parked();
t.headless_win.request_frame();
let (has_list, has_empty) = t
.app
.update(|cx| {
t.window_handle.update(cx, |_, window, _| {
let snap = window.frame_snapshot();
(
snap.elements.contains_key("mobile.search.results"),
snap.elements.contains_key("mobile.search.empty_state"),
)
})
})
.unwrap();
assert!(!has_list, "empty search must not render bordered list box");
assert!(has_empty, "empty search must render centered empty state");
}
#[test]
fn journals_week_strip_switches_date_and_creates_new_journal_for_empty_day() {
let t = TestApp::launch(390, 844, MobileLocale::En);
t.click_id("mobile.tab.journals");
// Today (2026-11-25) already has `doc-journal`: clicking CTA opens it without creating a new doc.
let docs_before = t
.app
.update(|cx| t.window_handle.update(cx, |v, _, _| v.state.docs.len()))
.unwrap();
t.click_id("mobile.journals.create_btn");
let (route_today, docs_after_today) = t
.app
.update(|cx| {
t.window_handle
.update(cx, |v, _, _| (v.state.route.clone(), v.state.docs.len()))
})
.unwrap();
assert_eq!(route_today, MobileRoute::Page("doc-journal".into()));
assert_eq!(docs_after_today, docs_before);
// Go back, select 2026-11-26 (no journal yet), and click CTA -> creates & opens new journal.
t.click_id("mobile.page.back_btn");
t.click_id("mobile.journals.day.2026-11-26");
t.click_id("mobile.journals.create_btn");
let (new_route, new_title, new_date, origin) = t
.app
.update(|cx| {
t.window_handle.update(cx, |v, _, _| {
let id = match &v.state.route {
MobileRoute::Page(id) => id.clone(),
other => panic!("expected Page route, got {other:?}"),
};
let doc = v.state.doc_by_id(&id).unwrap();
(
id,
doc.title.clone(),
doc.journal_date.clone(),
v.state.history.current().unwrap().origin.clone(),
)
})
})
.unwrap();
assert_ne!(new_route, "doc-journal");
assert_eq!(new_title, "Journal 2026-11-26");
assert_eq!(new_date.as_deref(), Some("2026-11-26"));
assert_eq!(origin, Origin::Journal);
}
#[test]
fn trashed_doc_supports_restore_ready_backlinks_two_step_delete_and_history_purge() {
// 1. Restore clears trashed flag, hides banner, keeps backlinks `Ready` workspace-wide,
// and rejects late/stale delete or restore calls on non-trashed or wrong-workspace docs.
let t1 = TestApp::launch(390, 844, MobileLocale::En);
t1.click_id("mobile.tab.explorer");
t1.click_id("mobile.explorer.trash");
t1.click_id("mobile.explorer.doc.14:ws-mobile-rustdoc-trash");
t1.click_id("mobile.page.trash_restore_btn.14:ws-mobile-rustdoc-trash");
let (route_after_restore, still_trashed, has_banner, arch_bl_ready, arch_bl_len) = t1
.app
.update(|cx| {
t1.window_handle.update(cx, |v, window, _| {
let bl = v.state.backlinks_for("doc-arch");
assert!(!v.state.restore_doc_scoped("ws-mobile-rust", "doc-trash"));
assert!(!v.state.delete_doc_permanently_scoped(
"ws-mobile-rust",
"doc-trash",
500.0
));
assert!(
!v.state
.delete_doc_permanently_scoped("ws-personal", "doc-trash", 500.0)
);
(
v.state.route.clone(),
v.state.doc_by_id("doc-trash").unwrap().trashed,
window
.frame_snapshot()
.elements
.contains_key("mobile.page.trash_banner"),
bl.completeness == affine_client::BacklinkCompleteness::Ready,
bl.items.len(),
)
})
})
.unwrap();
assert_eq!(route_after_restore, MobileRoute::Page("doc-trash".into()));
assert!(!still_trashed);
assert!(!has_banner);
assert!(
arch_bl_ready,
"restoring trashed doc must sync link_graph clock so backlinks stay Ready"
);
assert_eq!(arch_bl_len, 2);
// 2. Delete permanently requires two-step confirmation; Cancel preserves doc; Confirm purges
// all history entries pointing to `doc-trash` (`Home -> doc-trash -> doc-arch -> doc-trash`).
let t2 = TestApp::launch(390, 844, MobileLocale::En);
t2.app
.update(|cx| {
t2.window_handle.update(cx, |v, _, cx| {
v.state
.open_doc("doc-trash", Origin::Direct(DirectKind::AllDocs));
v.state
.open_doc("doc-arch", Origin::Direct(DirectKind::Home));
v.state
.open_doc("doc-trash", Origin::Direct(DirectKind::AllDocs));
cx.notify();
})
})
.unwrap();
t2.platform.run_until_parked();
t2.headless_win.request_frame();
// First click opens confirmation sheet without deleting.
t2.click_id("mobile.page.trash_delete_btn.14:ws-mobile-rustdoc-trash");
let (sheet_after_first, doc_still_exists) = t2
.app
.update(|cx| {
t2.window_handle.update(cx, |v, _, _| {
(
v.state.active_sheet,
v.state.doc_by_id("doc-trash").is_some(),
)
})
})
.unwrap();
assert_eq!(sheet_after_first, MobileSheet::ConfirmDeleteDoc);
assert!(doc_still_exists, "first click must NOT delete immediately");
// Cancel closes sheet and keeps doc intact.
t2.click_id("app.sheet.delete_cancel.14:ws-mobile-rustdoc-trash");
let (sheet_after_cancel, doc_after_cancel) = t2
.app
.update(|cx| {
t2.window_handle.update(cx, |v, _, _| {
(
v.state.active_sheet,
v.state.doc_by_id("doc-trash").is_some(),
)
})
})
.unwrap();
assert_eq!(sheet_after_cancel, MobileSheet::None);
assert!(doc_after_cancel);
// Reopen and confirm delete -> doc removed, lands on `doc-arch`, one Back goes straight to `Home`.
t2.click_id("mobile.page.trash_delete_btn.14:ws-mobile-rustdoc-trash");
t2.click_id("app.sheet.delete_confirm.14:ws-mobile-rustdoc-trash");
let (route_after_del, doc_exists) = t2
.app
.update(|cx| {
t2.window_handle.update(cx, |v, _, _| {
(
v.state.route.clone(),
v.state.doc_by_id("doc-trash").is_some(),
)
})
})
.unwrap();
assert_eq!(route_after_del, MobileRoute::Page("doc-arch".into()));
assert!(!doc_exists);
t2.click_id("mobile.page.back_btn");
let route_after_back = t2
.app
.update(|cx| t2.window_handle.update(cx, |v, _, _| v.state.route.clone()))
.unwrap();
assert_eq!(
route_after_back,
MobileRoute::Home,
"Back after permanent delete must skip purged ghost entries and reach Home"
);
}
#[test]
fn explorer_scrolls_30_docs_keeps_tabbar_fixed_and_opens_30th_doc() {
let t = TestApp::launch(390, 844, MobileLocale::En);
t.app
.update(|cx| {
t.window_handle.update(cx, |v, _, cx| {
for i in 1..=30 {
v.state.docs.push(affine_mobile::MobileDocRecord {
id: format!("doc-bulk-{i}"),
title: format!("Bulk Document {i}"),
body_preview: format!("Preview {i}"),
tags: Vec::new(),
updated_at_ms: 1_764_000_000 + i as i64,
is_favorite: false,
trashed: false,
journal_date: None,
clock: 1,
outgoing_edges: Vec::new(),
});
}
v.state.switch_tab(affine_mobile::MobileTab::Explorer, 0.0);
cx.notify();
})
})
.unwrap();
t.platform.run_until_parked();
t.headless_win.request_frame();
let tabbar_before = t
.app
.update(|cx| {
t.window_handle.update(cx, |_, window, _| {
window.frame_snapshot().elements["mobile.tabbar"].bounds
})
})
.unwrap();
// Dispatch real scroll-wheel events to scroll to the bottom of the 30-doc list.
for _ in 0..8 {
t.headless_win
.dispatch_input(PlatformInput::Scroll(ui::ScrollEvent {
position: point(px(195.0), px(400.0)),
delta: ui::ScrollDelta::Pixels(point(px(0.0), px(-300.0))),
modifiers: ui::Modifiers::default(),
touch_phase: ui::TouchPhase::Moved,
..Default::default()
}));
t.platform.run_until_parked();
t.headless_win.request_frame();
}
let doc30_id = "mobile.explorer.doc.14:ws-mobile-rustdoc-bulk-30";
let (tabbar_after, snap_bounds, a11y_bounds) = t
.app
.update(|cx| {
t.window_handle.update(cx, |v, window, _| {
let snap = window.frame_snapshot();
let tb = snap.elements["mobile.tabbar"].bounds;
let sb = snap
.elements
.get(doc30_id)
.expect("30th doc must be visible in FrameSnapshot after scrolling")
.bounds;
let ab = v
.published_a11y_tree()
.nodes
.get(doc30_id)
.expect("30th doc must be published in AccessibilityTree after scrolling")
.bounds;
(tb, sb, ab)
})
})
.unwrap();
assert!((tabbar_after.y - tabbar_before.y).abs() <= 0.5);
let drift = (snap_bounds.x - a11y_bounds.x)
.abs()
.max((snap_bounds.y - a11y_bounds.y).abs())
.max((snap_bounds.width - a11y_bounds.width).abs())
.max((snap_bounds.height - a11y_bounds.height).abs());
assert!(drift <= 1.0, "30th doc a11y drift {drift:.2}px");
t.click_id(doc30_id);
let route = t
.app
.update(|cx| t.window_handle.update(cx, |v, _, _| v.state.route.clone()))
.unwrap();
assert_eq!(route, MobileRoute::Page("doc-bulk-30".into()));
}
#[test]
fn touch_swipe_scrolls_30_docs_without_accidental_click_and_back_restores_scroll() {
let t = TestApp::launch(390, 844, MobileLocale::En);
t.app
.update(|cx| {
t.window_handle.update(cx, |v, _, cx| {
for i in 1..=30 {
v.state.docs.push(affine_mobile::MobileDocRecord {
id: format!("doc-bulk-{i}"),
title: format!("Bulk Document {i}"),
body_preview: format!("Preview {i}"),
tags: Vec::new(),
updated_at_ms: 1_764_000_000 + i as i64,
is_favorite: false,
trashed: false,
journal_date: None,
clock: 1,
outgoing_edges: Vec::new(),
});
}
v.state.switch_tab(affine_mobile::MobileTab::Explorer, 0.0);
cx.notify();
})
})
.unwrap();
t.platform.run_until_parked();
t.headless_win.request_frame();
let tabbar_before = t
.app
.update(|cx| {
t.window_handle.update(cx, |_, window, _| {
window.frame_snapshot().elements["mobile.tabbar"].bounds
})
})
.unwrap();
// Perform 4 native Touch pan swipes upward (y=600 -> y=160) to scroll to the 30th doc.
for swipe in 0..4u64 {
let touch_id = ui::TouchId(swipe + 1);
t.headless_win
.dispatch_input(PlatformInput::Touch(ui::TouchEvent {
id: touch_id,
phase: ui::TouchPhase::Started,
position: point(px(195.0), px(600.0)),
predicted_position: None,
force: None,
}));
for step in 1..=8 {
let y = 600.0 - (step as f32) * 55.0;
t.headless_win
.dispatch_input(PlatformInput::Touch(ui::TouchEvent {
id: touch_id,
phase: ui::TouchPhase::Moved,
position: point(px(195.0), px(y)),
predicted_position: None,
force: None,
}));
}
t.headless_win
.dispatch_input(PlatformInput::Touch(ui::TouchEvent {
id: touch_id,
phase: ui::TouchPhase::Ended,
position: point(px(195.0), px(160.0)),
predicted_position: None,
force: None,
}));
t.platform.run_until_parked();
t.headless_win.request_frame();
}
let doc30_id = format!(
"mobile.explorer.doc.{}",
affine_mobile::encode_scoped_doc_target("ws-mobile-rust", "doc-bulk-30")
);
let (route_after_swipe, scroll_after_swipe, tabbar_after, doc30_bounds) = t
.app
.update(|cx| {
t.window_handle.update(cx, |v, window, _| {
let snap = window.frame_snapshot();
(
v.state.route.clone(),
v.state.explorer_scroll_y,
snap.elements["mobile.tabbar"].bounds,
snap.elements
.get(&doc30_id)
.expect("30th doc must be visible after touch swipe")
.bounds,
)
})
})
.unwrap();
assert_eq!(
route_after_swipe,
MobileRoute::Explorer,
"touch swipe must never accidentally open an intermediate document"
);
assert!(
scroll_after_swipe > 600.0,
"expected scroll_y > 600 after swipes, got {scroll_after_swipe}"
);
assert!((tabbar_after.y - tabbar_before.y).abs() <= 0.5);
// Tap the 30th document via native Touch Started -> Ended.
let tap_pos = point(
px(doc30_bounds.x + doc30_bounds.width * 0.5),
px(doc30_bounds.y + doc30_bounds.height * 0.5),
);
t.headless_win
.dispatch_input(PlatformInput::Touch(ui::TouchEvent {
id: ui::TouchId(99),
phase: ui::TouchPhase::Started,
position: tap_pos,
predicted_position: None,
force: None,
}));
t.headless_win
.dispatch_input(PlatformInput::Touch(ui::TouchEvent {
id: ui::TouchId(99),
phase: ui::TouchPhase::Ended,
position: tap_pos,
predicted_position: None,
force: None,
}));
t.platform.run_until_parked();
t.headless_win.request_frame();
let route_after_tap = t
.app
.update(|cx| t.window_handle.update(cx, |v, _, _| v.state.route.clone()))
.unwrap();
assert_eq!(route_after_tap, MobileRoute::Page("doc-bulk-30".into()));
// Pressing Back must restore the exact saved Explorer scroll position.
t.click_id("mobile.page.back_btn");
let (route_after_back, restored_scroll) = t
.app
.update(|cx| {
t.window_handle.update(cx, |v, _, _| {
(v.state.route.clone(), v.state.explorer_scroll_y)
})
})
.unwrap();
assert_eq!(route_after_back, MobileRoute::Explorer);
assert!(
(restored_scroll - scroll_after_swipe).abs() <= 1.0,
"expected restored scroll {scroll_after_swipe}, got {restored_scroll}"
);
}
#[test]
fn mouse_drag_off_list_and_hover_does_not_scroll_or_open_doc() {
let t = TestApp::launch(390, 844, MobileLocale::En);
t.app
.update(|cx| {
t.window_handle.update(cx, |v, _, cx| {
for i in 1..=30 {
v.state.docs.push(affine_mobile::MobileDocRecord {
id: format!("doc-bulk-{i}"),
title: format!("Bulk Document {i}"),
body_preview: format!("Preview {i}"),
tags: Vec::new(),
updated_at_ms: 1_764_000_000 + i as i64,
is_favorite: false,
trashed: false,
journal_date: None,
clock: 1,
outgoing_edges: Vec::new(),
});
}
v.state.switch_tab(affine_mobile::MobileTab::Explorer, 0.0);
cx.notify();
})
})
.unwrap();
t.platform.run_until_parked();
t.headless_win.request_frame();
// Press mouse on a list row, drag onto the bottom TabBar, release on TabBar, then hover back across list.
t.headless_win
.dispatch_input(PlatformInput::MouseDown(ui::MouseDownEvent {
button: ui::MouseButton::Left,
position: point(px(195.0), px(450.0)),
modifiers: ui::Modifiers::default(),
click_count: 1,
first_mouse: false,
}));
t.headless_win
.dispatch_input(PlatformInput::MouseMove(ui::MouseMoveEvent {
position: point(px(195.0), px(810.0)),
pressed_button: Some(ui::MouseButton::Left),
modifiers: ui::Modifiers::default(),
}));
t.headless_win
.dispatch_input(PlatformInput::MouseUp(ui::MouseUpEvent {
button: ui::MouseButton::Left,
position: point(px(195.0), px(810.0)),
modifiers: ui::Modifiers::default(),
click_count: 1,
}));
for y in [700.0_f32, 550.0, 400.0, 250.0] {
t.headless_win
.dispatch_input(PlatformInput::MouseMove(ui::MouseMoveEvent {
position: point(px(195.0), px(y)),
pressed_button: None,
modifiers: ui::Modifiers::default(),
}));
}
t.platform.run_until_parked();
t.headless_win.request_frame();
let (route, scroll_y) = t
.app
.update(|cx| {
t.window_handle.update(cx, |v, _, _| {
(v.state.route.clone(), v.state.explorer_scroll_y)
})
})
.unwrap();
assert_eq!(route, MobileRoute::Explorer);
assert_eq!(
scroll_y, 0.0,
"mouse drag off-list and subsequent unpressed hover must not scroll Explorer"
);
}