mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 19:25:00 +03:00
fix(desktop): preserve explorer prefs and align backlink controls
This commit is contained in:
1 parent
391ab796b1
commit
5ab77c6e94
9 files changed
+352
-82
No files matched your search
@@ -45,10 +45,7 @@ use super::{
|
||||
};
|
||||
use crate::{
|
||||
DesktopFlexExt as _, DesktopPalette,
|
||||
doc_store::{
|
||||
DesktopDocMeta, ExplorerOrder, ExplorerPrefsStore, ExplorerRouteScope, ExplorerViewMode,
|
||||
PageWidth,
|
||||
},
|
||||
doc_store::{DesktopDocMeta, ExplorerOrder, ExplorerRouteScope, ExplorerViewMode, PageWidth},
|
||||
split_view::DesktopRoute,
|
||||
workbench::DesktopShellView,
|
||||
};
|
||||
@@ -87,9 +84,7 @@ impl RenderOnce for DocsExplorer {
|
||||
let state = window.use_keyed_state(location.key("desktop.explorer.state"), app, |_, _| {
|
||||
ExplorerState::default()
|
||||
});
|
||||
let prefs_entity = window.use_keyed_state("desktop.explorer.prefs", app, |_, _| {
|
||||
ExplorerPrefsStore::default()
|
||||
});
|
||||
let prefs_entity = self.shell.read(app).explorer_prefs.clone();
|
||||
let display_menu = window.use_keyed_state(
|
||||
location.key("desktop.explorer.display_menu"),
|
||||
app,
|
||||
|
||||
@@ -216,6 +216,35 @@ fn compact_all_docs_tab_clears_hidden_collection_filter() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod route_lifetime {
|
||||
use super::*;
|
||||
|
||||
pub(super) fn open_sync_document(shell: &ExplorerShell) {
|
||||
shell.click("desktop.list.doc.doc-sync");
|
||||
shell.update(|view, _, _| {
|
||||
assert_eq!(
|
||||
view.state.split.active().active_route().doc_id(),
|
||||
Some("doc-sync")
|
||||
);
|
||||
});
|
||||
assert!(!shell.contains("desktop.explorer.grid"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_memory_grid_preference_survives_opening_a_document() {
|
||||
let shell = ExplorerShell::open(
|
||||
1280,
|
||||
800,
|
||||
DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-03"),
|
||||
);
|
||||
shell.click("desktop.explorer.grid");
|
||||
open_sync_document(&shell);
|
||||
shell.click("desktop.sidebar.all_docs");
|
||||
assert!(shell.bounds("desktop.list.doc.doc-sync").height >= 148.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
const PREFS_SPACE_ID: &str = "ws-affine-desktop";
|
||||
|
||||
@@ -227,7 +256,11 @@ fn display_preferences_survive_connected_sqlite_reopen_and_skip_read_only() {
|
||||
let dir = std::env::temp_dir().join(format!("desktop-explorer-prefs-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let executable = std::env::current_exe().expect("desktop test executable");
|
||||
for save_phase in ["save-before-binding", "save-after-binding"] {
|
||||
for save_phase in [
|
||||
"save-before-binding",
|
||||
"save-after-binding",
|
||||
"save-from-document",
|
||||
] {
|
||||
let workspace_dir = dir.join(save_phase);
|
||||
for phase in [save_phase, "reopen"] {
|
||||
let output = Command::new(&executable)
|
||||
@@ -339,25 +372,33 @@ async fn sqlite_explorer_prefs_child() {
|
||||
};
|
||||
let prefs_path = PathBuf::from(store.storage().path()).with_extension("db.explorer-prefs.json");
|
||||
let database = checkpointed_database().await;
|
||||
if phase == "save-before-binding" {
|
||||
let from_document = phase == "save-from-document";
|
||||
if phase == "save-before-binding" || from_document {
|
||||
configure_display();
|
||||
assert!(!prefs_path.exists());
|
||||
}
|
||||
if from_document {
|
||||
route_lifetime::open_sync_document(&shell);
|
||||
}
|
||||
shell.update(|view, _, cx| {
|
||||
view.connect_workspace(Arc::new(Mutex::new(session)), host, NOW_MS, |_| {}, cx)
|
||||
.expect("connect workspace");
|
||||
});
|
||||
shell.window.request_frame();
|
||||
if !from_document {
|
||||
shell.window.request_frame();
|
||||
}
|
||||
if phase == "save-after-binding" {
|
||||
configure_display();
|
||||
}
|
||||
let saved = std::fs::read_to_string(&prefs_path)
|
||||
.expect("preferences saved after binding and one frame");
|
||||
let saved = std::fs::read_to_string(&prefs_path).expect("preferences saved on binding");
|
||||
let saved: serde_json::Value = serde_json::from_str(&saved).expect("saved preference JSON");
|
||||
let all_docs = &saved["scopes"]["allDocs"];
|
||||
assert_eq!(all_docs["view"], "grid");
|
||||
assert_eq!(all_docs["grid"]["groupBy"]["type"], "docPrimaryMode");
|
||||
assert_eq!(all_docs["grid"]["showDocPreview"], false);
|
||||
if from_document {
|
||||
shell.click("desktop.sidebar.all_docs");
|
||||
}
|
||||
assert!(shell.contains("desktop.explorer.group_header.page"));
|
||||
assert!(shell.bounds("desktop.list.doc.doc-sync").height >= 148.0);
|
||||
if phase == "reopen" {
|
||||
|
||||
+37
-16
@@ -150,6 +150,7 @@ impl Panel<'_> {
|
||||
.bg(palette.bg_elevated)
|
||||
.text_size(px(13.0))
|
||||
.text_color(palette.text_primary);
|
||||
let first_stop = self.stops.len();
|
||||
let epoch = self.sections.read(self.app).query_epoch;
|
||||
let search = self.input(
|
||||
&format!("{key}.search.{epoch}"),
|
||||
@@ -161,7 +162,7 @@ impl Panel<'_> {
|
||||
let query = search.read(self.app).text().trim().to_owned();
|
||||
let search_stop = search.read(self.app).focus_stop();
|
||||
menu = menu.child(search);
|
||||
let first_stop = self.stops.len();
|
||||
let mut choices = Vec::new();
|
||||
let mut list = div().flex().flex_col().gap(px(2.0));
|
||||
let needle = query.to_lowercase();
|
||||
let shown: Vec<_> = options
|
||||
@@ -187,6 +188,7 @@ impl Panel<'_> {
|
||||
palette,
|
||||
));
|
||||
let value = query.clone();
|
||||
choices.push((stop.clone(), None));
|
||||
list = list.child(activate(control, stop, move |_, app| {
|
||||
if save(DatabaseCellEdit::CreateOption(value.clone()), app) {
|
||||
sections.update(app, |state, cx| {
|
||||
@@ -227,14 +229,14 @@ impl Panel<'_> {
|
||||
))
|
||||
.child(div().flex_1())
|
||||
.children(checked.then(|| icon(icons::DONE, palette.text_primary)));
|
||||
let more = {
|
||||
let (more, more_stop) = {
|
||||
let sections = self.sections.clone();
|
||||
let id = option.id.clone();
|
||||
let (control, stop) = self.control(
|
||||
&format!("{key}.option.{}.more", option.id),
|
||||
Some(icons::MORE_HORIZONTAL),
|
||||
);
|
||||
activate(control.px(px(4.0)), stop, move |_, app| {
|
||||
let button = activate(control.px(px(4.0)), stop.clone(), move |_, app| {
|
||||
sections.update(app, |state, cx| {
|
||||
state.option_menu = if state.option_menu.as_deref() == Some(&id) {
|
||||
None
|
||||
@@ -243,8 +245,10 @@ impl Panel<'_> {
|
||||
};
|
||||
cx.notify();
|
||||
});
|
||||
})
|
||||
});
|
||||
(button, stop)
|
||||
};
|
||||
choices.push((stop.clone(), Some(more_stop)));
|
||||
let anchor = anchor.clone();
|
||||
let pick = activate(control.flex_1().min_w_0(), stop, move |window, app| {
|
||||
save(edit.clone(), app);
|
||||
@@ -270,11 +274,15 @@ impl Panel<'_> {
|
||||
}
|
||||
// `0.27.5` `TagsInlineEditor` scrolls its options in a viewport up to 200 px tall
|
||||
// under the fixed search field.
|
||||
let rows = self.stops[first_stop..].to_vec();
|
||||
let rows = self.stops[first_stop + 1..].to_vec();
|
||||
// The properties panel keeps the trigger in view. The picker scrolls its own rows.
|
||||
for stop in &mut self.stops[first_stop..] {
|
||||
stop.bounds = anchor.bounds.clone();
|
||||
}
|
||||
menu = menu.child(scroll_menu(
|
||||
self.properties.database_key(&format!("{key}.options")),
|
||||
list,
|
||||
rows.clone(),
|
||||
rows,
|
||||
(px(212.0), px(200.0)),
|
||||
self.window,
|
||||
self.app,
|
||||
@@ -299,17 +307,30 @@ impl Panel<'_> {
|
||||
}
|
||||
})
|
||||
.capture_key_down(move |event, window, app| {
|
||||
// `Down` and `Up` in the search field go to the first and last row,
|
||||
// before the field reads them as caret moves.
|
||||
if !search_stop.handle.is_focused(window) {
|
||||
return;
|
||||
}
|
||||
let row = match event.keystroke.key.as_str() {
|
||||
"down" => rows.first(),
|
||||
"up" => rows.last(),
|
||||
_ => None,
|
||||
let down = match event.keystroke.key.as_str() {
|
||||
"down" => true,
|
||||
"up" => false,
|
||||
_ => return,
|
||||
};
|
||||
if let Some(row) = row {
|
||||
let current = choices.iter().position(|(row, more)| {
|
||||
row.handle.is_focused(window)
|
||||
|| more
|
||||
.as_ref()
|
||||
.is_some_and(|stop| stop.handle.is_focused(window))
|
||||
});
|
||||
let next = match current {
|
||||
Some(index) if down => choices.get(index + 1).or(choices.first()),
|
||||
Some(index) => index
|
||||
.checked_sub(1)
|
||||
.and_then(|index| choices.get(index))
|
||||
.or(choices.last()),
|
||||
None if search_stop.handle.is_focused(window) && down => {
|
||||
choices.first()
|
||||
}
|
||||
None if search_stop.handle.is_focused(window) => choices.last(),
|
||||
None => return,
|
||||
};
|
||||
if let Some((row, _)) = next {
|
||||
row.handle.focus(window, app);
|
||||
window.prevent_default();
|
||||
app.stop_propagation();
|
||||
|
||||
@@ -71,6 +71,69 @@ fn database_backlink_option_picker_picks_a_filtered_option_with_down_and_enter()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn database_backlink_option_picker_arrows_choose_rows_and_tab_reaches_option_actions() {
|
||||
for dialog in [false, true] {
|
||||
for (column, first, second, expected) in [
|
||||
(
|
||||
"col-status",
|
||||
"opt-todo",
|
||||
"opt-done",
|
||||
DatabaseCellValue::Text("opt-done".into()),
|
||||
),
|
||||
(
|
||||
"col-tags",
|
||||
"opt-rust",
|
||||
"opt-ui",
|
||||
DatabaseCellValue::MultiSelect(vec!["opt-rust".into(), "opt-ui".into()]),
|
||||
),
|
||||
] {
|
||||
let (prefix, app) = backlink_shell(dialog);
|
||||
let key = format!("{PARENT}/{DATABASE}/{ROW}");
|
||||
let cell_id = |part: &str| format!("{prefix}.database.{key}.cell.{column}.{part}");
|
||||
let focused = |part: &str| {
|
||||
app.update(|_, window, _| window.frame_snapshot().elements[&cell_id(part)].focused)
|
||||
};
|
||||
app.click(&format!("{prefix}.database.{key}"));
|
||||
app.click(&cell_id("value"));
|
||||
app.click(&cell_id("search.0"));
|
||||
app.key("down");
|
||||
assert!(focused(&format!("option.{first}")), "{prefix} {column}");
|
||||
app.key("down");
|
||||
assert!(focused(&format!("option.{second}")), "{prefix} {column}");
|
||||
app.key("enter");
|
||||
app.update(|shell, _, _| {
|
||||
assert_eq!(cell(&shell.state.store, column), expected, "{prefix}");
|
||||
});
|
||||
|
||||
if !app.contains(&cell_id("picker")) {
|
||||
app.click(&cell_id("value"));
|
||||
}
|
||||
app.click(&cell_id("search.0"));
|
||||
app.key("up");
|
||||
assert!(focused(&format!("option.{second}")), "{prefix} {column}");
|
||||
app.key("up");
|
||||
assert!(focused(&format!("option.{first}")), "{prefix} {column}");
|
||||
app.key("tab");
|
||||
assert!(
|
||||
focused(&format!("option.{first}.more")),
|
||||
"{prefix} {column}"
|
||||
);
|
||||
app.key("shift-tab");
|
||||
assert!(focused(&format!("option.{first}")), "{prefix} {column}");
|
||||
app.key("tab");
|
||||
app.key(if dialog { "enter" } else { "space" });
|
||||
assert!(
|
||||
app.contains(&cell_id(&format!("option.{first}.name"))),
|
||||
"{prefix} {column}"
|
||||
);
|
||||
app.update(|shell, _, _| {
|
||||
assert_eq!(cell(&shell.state.store, column), expected, "{prefix}");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn database_backlink_option_picker_scrolls_to_and_picks_the_last_of_many_options() {
|
||||
let key = format!("{PARENT}/{DATABASE}/{ROW}");
|
||||
@@ -111,19 +174,21 @@ fn database_backlink_option_picker_scrolls_to_and_picks_the_last_of_many_options
|
||||
);
|
||||
let item = format!("{prefix}.database.{key}.cell.col-status.option.{last}");
|
||||
assert!(app.bounds(&item).y > bottom, "{width}x{height}");
|
||||
for _ in 0..12 {
|
||||
let rect = app.bounds(&item);
|
||||
if rect.y + rect.height <= bottom {
|
||||
break;
|
||||
}
|
||||
app.scroll(picker.x + picker.width / 2.0, bottom - 24.0, -120.0);
|
||||
}
|
||||
let rect = app.bounds(&item);
|
||||
assert!(
|
||||
rect.y >= picker.y && rect.y + rect.height <= bottom,
|
||||
"{width}x{height}: {rect:?} in {picker:?}"
|
||||
);
|
||||
app.click(&item);
|
||||
app.click(&format!("{prefix}.database.{key}.cell.col-status.search.0"));
|
||||
app.key("up");
|
||||
app.update(|_, window, _| {
|
||||
let frame = window.frame_snapshot();
|
||||
let row = &frame.elements[&item];
|
||||
assert!(row.focused, "{width}x{height}");
|
||||
assert!(
|
||||
row.bounds.y >= row.content_mask.y - 0.5
|
||||
&& row.bounds.bottom() <= row.content_mask.bottom() + 0.5,
|
||||
"{width}x{height}: {:?} in {:?}",
|
||||
row.bounds,
|
||||
row.content_mask
|
||||
);
|
||||
});
|
||||
app.key("enter");
|
||||
app.update(|shell, _, _| {
|
||||
assert_eq!(
|
||||
cell(&shell.state.store, "col-status"),
|
||||
|
||||
@@ -607,7 +607,7 @@ fn database_backlink_link_cells_edit_and_open_only_links_of_the_workspace_origin
|
||||
// Document links at the workspace origin, with and without a view mode, and the same
|
||||
// paths at another origin. A mode of `None` keeps the mode the document opens in.
|
||||
let edgeless = Some(DocViewMode::Edgeless);
|
||||
let cases: [(&str, Option<&str>, Option<DocViewMode>); 8] = [
|
||||
let cases = [
|
||||
(
|
||||
"https://app.affine.pro/workspace/{ws}/{parent}",
|
||||
Some(PARENT),
|
||||
@@ -623,8 +623,39 @@ fn database_backlink_link_cells_edit_and_open_only_links_of_the_workspace_origin
|
||||
Some(PARENT),
|
||||
edgeless,
|
||||
),
|
||||
("/workspace/{ws}/{parent}#notes", Some(PARENT), None),
|
||||
(
|
||||
"/workspace/{ws}/{parent}?mode=edgeless#notes",
|
||||
Some(PARENT),
|
||||
edgeless,
|
||||
),
|
||||
("/workspace/{ws}/{parent}?commentId=c1", Some(PARENT), None),
|
||||
(
|
||||
"/desktop/?workspace={ws}&doc={parent}#notes",
|
||||
Some(PARENT),
|
||||
None,
|
||||
),
|
||||
(
|
||||
"/desktop/?workspace={ws}&doc={parent}&mode=edgeless#notes",
|
||||
Some(PARENT),
|
||||
edgeless,
|
||||
),
|
||||
(
|
||||
"/desktop/?workspace={ws}&doc={parent}&commentId=c1",
|
||||
Some(PARENT),
|
||||
None,
|
||||
),
|
||||
(
|
||||
"https://example.org/workspace/{ws}/{parent}?commentId=c1#notes",
|
||||
None,
|
||||
None,
|
||||
),
|
||||
("/workspace/{ws}/doc-board", Some("doc-board"), None),
|
||||
("/workspace/{ws}/{parent}?blockIds={db}", Some(PARENT), None),
|
||||
(
|
||||
"/workspace/{ws}/{parent}?blockIds={db}&commentId=c1#notes",
|
||||
Some(PARENT),
|
||||
Some(DocViewMode::Page),
|
||||
),
|
||||
("https://example.org/workspace/{ws}/{parent}", None, None),
|
||||
(
|
||||
"https://example.org/workspace/{ws}/{parent}?blockIds={db}",
|
||||
|
||||
@@ -173,6 +173,7 @@ impl DesktopShellView {
|
||||
}
|
||||
}),
|
||||
});
|
||||
self.sync_explorer_prefs(cx);
|
||||
cx.notify();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -24,14 +24,14 @@ use affine_store::{
|
||||
};
|
||||
use anyhow::{Context as _, Result, anyhow};
|
||||
use blocksuite_playground_doc::{session::PageDocSession, try_random_client_id};
|
||||
use ui::Context;
|
||||
use ui::{Context, Entity};
|
||||
use ui_tokens::ThemeMode;
|
||||
|
||||
use super::{DesktopAppState, DesktopShellView, topbar::SavedTabs};
|
||||
use crate::{
|
||||
doc_store::{
|
||||
DesktopDocStore, LoadedWorkspace, PendingUpdates, SessionWriter, load_workspace,
|
||||
merge_pending_updates,
|
||||
DesktopDocStore, ExplorerPrefsStore, LoadedWorkspace, PendingUpdates, SessionWriter,
|
||||
load_workspace, merge_pending_updates,
|
||||
},
|
||||
showcase::SHOWCASE_WORKSPACE_ID,
|
||||
split_view::DesktopRoute,
|
||||
@@ -616,6 +616,7 @@ impl DesktopShellView {
|
||||
}),
|
||||
});
|
||||
self.save_local_workspaces();
|
||||
self.sync_explorer_prefs(cx);
|
||||
workspaces
|
||||
}
|
||||
|
||||
@@ -687,6 +688,26 @@ impl DesktopShellView {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn new_explorer_prefs(cx: &mut Context<Self>) -> Entity<ExplorerPrefsStore> {
|
||||
let prefs = ui::AppContext::new(cx, |_| ExplorerPrefsStore::default());
|
||||
cx.observe(&prefs, |_, _, cx| cx.notify()).detach();
|
||||
prefs
|
||||
}
|
||||
|
||||
pub(super) fn sync_explorer_prefs(&self, cx: &mut Context<Self>) {
|
||||
let store = &self.state.store;
|
||||
let workspace_id = &store.active_workspace().id;
|
||||
self.explorer_prefs.update(cx, |prefs, _| {
|
||||
prefs.workspace_prefs_with_local(
|
||||
workspace_id,
|
||||
store,
|
||||
self.explorer_prefs_binding(workspace_id),
|
||||
|| self.local_explorer_prefs(workspace_id),
|
||||
&mut |id, json| self.save_local_explorer_prefs(id, json),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// Return the identity of the workspace preference binding without reading it.
|
||||
pub(crate) fn explorer_prefs_binding(&self, workspace_id: &str) -> usize {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
|
||||
@@ -62,6 +62,7 @@ pub(crate) enum BlockReveal {
|
||||
/// Interactive GPU UI root view for AFFiNE Web Desktop & Electron shell.
|
||||
pub struct DesktopShellView {
|
||||
pub state: DesktopAppState,
|
||||
pub(crate) explorer_prefs: ui::Entity<crate::doc_store::ExplorerPrefsStore>,
|
||||
editor_host: DesktopEditorHost,
|
||||
pending_block: Option<PendingBlockLink>,
|
||||
pub(crate) sidebar_rows: SidebarRowIndex,
|
||||
@@ -100,6 +101,7 @@ impl DesktopShellView {
|
||||
};
|
||||
Self {
|
||||
state,
|
||||
explorer_prefs: Self::new_explorer_prefs(cx),
|
||||
editor_host: DesktopEditorHost::new(),
|
||||
pending_block: None,
|
||||
sidebar_rows: SidebarRowIndex::default(),
|
||||
|
||||
@@ -122,12 +122,15 @@ impl DesktopShellView {
|
||||
let Some(url) = absolute_cell_url(url, &origin) else {
|
||||
return;
|
||||
};
|
||||
if let Some(target) = BlockLink::parse(&url)
|
||||
let document_url = cell_document_url(&url);
|
||||
if let Some(target) = document_url.as_deref().and_then(BlockLink::parse)
|
||||
&& self.open_document_block_link(target, cx)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if let Some((doc_id, mode)) = workspace_doc_of(&url, &origin, &workspace_id)
|
||||
if let Some((doc_id, mode)) = document_url
|
||||
.as_deref()
|
||||
.and_then(|url| workspace_doc_of(url, &origin, &workspace_id))
|
||||
&& self.state.is_openable_doc(&doc_id)
|
||||
&& self.state.store.ensure_doc_hydrated(&doc_id) == Ok(true)
|
||||
{
|
||||
@@ -256,9 +259,69 @@ fn absolute_cell_url(url: &str, origin: &str) -> Option<String> {
|
||||
(mailto || BlockLink::server_origin(&absolute).is_some()).then_some(absolute)
|
||||
}
|
||||
|
||||
/// The document and the optional `mode` of a `/workspace/<workspace>/<doc>` URL or a Web
|
||||
/// Desktop `?workspace=&doc=` URL at `origin` without block parameters, when it is in
|
||||
/// `workspace_id`.
|
||||
fn decode_url_part(part: &str) -> Option<String> {
|
||||
let bytes = part.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut index = 0;
|
||||
while index < bytes.len() {
|
||||
let byte = bytes[index];
|
||||
let escaped = (byte == b'%')
|
||||
.then(|| part.get(index + 1..index + 3))
|
||||
.flatten()
|
||||
.and_then(|hex| u8::from_str_radix(hex, 16).ok());
|
||||
match escaped {
|
||||
Some(value) => {
|
||||
out.push(value);
|
||||
index += 3;
|
||||
}
|
||||
None => {
|
||||
out.push(byte);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
String::from_utf8(out).ok()
|
||||
}
|
||||
|
||||
/// Keep the parameters that identify a document, its mode, or its selection.
|
||||
fn cell_document_url(url: &str) -> Option<String> {
|
||||
let url = url.split_once('#').map_or(url, |(head, _)| head);
|
||||
let (base, query) = url.split_once('?').unwrap_or((url, ""));
|
||||
let (_, authority) = base.split_once("://")?;
|
||||
let path = &authority[authority.find('/')?..];
|
||||
let desktop = matches!(path, "/desktop/" | "/desktop");
|
||||
if !desktop && !path.starts_with("/workspace/") {
|
||||
return None;
|
||||
}
|
||||
let mut normalized = base.to_owned();
|
||||
let mut separator = '?';
|
||||
for (key, value) in query.split('&').filter_map(|pair| pair.split_once('=')) {
|
||||
let Some(key) = decode_url_part(key) else {
|
||||
continue;
|
||||
};
|
||||
let mode;
|
||||
let value = match key.as_str() {
|
||||
"workspace" | "doc" if desktop => value,
|
||||
"blockIds" | "elementIds" if !value.is_empty() => value,
|
||||
"mode" => {
|
||||
mode = decode_url_part(value);
|
||||
match mode.as_deref() {
|
||||
Some(mode @ ("page" | "edgeless")) => mode,
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
normalized.push(separator);
|
||||
normalized.push_str(&key);
|
||||
normalized.push('=');
|
||||
normalized.push_str(value);
|
||||
separator = '&';
|
||||
}
|
||||
Some(normalized)
|
||||
}
|
||||
|
||||
/// The document and optional mode of a workspace link at the active workspace origin.
|
||||
fn workspace_doc_of(
|
||||
url: &str,
|
||||
origin: &str,
|
||||
@@ -270,29 +333,6 @@ fn workspace_doc_of(
|
||||
let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
|
||||
let path = &rest[rest.find('/')?..];
|
||||
let (path, query) = path.split_once('?').unwrap_or((path, ""));
|
||||
let decode = |part: &str| {
|
||||
let bytes = part.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut index = 0;
|
||||
while index < bytes.len() {
|
||||
let byte = bytes[index];
|
||||
let escaped = (byte == b'%')
|
||||
.then(|| part.get(index + 1..index + 3))
|
||||
.flatten()
|
||||
.and_then(|hex| u8::from_str_radix(hex, 16).ok());
|
||||
match escaped {
|
||||
Some(value) => {
|
||||
out.push(value);
|
||||
index += 3;
|
||||
}
|
||||
None => {
|
||||
out.push(byte);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
String::from_utf8(out).ok()
|
||||
};
|
||||
let desktop = matches!(path, "/desktop/" | "/desktop");
|
||||
let (mut workspace, mut doc, mut mode) = (None, None, None);
|
||||
if let Some(tail) = path.strip_prefix("/workspace/") {
|
||||
@@ -300,17 +340,19 @@ fn workspace_doc_of(
|
||||
if page.contains('/') {
|
||||
return None;
|
||||
}
|
||||
(workspace, doc) = (decode(id), decode(page));
|
||||
(workspace, doc) = (decode_url_part(id), decode_url_part(page));
|
||||
} else if !desktop {
|
||||
return None;
|
||||
}
|
||||
for pair in query.split('&').filter(|pair| !pair.is_empty()) {
|
||||
match pair.split_once('=')? {
|
||||
("workspace", value) if desktop => workspace = decode(value),
|
||||
("doc", value) if desktop => doc = decode(value),
|
||||
("workspace", value) if desktop => {
|
||||
workspace = decode_url_part(&value.replace('+', " "))
|
||||
}
|
||||
("doc", value) if desktop => doc = decode_url_part(&value.replace('+', " ")),
|
||||
("mode", "page") => mode = Some(DocViewMode::Page),
|
||||
("mode", "edgeless") => mode = Some(DocViewMode::Edgeless),
|
||||
_ => return None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let doc = doc.filter(|doc| !doc.is_empty())?;
|
||||
@@ -358,12 +400,12 @@ mod tests {
|
||||
(
|
||||
"/workspace/ws-1/doc-a?mode=slides",
|
||||
"https://app.affine.pro/workspace/ws-1/doc-a?mode=slides",
|
||||
None,
|
||||
Some(("doc-a", None)),
|
||||
),
|
||||
(
|
||||
"/workspace/ws-1/doc-a?doc=doc-b",
|
||||
"https://app.affine.pro/workspace/ws-1/doc-a?doc=doc-b",
|
||||
None,
|
||||
Some(("doc-a", None)),
|
||||
),
|
||||
(
|
||||
"https://example.org/workspace/ws-1/doc-a",
|
||||
@@ -383,7 +425,7 @@ mod tests {
|
||||
(
|
||||
"https://app.affine.pro/workspace/ws-1/doc-a?blockIds=b",
|
||||
"https://app.affine.pro/workspace/ws-1/doc-a?blockIds=b",
|
||||
None,
|
||||
Some(("doc-a", None)),
|
||||
),
|
||||
(
|
||||
"//example.org/workspace/ws-1/doc-a",
|
||||
@@ -400,7 +442,9 @@ mod tests {
|
||||
assert_eq!(absolute.as_deref(), Some(url), "{value}");
|
||||
let absolute = absolute.unwrap_or_default();
|
||||
assert_eq!(
|
||||
workspace_doc_of(&absolute, ORIGIN, "ws-1"),
|
||||
cell_document_url(&absolute)
|
||||
.as_deref()
|
||||
.and_then(|url| workspace_doc_of(url, ORIGIN, "ws-1")),
|
||||
doc.map(|(doc, mode)| (doc.to_owned(), mode)),
|
||||
"{value}"
|
||||
);
|
||||
@@ -417,6 +461,55 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_document_links_keep_modes_and_selections_with_extra_parameters() {
|
||||
const ORIGIN: &str = "https://app.affine.pro";
|
||||
for (route, separator) in [
|
||||
("/workspace/ws-1/doc-a", '?'),
|
||||
("/desktop/?workspace=ws-1&doc=doc-a", '&'),
|
||||
] {
|
||||
for (suffix, mode) in [
|
||||
("#notes".to_owned(), None),
|
||||
(format!("{separator}commentId=c1"), None),
|
||||
(
|
||||
format!("{separator}mode=edgeless#notes"),
|
||||
Some(DocViewMode::Edgeless),
|
||||
),
|
||||
] {
|
||||
let url = cell_document_url(&format!("{ORIGIN}{route}{suffix}")).unwrap();
|
||||
assert_eq!(
|
||||
workspace_doc_of(&url, ORIGIN, "ws-1"),
|
||||
Some(("doc-a".to_owned(), mode))
|
||||
);
|
||||
}
|
||||
for (selection, expected_mode) in [
|
||||
("blockIds=b&mode=slides", DocViewMode::Page),
|
||||
("mode=edgeless&elementIds=e", DocViewMode::Edgeless),
|
||||
] {
|
||||
let url = cell_document_url(&format!(
|
||||
"{ORIGIN}{route}{separator}{selection}&commentId=c1#notes"
|
||||
))
|
||||
.unwrap();
|
||||
match BlockLink::parse(&url).unwrap() {
|
||||
ParsedBlockLink::Page { link, block_ids } => {
|
||||
assert_eq!(expected_mode, DocViewMode::Page);
|
||||
assert_eq!(link.doc_id, "doc-a");
|
||||
assert_eq!(block_ids, ["b"]);
|
||||
}
|
||||
ParsedBlockLink::Edgeless {
|
||||
doc_id,
|
||||
element_ids,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(expected_mode, DocViewMode::Edgeless);
|
||||
assert_eq!(doc_id, "doc-a");
|
||||
assert_eq!(element_ids, ["e"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn share_url_encodes_workspace_and_document_on_both_hosts() {
|
||||
let target = DocTarget {
|
||||
|
||||
Reference in new issue
Block a user