fix(desktop): publish backups and reduce work in template and trash views

This commit is contained in:
DarkSky committed 2026-12-05 11:35:08 +09:00
1 parent dbe1cbae29
commit 397994fac8
7 files changed
+517 -152

No files matched your search

@@ -32,10 +32,19 @@ impl ScrollRegion {
.clone()
}
pub(super) fn offset(&self) -> f32 {
self.axis.get().offset
}
pub(super) fn reset(&self) {
self.axis.set(ScrollAxis::default());
}
pub(super) fn reveal_end(&self) {
let max = self.axis.get().max;
self.axis.set(ScrollAxis::new(max, max));
}
pub(super) fn reveal(&self, top: f32, height: f32) {
let axis = self.axis.get();
let viewport = f32::from(self.viewport.get().size.height);
@@ -421,6 +421,18 @@ mod tests {
self.window.request_frame();
}
fn press_key(&self, name: &'static str) -> bool {
let consumed = self.app.update(|cx| {
ui::AnyWindowHandle::from(self.handle)
.update(cx, |_, window, cx| {
window.dispatch_keystroke(ui::Keystroke::parse(name).unwrap(), cx)
})
.unwrap()
});
self.window.request_frame();
consumed
}
fn capture(&self, path: &Path) {
self.shell(|_, window, _| {
window
@@ -898,6 +910,110 @@ mod tests {
}
}
#[test]
fn template_picker_end_reveals_and_selects_the_last_registered_template() {
let session = Session::new(1280, 800, ThemeMode::Light);
let last = session.shell(|view, _, cx| {
let store = &mut view.state.store;
let mut last = String::new();
for index in 0..1_000 {
last = store.create_doc(
format!("Template {:04}", 999 - index),
affine_store::directory::DocMode::Page,
None,
1_900_000_000_000 + index,
);
assert!(store.set_doc_is_template(&last, true));
}
cx.notify();
last
});
session.window.request_frame();
session.click(Page::Preference.id());
session.click("desktop.settings.preference.journal_template");
let assert_last_selected = || {
session.shell(|view, _, _| {
assert_eq!(
view.state
.store
.template_settings()
.journal_template_id
.as_deref(),
Some(last.as_str())
);
});
};
session.press_key("end");
session.press_key("enter");
assert_last_selected();
session.click("desktop.settings.preference.journal_template");
session.press_key("up");
session.press_key("enter");
session.shell(|view, _, _| {
assert!(
view.state
.store
.template_settings()
.journal_template_id
.is_none()
);
});
session.click("desktop.settings.preference.journal_template");
session.press_key("end");
let menu = session.bounds("settings-tpl-journal-scroll");
session.click_point(point(
menu.center().x,
menu.origin.y + menu.size.height - px(14.0),
));
assert_last_selected();
}
#[test]
fn empty_template_picker_shows_and_selects_none_after_arrow_navigation() {
let session = Session::new(1280, 800, ThemeMode::Light);
session.click(Page::Preference.id());
for arrow in ["up", "down"] {
session.shell(|view, _, cx| {
let store = &mut view.state.store;
let mut settings = store.template_settings();
settings.journal_template_id = Some("doc-sync".to_owned());
assert!(store.set_template_settings(settings));
cx.notify();
});
session.window.request_frame();
session.click("desktop.settings.preference.journal_template");
let assert_rows_fit = || {
let viewport = session.bounds("settings-tpl-journal-scroll");
let menu_id = "desktop.settings.preference.journal_template.menu";
let menu = session.bounds(menu_id);
let hint = session.bounds(&format!("{menu_id}.empty"));
let none = session.bounds(&format!("{menu_id}.remove"));
assert_eq!(menu.size.width, px(210.0));
assert!(hint.size.height > px(28.0));
assert!(hint.origin.y >= viewport.origin.y);
assert!(
none.origin.y + none.size.height <= viewport.origin.y + viewport.size.height
);
};
assert_rows_fit();
assert!(session.press_key(arrow));
assert_rows_fit();
assert!(session.press_key("enter"));
session.shell(|view, _, _| {
assert!(
view.state
.store
.template_settings()
.journal_template_id
.is_none()
);
});
}
}
#[test]
fn workspace_preference_properties_backup_and_language_ui_roundtrip() {
let evidence = std::env::var_os("AFFINE_SETTINGS_EVIDENCE").map(std::path::PathBuf::from);
@@ -983,21 +1099,6 @@ mod tests {
assert!(meta.len() > 0);
let _ = std::fs::remove_file(&exported_path);
let nonce = blocksuite_playground_doc::try_random_client_id().expect("nonce");
let uniq_dir = std::env::temp_dir().join(format!("affine-uniq-{nonce:x}"));
let p1 = super::storage_page::write_unique_backup_in(&uniq_dir, "Demo.affine", b"a")
.expect("write 1");
let p2 = super::storage_page::write_unique_backup_in(&uniq_dir, "Demo.affine", b"b")
.expect("write 2");
let p3 = super::storage_page::write_unique_backup_in(&uniq_dir, "Demo.affine", b"c")
.expect("write 3");
assert_eq!(p1.file_name().unwrap(), "Demo.affine");
assert_eq!(p2.file_name().unwrap(), "Demo-2.affine");
assert_eq!(p3.file_name().unwrap(), "Demo-3.affine");
assert_eq!(std::fs::read(&p1).unwrap(), b"a");
assert_eq!(std::fs::read(&p2).unwrap(), b"b");
let _ = std::fs::remove_dir_all(&uniq_dir);
app.click(Page::Appearance.id());
app.click("desktop.settings.appearance.language");
app.shell(|_, window, _| {
@@ -31,39 +31,106 @@ struct ExportFeedback {
}
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn write_unique_backup_in(
struct UnpublishedBackup(Option<std::path::PathBuf>);
#[cfg(not(target_arch = "wasm32"))]
impl Drop for UnpublishedBackup {
fn drop(&mut self) {
if let Some(path) = &self.0 {
let _ = std::fs::remove_file(path);
}
}
}
#[cfg(not(target_arch = "wasm32"))]
fn write_unique_backup_in(
dir: &std::path::Path,
filename: &str,
bytes: &[u8],
) -> anyhow::Result<std::path::PathBuf> {
use std::io::{ErrorKind, Write as _};
) -> std::io::Result<std::path::PathBuf> {
use std::io::Write as _;
publish_backup(dir, filename, |file| file.write_all(bytes))
}
#[cfg(not(target_arch = "wasm32"))]
fn publish_backup(
dir: &std::path::Path,
filename: &str,
write: impl FnOnce(&mut std::fs::File) -> std::io::Result<()>,
) -> std::io::Result<std::path::PathBuf> {
use std::{
fs::{File, OpenOptions},
io::ErrorKind,
sync::atomic::{AtomicU64, Ordering},
};
static NEXT_TEMP: AtomicU64 = AtomicU64::new(0);
std::fs::create_dir_all(dir)?;
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt as _;
options.mode(0o600);
}
let (temp, mut file) = loop {
let serial = NEXT_TEMP.fetch_add(1, Ordering::Relaxed);
let pid = std::process::id();
let temp = dir.join(format!(".affine-export-{pid}-{serial}.tmp"));
match options.open(&temp) {
Ok(file) => break (temp, file),
Err(err) if err.kind() == ErrorKind::AlreadyExists => continue,
Err(err) => return Err(err),
}
};
let _temp_cleanup = UnpublishedBackup(Some(temp.clone()));
let result = write(&mut file).and_then(|()| file.sync_all());
drop(file);
result?;
#[cfg(unix)]
let mut try_link = true;
let stem = filename.strip_suffix(".affine").unwrap_or(filename);
let mut index = 1usize;
loop {
let candidate_name = if index == 1 {
for index in 0usize.. {
let dest = dir.join(if index == 0 {
format!("{stem}.affine")
} else {
format!("{stem}-{index}.affine")
};
let dest = dir.join(candidate_name);
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&dest)
{
});
#[cfg(unix)]
if try_link {
match std::fs::hard_link(&temp, &dest) {
Ok(()) => return Ok(dest),
Err(err) if err.kind() == ErrorKind::AlreadyExists => continue,
Err(err)
if matches!(
err.kind(),
ErrorKind::Unsupported | ErrorKind::CrossesDevices
) =>
{
try_link = false;
}
Err(err) => return Err(err),
}
}
let mut source = File::open(&temp)?;
match options.open(&dest) {
Ok(mut file) => {
file.write_all(bytes)?;
file.sync_all()?;
let mut cleanup = UnpublishedBackup(Some(dest.clone()));
let result = std::io::copy(&mut source, &mut file).and_then(|_| file.sync_all());
drop(file);
result?;
cleanup.0 = None;
return Ok(dest);
}
Err(err) if err.kind() == ErrorKind::AlreadyExists => {
index += 1;
}
Err(err) => return Err(err.into()),
Err(err) if err.kind() == ErrorKind::AlreadyExists => continue,
Err(err) => return Err(err),
}
}
Err(std::io::Error::other("No backup name is available"))
}
#[cfg(not(target_arch = "wasm32"))]
@@ -245,3 +312,43 @@ impl SettingsModal {
}
}
}
#[cfg(test)]
mod tests {
#![cfg(not(target_arch = "wasm32"))]
use super::*;
use std::io::Write as _;
#[test]
fn failed_backup_write_leaves_the_directory_empty() {
let dir = backup_test_directory();
let result = publish_backup(&dir, "Demo.affine", |file| {
file.write_all(&[0; 4096])?;
Err(std::io::Error::other("Injected write failure"))
});
assert!(result.is_err());
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0);
std::fs::remove_dir(dir).unwrap();
}
#[test]
fn backup_publishes_complete_bytes_at_the_first_free_name() {
let dir = backup_test_directory();
std::fs::write(dir.join("Demo.affine"), b"original").unwrap();
for (name, bytes) in [("Demo-1.affine", b"first"), ("Demo-2.affine", b"other")] {
let path = write_unique_backup_in(&dir, "Demo.affine", bytes).unwrap();
assert_eq!(path, dir.join(name));
assert_eq!(std::fs::read(path).unwrap(), bytes);
}
assert_eq!(std::fs::read(dir.join("Demo.affine")).unwrap(), b"original");
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 3);
std::fs::remove_dir_all(dir).unwrap();
}
fn backup_test_directory() -> std::path::PathBuf {
let nonce = blocksuite_playground_doc::try_random_client_id().unwrap();
let dir = std::env::temp_dir().join(format!("affine-backup-test-{nonce:x}"));
std::fs::create_dir(&dir).unwrap();
dir
}
}
@@ -1,6 +1,8 @@
//! Template toggle and template-document picker widgets for workspace settings.
use std::rc::Rc;
use std::{ops::Range, rc::Rc};
use affine_store::workspace_db::{WorkspaceDbTableName, YjsTableDoc};
use ui::{
Anchor, App, Entity, FontWeight, InteractiveElement, IntoElement, MouseButton, ParentElement,
@@ -14,7 +16,93 @@ use super::{
controls::{FocusStops, ScrollRegion, focus_stop, scroll_area},
i18n::SettingsStrings,
};
use crate::{DesktopFlexExt, DesktopPalette, workbench::DesktopShellView};
use crate::{
DesktopFlexExt, DesktopPalette, doc_store::DesktopDocStore, workbench::DesktopShellView,
};
const ROW_HEIGHT: f32 = 28.0;
const ROW_GAP: f32 = 2.0;
const ROW_STRIDE: f32 = ROW_HEIGHT + ROW_GAP;
const LIST_PADDING: f32 = 6.0;
const DIVIDER_HEIGHT: f32 = 1.0;
const DIVIDER_MARGIN: f32 = 2.0;
const MAX_VIEWPORT_HEIGHT: f32 = 200.0;
struct TemplateOption {
id: String,
title: String,
}
#[derive(PartialEq, Eq)]
struct TemplateRevision {
workspace: String,
meta: u64,
order: u64,
properties: Option<u64>,
}
impl TemplateRevision {
fn matches(&self, store: &DesktopDocStore, properties: Option<u64>) -> bool {
self.workspace == store.active_workspace().id
&& self.meta == store.derived.meta_rev
&& self.order == store.directory.db().root().revision()
&& self.properties == properties
}
}
fn template_properties(store: &DesktopDocStore) -> Option<&YjsTableDoc> {
store
.directory
.db()
.db_table(WorkspaceDbTableName::DocProperties)
}
fn template_title<'a>(
store: &'a DesktopDocStore,
properties: &YjsTableDoc,
id: &str,
) -> Option<&'a str> {
let entry = store.get_doc(id)?;
(!entry.meta.trashed && properties.get_row_bool(id, "isTemplate") == Some(true))
.then_some(entry.meta.title.as_str())
}
fn display_title<'a>(title: &'a str, untitled: &'a str) -> &'a str {
if title.trim().is_empty() {
untitled
} else {
title
}
}
fn registered_templates(
store: &DesktopDocStore,
properties: Option<&YjsTableDoc>,
) -> Vec<TemplateOption> {
let Some(properties) = properties else {
return Vec::new();
};
store
.directory
.db()
.root()
.list_pages()
.unwrap_or_default()
.into_iter()
.filter_map(|page| {
let title = template_title(store, properties, &page.id)?.to_owned();
Some(TemplateOption { id: page.id, title })
})
.collect()
}
fn row_window(len: usize, offset: f32, viewport: f32) -> Range<usize> {
const OVERSCAN: usize = 2;
let top = (offset - LIST_PADDING).max(0.0);
let start = (top / ROW_STRIDE).floor() as usize;
let end = ((top + viewport) / ROW_STRIDE).ceil() as usize;
start.saturating_sub(OVERSCAN).min(len)..end.saturating_add(OVERSCAN).min(len)
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum TemplateTarget {
@@ -22,10 +110,39 @@ pub(super) enum TemplateTarget {
Page,
}
#[derive(Clone, Default)]
#[derive(Default)]
pub(super) struct TemplateMenuState {
pub(super) open: Option<TemplateTarget>,
highlight: usize,
options: Option<(TemplateRevision, Rc<Vec<TemplateOption>>)>,
}
impl TemplateMenuState {
fn options(
menu: &Entity<Self>,
shell: &Entity<DesktopShellView>,
app: &mut App,
) -> Rc<Vec<TemplateOption>> {
let store = &shell.read(app).state.store;
let properties = template_properties(store);
let properties_rev = properties.map(YjsTableDoc::revision);
if let Some((key, options)) = &menu.read(app).options
&& key.matches(store, properties_rev)
{
return Rc::clone(options);
}
let key = TemplateRevision {
workspace: store.active_workspace().id.clone(),
meta: store.derived.meta_rev,
order: store.directory.db().root().revision(),
properties: properties_rev,
};
let options = Rc::new(registered_templates(store, properties));
menu.update(app, |state, _| {
state.options = Some((key, Rc::clone(&options)))
});
options
}
}
pub(super) fn menu_state(window: &mut Window, app: &mut App) -> Entity<TemplateMenuState> {
@@ -123,7 +240,6 @@ pub(super) fn template_selector(
id: &'static str,
target: TemplateTarget,
current_id: Option<&str>,
template_docs: &[(String, String)],
disabled: bool,
t: &SettingsStrings,
menu_state: &Entity<TemplateMenuState>,
@@ -142,18 +258,15 @@ pub(super) fn template_selector(
window,
app,
);
const ROW_HEIGHT: f32 = 28.0;
const ROW_GAP: f32 = 2.0;
const LIST_PADDING: f32 = 6.0;
const DIVIDER_HEIGHT: f32 = 1.0;
const DIVIDER_MARGIN: f32 = 2.0;
let snapshot_state = menu_state.read(app).clone();
let is_open = !disabled && snapshot_state.open == Some(target);
let snapshot = menu_state.read(app);
let is_open = !disabled && snapshot.open == Some(target);
let highlight = snapshot.highlight;
let store = &shell.read(app).state.store;
let current_label = current_id
.and_then(|cid| template_docs.iter().find(|(did, _)| did == cid))
.map_or(t.none_option, |(_, title)| title.as_str())
.and_then(|id| template_title(store, template_properties(store)?, id))
.map_or(t.none_option, |title| display_title(title, t.untitled))
.to_owned();
let template_docs = is_open.then(|| TemplateMenuState::options(menu_state, shell, app));
let stop = (!disabled).then(|| focus_stop(id, stops, window, app));
let focused = stop.as_ref().is_some_and(|s| s.handle.is_focused(window));
let keyboard = window.last_input_was_keyboard();
@@ -217,7 +330,6 @@ pub(super) fn template_selector(
.text_color(palette.text_secondary),
);
let item_count = template_docs.len() + 1;
if disabled {
trigger = trigger.opacity(0.5).cursor(ui::CursorStyle::Arrow);
} else if let Some(stop) = stop.clone() {
@@ -226,7 +338,7 @@ pub(super) fn template_selector(
let key_menu = menu_state.clone();
let key_stop = stop.clone();
let key_apply = apply_choice.clone();
let docs_for_keys = template_docs.to_vec();
let docs_for_keys = template_docs.clone();
let click_scroll = tpl_scroll.clone();
let key_scroll = tpl_scroll.clone();
trigger = trigger
@@ -256,18 +368,24 @@ pub(super) fn template_selector(
cx.notify();
});
}
"up" | "down" if open => {
"up" | "down" | "home" | "end" if open => {
let Some(docs) = &docs_for_keys else {
return;
};
key_menu.update(app, |state, cx| {
let current = state.highlight.min(item_count - 1);
state.highlight = if event.keystroke.key == "up" {
current.checked_sub(1).unwrap_or(item_count - 1)
} else {
(current + 1) % item_count
let last = docs.len();
let current = state.highlight.min(last);
state.highlight = match event.keystroke.key.as_str() {
"up" => current.checked_sub(1).unwrap_or(last),
"down" => (current + 1) % (last + 1),
"end" => last.saturating_sub(1),
_ => 0,
};
if !docs_for_keys.is_empty() {
let mut top =
LIST_PADDING + state.highlight as f32 * (ROW_HEIGHT + ROW_GAP);
if state.highlight == docs_for_keys.len() {
if docs.is_empty() {
key_scroll.reveal_end();
} else {
let mut top = LIST_PADDING + state.highlight as f32 * ROW_STRIDE;
if state.highlight == last {
top += DIVIDER_HEIGHT + 2.0 * DIVIDER_MARGIN + ROW_GAP;
}
key_scroll.reveal(top, ROW_HEIGHT);
@@ -278,9 +396,10 @@ pub(super) fn template_selector(
"enter" | "space" => {
key_stop.reveal(window);
if open {
let idx = key_menu.read(app).highlight;
let chosen = docs_for_keys.get(idx).map(|(id, _)| id.clone());
key_apply(chosen, app);
if let Some(docs) = &docs_for_keys {
let idx = key_menu.read(app).highlight;
key_apply(docs.get(idx).map(|doc| doc.id.clone()), app);
}
} else {
key_scroll.reset();
key_menu.update(app, |state, cx| {
@@ -299,7 +418,7 @@ pub(super) fn template_selector(
}
wrapper = wrapper.child(trigger);
if is_open && let Some(stop) = stop {
if let (Some(template_docs), Some(stop)) = (template_docs, stop) {
let bounds = stop.bounds.get();
let tokens = crate::theme_tokens_for(mode);
let panel_bg = crate::rgba_to_hsla(tokens.background_overlay_panel);
@@ -320,12 +439,29 @@ pub(super) fn template_selector(
.gap(px(ROW_GAP))
.p(px(LIST_PADDING));
for (idx, (doc_id, title)) in template_docs.iter().enumerate() {
let visible_rows = template_docs.len().max(1) + 1;
let content_h = visible_rows as f32 * ROW_STRIDE
+ 2.0 * LIST_PADDING
+ DIVIDER_HEIGHT
+ 2.0 * DIVIDER_MARGIN
- ROW_GAP;
let viewport_h = content_h.min(MAX_VIEWPORT_HEIGHT);
let offset = tpl_scroll.offset().min(content_h - viewport_h);
let rows = row_window(template_docs.len(), offset, viewport_h);
let mut window_rows = div()
.flex()
.flex_col()
.flex_shrink(0.0)
.gap(px(ROW_GAP))
.mt(px(rows.start as f32 * ROW_STRIDE))
.mb(px((template_docs.len() - rows.end) as f32 * ROW_STRIDE));
for idx in rows {
let TemplateOption { id: doc_id, title } = &template_docs[idx];
let selected = current_id == Some(doc_id.as_str());
let highlighted = idx == snapshot_state.highlight;
let highlighted = idx == highlight;
let pick = apply_choice.clone();
let chosen_id = doc_id.clone();
items_list = items_list.child(
window_rows = window_rows.child(
div()
.id(SharedString::from(format!("{menu_id}.{doc_id}")))
.flex()
@@ -346,7 +482,12 @@ pub(super) fn template_selector(
.text_size(px(12.0))
.text_color(palette.text_primary)
.on_click(move |_, _, app| pick(Some(chosen_id.clone()), app))
.child(div().min_w_0().truncate().child(title.clone()))
.child(
div()
.min_w_0()
.truncate()
.child(display_title(title, t.untitled).to_owned()),
)
.children(selected.then(|| {
svg()
.data(icons::DONE.svg.as_bytes())
@@ -359,6 +500,7 @@ pub(super) fn template_selector(
if template_docs.is_empty() {
items_list = items_list.child(
div()
.snapshot(ui::snap_id!("{menu_id}.empty"), Some(MODAL_ID))
.px(px(8.0))
.py(px(6.0))
.flex_shrink(0.0)
@@ -366,9 +508,12 @@ pub(super) fn template_selector(
.text_color(palette.text_muted)
.child(t.no_templates_yet),
);
} else {
items_list = items_list.child(window_rows);
}
let remove_idx = template_docs.len();
let remove_pick = apply_choice;
let remove_id = SharedString::from(format!("{menu_id}.remove"));
items_list = items_list
.child(
div()
@@ -379,7 +524,8 @@ pub(super) fn template_selector(
)
.child(
div()
.id(SharedString::from(format!("{menu_id}.remove")))
.id(remove_id.clone())
.snapshot(remove_id, Some(MODAL_ID))
.flex()
.items_center()
.gap(px(6.0))
@@ -388,7 +534,7 @@ pub(super) fn template_selector(
.rounded(px(6.0))
.flex_shrink(0.0)
.cursor_pointer()
.bg(if snapshot_state.highlight == remove_idx {
.bg(if highlight == remove_idx {
palette.hover_color
} else {
ui::transparent_black()
@@ -400,13 +546,12 @@ pub(super) fn template_selector(
.child(t.none_option),
);
let visible_rows = template_docs.len().max(1) + 1;
let viewport_h = (visible_rows as f32 * (ROW_HEIGHT + ROW_GAP)
+ 2.0 * LIST_PADDING
+ DIVIDER_HEIGHT
+ 2.0 * DIVIDER_MARGIN
- ROW_GAP)
.min(200.0);
let mut scroll = scroll_area(scroll_id, &tpl_scroll, items_list);
if template_docs.is_empty() {
scroll.style().max_size.height = Some(px(MAX_VIEWPORT_HEIGHT).into());
} else {
scroll = scroll.h(px(viewport_h));
}
let out_scroll = tpl_scroll.clone();
let menu_box = div()
.id(menu_id)
@@ -431,7 +576,7 @@ pub(super) fn template_selector(
});
}
})
.child(scroll_area(scroll_id, &tpl_scroll, items_list).h(px(viewport_h)));
.child(scroll);
wrapper = wrapper.child(
deferred(
@@ -98,19 +98,6 @@ impl SettingsModal {
let palette = self.palette;
let t = strings_for(&state.display_language);
let template_settings = state.store.template_settings();
let template_docs: Vec<(String, String)> = state
.store
.template_docs()
.into_iter()
.map(|doc| {
let title = if doc.title.trim().is_empty() {
t.untitled.to_owned()
} else {
doc.title.clone()
};
(doc.id.clone(), title)
})
.collect();
let active_doc = state
.split
.active()
@@ -294,7 +281,6 @@ impl SettingsModal {
JOURNAL_TEMPLATE_ID,
TemplateTarget::Journal,
template_settings.journal_template_id.as_deref(),
&template_docs,
readonly,
t,
&tpl_menu,
@@ -348,7 +334,6 @@ impl SettingsModal {
PAGE_TEMPLATE_ID,
TemplateTarget::Page,
template_settings.page_template_id.as_deref(),
&template_docs,
readonly,
t,
&tpl_menu,
@@ -285,19 +285,17 @@ impl RenderOnce for TrashFooter {
button
};
let ids = vec![self.doc.clone()];
let restore_action: Option<Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>> =
writable.then(|| {
Rc::new(controls.action(ids.clone(), |_, state, ids| {
for id in ids {
state.restore_doc(&id);
}
let id = self.doc.clone();
Rc::new(controls.action(move |_, state| {
state.restore_doc(&id);
})) as Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>
});
let delete_action: Option<Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>> =
writable.then(|| {
Rc::new(controls.action(ids, |selection, _, ids| {
selection.pending = Some(ids);
Rc::new(controls.action(move |selection, _| {
selection.pending = Some(vec![self.doc.clone()]);
})) as Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>
});
@@ -1,7 +1,7 @@
use std::{
cell::RefCell,
collections::{BTreeSet, HashMap},
rc::Rc,
rc::{Rc, Weak},
sync::Arc,
};
@@ -51,6 +51,7 @@ struct TrashSelection {
/// The multi-select mode of the web trash. It stays on when `Clear` empties the selection.
select_mode: bool,
selected: BTreeSet<String>,
visible_count: RefCell<Option<(Weak<Vec<DocRowKey>>, usize)>>,
/// The documents that wait for the permanent delete confirmation.
pending: Option<Vec<String>>,
confirmation_focus: Option<ConfirmationFocus>,
@@ -159,9 +160,28 @@ fn resolve_confirmation(
}
impl TrashSelection {
fn visible_count(&self, keys: &Rc<Vec<DocRowKey>>) -> usize {
if self.selected.is_empty() {
return 0;
}
if let Some((cached, count)) = self.visible_count.borrow().as_ref()
&& cached.ptr_eq(&Rc::downgrade(keys))
{
return *count;
}
let count = keys
.iter()
.filter(|key| self.selected.contains(&key.id))
.count();
self.visible_count
.replace(Some((Rc::downgrade(keys), count)));
count
}
fn leave_select_mode(&mut self) {
self.select_mode = false;
self.selected.clear();
self.visible_count.get_mut().take();
}
fn dismiss(&mut self) {
@@ -173,6 +193,7 @@ impl TrashSelection {
return;
};
self.failed = false;
self.visible_count.get_mut().take();
for id in ids {
if state.permanently_delete_doc(&id) {
self.selected.remove(&id);
@@ -190,7 +211,23 @@ struct TrashView {
shell: Entity<DesktopShellView>,
}
type TrashAction = fn(&mut TrashSelection, &mut DesktopAppState, Vec<String>);
enum ActionRows {
One(String),
Selected(Rc<Vec<DocRowKey>>),
}
impl ActionRows {
fn ids(&self, selection: &TrashSelection) -> Vec<String> {
match self {
Self::One(id) => vec![id.clone()],
Self::Selected(keys) => keys
.iter()
.filter(|key| selection.selected.contains(&key.id))
.map(|key| key.id.clone())
.collect(),
}
}
}
/// The row keys of the trash, shared while the document views stay the same.
#[derive(Default)]
@@ -251,17 +288,7 @@ impl TrashControls {
fn action(
&self,
ids: Vec<String>,
action: TrashAction,
) -> impl Fn(&ui::ClickEvent, &mut Window, &mut App) + 'static {
self.rows_action(move || ids.clone(), action)
}
/// Like `action`, but reads the document IDs only on a click.
fn rows_action(
&self,
ids: impl Fn() -> Vec<String> + 'static,
action: TrashAction,
action: impl Fn(&mut TrashSelection, &mut DesktopAppState) + 'static,
) -> impl Fn(&ui::ClickEvent, &mut Window, &mut App) + 'static {
let this = self.clone();
move |_, window, app| {
@@ -273,7 +300,8 @@ impl TrashControls {
return;
}
let pending = this.selection.update(cx, |selection, cx| {
action(selection, &mut shell.state, ids());
action(selection, &mut shell.state);
selection.visible_count.get_mut().take();
if selection.pending.is_some() && selection.confirmation_focus.is_none() {
let focus = ConfirmationFocus {
buttons: ConfirmFocus::new(cx),
@@ -346,21 +374,10 @@ impl RenderOnce for TrashView {
let keys = row_keys.read(app).resolve(store);
let writable = !store.is_readonly_sqlite();
let state = controls.selection.read(app);
let selected: Vec<_> = if state.selected.is_empty() {
Vec::new()
} else {
keys.iter()
.filter(|key| state.selected.contains(&key.id))
.map(|key| key.id.clone())
.collect()
};
let selected_count = state.visible_count(&keys);
let has_rows = !keys.is_empty();
let all_selected = has_rows && keys.len() == selected.len();
let all_selected = has_rows && keys.len() == selected_count;
let select_mode = state.select_mode && writable && has_rows;
let all_ids = {
let keys = Rc::clone(&keys);
move || keys.iter().map(|key| key.id.clone()).collect::<Vec<_>>()
};
let mut heading = div()
.flex()
.flex_wrap()
@@ -392,11 +409,12 @@ impl RenderOnce for TrashView {
.snapshot("desktop.trash.select_all", Some("desktop.trash.view"))
.snapshot_text(if all_selected { "Clear" } else { "Select all" })
.on_click({
let toggle = controls.rows_action(all_ids, |selection, _, ids| {
if ids.iter().all(|id| selection.selected.contains(id)) {
let keys = Rc::clone(&keys);
let toggle = controls.action(move |selection, _| {
if selection.visible_count(&keys) == keys.len() {
selection.selected.clear();
} else {
selection.selected = ids.into_iter().collect();
selection.selected = keys.iter().map(|key| key.id.clone()).collect();
}
});
let select_bar = focus.clone();
@@ -451,27 +469,27 @@ impl RenderOnce for TrashView {
.flex_wrap()
.items_center()
.gap(px(8.0))
.child(format!("{} selected", selected.len()))
.child(format!("{selected_count} selected"))
.child(restore_button(
"desktop.trash.restore_selected",
ui::snap_id!("desktop.trash.restore_selected"),
selected.clone(),
ActionRows::Selected(Rc::clone(&keys)),
palette,
writable,
selected_count != 0,
&controls,
))
.child(delete_button(
"desktop.trash.delete_selected",
ui::snap_id!("desktop.trash.delete_selected"),
selected,
ActionRows::Selected(Rc::clone(&keys)),
palette,
writable,
selected_count != 0,
&controls,
))
.child(
button("desktop.trash.select_done", "Done", palette, writable)
.snapshot("desktop.trash.select_done", Some("desktop.trash.view"))
.on_click(controls.action(Vec::new(), |selection, _, _| {
.on_click(controls.action(|selection, _| {
selection.leave_select_mode();
})),
),
@@ -546,12 +564,11 @@ fn trash_row(
let identity = doc_identity(&doc.id);
let checked = state.selected.contains(&doc.id);
let toggle = writable.then(|| {
let toggle = Rc::new(controls.action(vec![doc.id.clone()], |selection, _, ids| {
let id = doc.id.clone();
let toggle = Rc::new(controls.action(move |selection, _| {
selection.select_mode = true;
if let Some(id) = ids.into_iter().next()
&& !selection.selected.remove(&id)
{
selection.selected.insert(id);
if !selection.selected.remove(&id) {
selection.selected.insert(id.clone());
}
}));
let select_bar = select_bar.clone();
@@ -612,7 +629,7 @@ fn trash_row(
.child(restore_button(
"restore",
ui::snap_id!("desktop.trash.restore.{}", doc.id),
vec![doc.id.clone()],
ActionRows::One(doc.id.clone()),
palette,
writable,
controls,
@@ -620,7 +637,7 @@ fn trash_row(
.child(delete_button(
"delete",
ui::snap_id!("desktop.trash.delete.{}", doc.id),
vec![doc.id.clone()],
ActionRows::One(doc.id.clone()),
palette,
writable,
controls,
@@ -631,20 +648,19 @@ fn trash_row(
fn restore_button(
id: &'static str,
snapshot: ui::SnapshotId,
ids: Vec<String>,
rows: ActionRows,
palette: DesktopPalette,
writable: bool,
enabled: bool,
controls: &TrashControls,
) -> ui::Stateful<Div> {
// `Clear` keeps the select mode with no documents, and then the bar actions do nothing.
let enabled = writable && !ids.is_empty();
let button =
button(id, "Restore", palette, enabled).snapshot(snapshot, Some("desktop.trash.view"));
if !enabled {
return button;
}
button.on_click(controls.action(ids, |selection, state, ids| {
for id in ids {
button.on_click(controls.action(move |selection, state| {
for id in rows.ids(selection) {
if state.restore_doc(&id) {
selection.selected.remove(&id);
}
@@ -656,12 +672,11 @@ fn restore_button(
fn delete_button(
id: &'static str,
snapshot: ui::SnapshotId,
ids: Vec<String>,
rows: ActionRows,
palette: DesktopPalette,
writable: bool,
enabled: bool,
controls: &TrashControls,
) -> ui::Stateful<Div> {
let enabled = writable && !ids.is_empty();
let button = button(id, "Delete permanently", palette, enabled)
.snapshot(snapshot, Some("desktop.trash.view"));
if !enabled {
@@ -671,7 +686,12 @@ fn delete_button(
confirmation_trigger(
button,
palette,
controls.action(ids, |selection, _, ids| selection.pending = Some(ids)),
controls.action(move |selection, _| {
let ids = rows.ids(selection);
if !ids.is_empty() {
selection.pending = Some(ids);
}
}),
)
}