feat(desktop): add database row backlink properties in doc inspector

Show the rows of databases in other documents that link to the
document, as the 0.27.5 DocDatabaseBacklinkInfo panel does, in the
inspector Properties tab and in the Page information dialog.

- Find the rows from the link graph: a row block of an affine:database
  whose text or embed references the document, also with a query or a
  fragment after the document ID. Skip trashed documents,
  template documents and rows that show no column. Sort the rows, then
  keep the first 100.
- Show one collapsible section for each row. The section lists the
  rich-text, number, checkbox, date, link, progress, select and
  multi-select cells, sorted by column name.
- Open the database block from the section header. A click opens it in
  the active pane, Cmd or Ctrl opens a new tab, and Shift opens a center
  peek. Each path opens Page mode and selects the database block.
- Read and write date cells in the local time zone. A date edit stores
  the local midnight of the day.
- Let the select and multi-select picker search the options, create an
  option from the search text, and rename, recolor or delete an option.
  The options scroll in a viewport up to 200 px tall under the search
  field. Down and Up in the search field go to the options, and Escape
  closes the picker before the dialog. The picker shows above the Page
  information dialog.
- Show a link cell as a link. A document link of the workspace origin
  opens in the app with its mode, and other http, https and mailto URLs
  open in the browser. Other schemes do not open. An edit button changes
  the URL in place.
- Write each cell edit to the parent document as one undo step. Close
  the open undo step of the parent document before a rich-text edit.
  Read-only workspaces show the values without controls.
- Show nothing when no database row links to the document.
This commit is contained in:
DarkSky committed 2026-12-04 20:46:49 +09:00
1 parent f3551424e8
commit f32d18af76
12 files changed
+2746 -16

No files matched your search

@@ -0,0 +1,294 @@
//! Rows of `affine:database` blocks in other documents that link to a document, and edits of
//! their cells.
use std::{cmp::Ordering, collections::BTreeSet};
use affine_store::workspace_db::{WorkspaceDb, WorkspaceDbTableName};
use blocksuite_editor::database::TAG_COLOR_PALETTE;
use blocksuite_playground_doc::{
read::{BlockContent, DatabaseCellValue, DatabaseColumn, DatabaseData},
schema::DatabaseCellSpec,
try_random_client_id,
};
use serde_json::Value as JsonValue;
use super::{DesktopDocStore, navigation::resolve_tag_color};
/// Column types that the database backlink panel shows, as in `0.27.5` `DatabaseRendererTypes`.
pub(crate) const DATABASE_BACKLINK_CELL_TYPES: [&str; 8] = [
"rich-text",
"checkbox",
"date",
"number",
"link",
"progress",
"select",
"multi-select",
];
/// Search limit of `0.27.5` `DocsSearchService::watchDatabasesTo`.
const DATABASE_BACKLINK_LIMIT: usize = 100;
/// One row of an `affine:database` block in another document that links to a document.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct DatabaseBacklink {
pub(crate) doc_id: String,
pub(crate) doc_title: String,
pub(crate) database_id: String,
pub(crate) database_name: String,
pub(crate) row_id: String,
/// Supported columns of the row, sorted by name.
pub(crate) cells: Vec<(DatabaseColumn, DatabaseCellValue)>,
}
/// A value written to one database backlink cell.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum DatabaseCellEdit {
/// Replace the plain text of a `rich-text` cell. Only the changed range is spliced, so
/// marks and references outside it stay.
RichText(String),
/// Add or remove one option of a `multi-select` cell.
ToggleOption(String),
/// Replace the cell value.
Value(DatabaseCellSpec),
/// Add an option named `value` to the column and select it in the cell, as `0.27.5`
/// `TagsInlineEditor` does when its query matches no option.
CreateOption(String),
/// Rename or recolor an option of the column.
UpdateOption {
id: String,
value: String,
color: String,
},
/// Remove an option from the column and from every cell that holds it.
DeleteOption(String),
}
fn locale_order(a: &str, b: &str) -> Ordering {
a.to_lowercase()
.cmp(&b.to_lowercase())
.then_with(|| a.cmp(b))
}
/// The RGB color of a `select` option color (`var(--affine-tag-*)` or `#rrggbb`).
pub(crate) fn select_option_rgb(color: &str, theme: ui_tokens::ThemeMode) -> u32 {
resolve_tag_color(color, crate::theme_tokens_for(theme))
}
impl DesktopDocStore {
/// Rows of `affine:database` blocks in other documents that link to `doc_id`, as
/// `0.27.5` `DocDatabaseBacklinksService` finds them: a row block whose own text or embed
/// references the document, with or without a `?` or `#` part after the document ID.
/// Trashed and template documents and rows without a shown column are left out.
pub(crate) fn database_backlinks(&mut self, doc_id: &str) -> Vec<DatabaseBacklink> {
let mut found = Vec::new();
for entry in self.docs.values() {
if entry.meta.trashed || entry.meta.id == doc_id {
continue;
}
let rows: BTreeSet<&str> = self
.link_graph
.outbound_edges(&entry.meta.id)
.iter()
.filter(|edge| edge.target_doc_id.split(['?', '#']).next() == Some(doc_id))
.map(|edge| edge.source_block_id.as_str())
.collect();
if rows.is_empty() {
continue;
}
let nodes = entry.snapshot.root.iter().chain(&entry.snapshot.detached);
for node in nodes.flat_map(|root| root.walk()) {
let BlockContent::Database(data) = &node.content else {
continue;
};
for row in node
.children
.iter()
.filter(|row| rows.contains(row.id.as_str()))
{
let mut cells: Vec<_> = data
.columns
.iter()
.filter(|column| {
DATABASE_BACKLINK_CELL_TYPES.contains(&column.column_type.as_str())
})
.map(|column| {
let value = data
.cells
.get(&(row.id.clone(), column.id.clone()))
.cloned()
.unwrap_or(DatabaseCellValue::Null);
(column.clone(), value)
})
.collect();
if cells.is_empty() {
continue;
}
cells.sort_by(|(a, _), (b, _)| locale_order(&a.name, &b.name));
found.push(DatabaseBacklink {
doc_id: entry.meta.id.clone(),
doc_title: entry.meta.title.clone(),
database_id: node.id.clone(),
database_name: data.title.plain.clone(),
row_id: row.id.clone(),
cells,
});
}
}
}
let parents: BTreeSet<String> = found.iter().map(|row| row.doc_id.clone()).collect();
let templates: BTreeSet<String> = parents
.into_iter()
.filter(|doc| self.is_template_doc(doc))
.collect();
found.retain(|row| !templates.contains(&row.doc_id));
found.sort_by(|a, b| {
locale_order(&a.database_name, &b.database_name)
.then_with(|| a.doc_id.cmp(&b.doc_id))
.then_with(|| a.row_id.cmp(&b.row_id))
});
found.truncate(DATABASE_BACKLINK_LIMIT);
found
}
/// Whether the workspace properties mark `doc_id` as a template.
fn is_template_doc(&mut self, doc_id: &str) -> bool {
let read = |db: &WorkspaceDb| {
db.db_table(WorkspaceDbTableName::DocProperties)
.and_then(|table| table.get_raw_row(doc_id))
.and_then(|row| row.get("isTemplate").and_then(JsonValue::as_bool))
== Some(true)
};
let now = self.writer_now();
match self.with_session(now, |session| {
Ok(read(session.directory().lock_directory().db()))
}) {
Some(result) => result.unwrap_or(false),
None => read(self.directory.db()),
}
}
/// Write one cell of a database backlink row in its document as one undo step.
pub(crate) fn edit_database_backlink_cell(
&mut self,
row: &DatabaseBacklink,
column_id: &str,
edit: DatabaseCellEdit,
now_ms: i64,
) -> bool {
if self.is_readonly_sqlite() {
return false;
}
let Some(entry) = self
.docs
.get_mut(&row.doc_id)
.filter(|entry| !entry.meta.trashed)
else {
return false;
};
let Ok(before) = entry.session.encode_state_vector_v1() else {
return false;
};
let (database, row_id, now) =
(row.database_id.as_str(), row.row_id.as_str(), now_ms as u64);
let session = &mut entry.session;
let written = match edit {
DatabaseCellEdit::RichText(text) => {
let current = match entry.snapshot.block(database).map(|node| &node.content) {
Some(BlockContent::Database(data)) => data
.cells
.get(&(row_id.to_owned(), column_id.to_owned()))
.and_then(DatabaseCellValue::as_str),
_ => None,
};
let (start, delete, insert) = utf16_splice(current.unwrap_or_default(), &text);
// Close the typing step of the document so the cell edit undoes on its own.
let _ = session.stop_capturing();
let written = session.splice_database_cell_text(
database, row_id, column_id, start, delete, &insert, now,
);
let _ = session.stop_capturing();
written
}
DatabaseCellEdit::ToggleOption(option) => session
.toggle_database_multi_select_option(database, row_id, column_id, &option, now),
DatabaseCellEdit::Value(value) => {
session.set_database_cell_value(database, row_id, column_id, value, now)
}
DatabaseCellEdit::CreateOption(value) => {
let column = match entry.snapshot.block(database).map(|node| &node.content) {
Some(BlockContent::Database(data)) => column_of(data, column_id),
_ => None,
};
let (Some(column), Ok(seed)) = (column, try_random_client_id()) else {
return false;
};
let id = format!("opt-{seed:x}");
let color =
TAG_COLOR_PALETTE[column.select_options().len() % TAG_COLOR_PALETTE.len()];
if column.column_type == "multi-select" {
session.upsert_database_select_option_and_add_multi(
database, column_id, &id, &value, color, row_id, now,
)
} else {
session.upsert_database_select_option_and_set_cell(
database,
column_id,
&id,
&value,
color,
row_id,
DatabaseCellSpec::Text(id.clone()),
now,
)
}
}
DatabaseCellEdit::UpdateOption { id, value, color } => {
session.upsert_database_select_option(database, column_id, &id, &value, &color, now)
}
DatabaseCellEdit::DeleteOption(id) => {
session.delete_database_select_option(database, column_id, &id, now)
}
};
if !matches!(written, Ok(Some(_))) {
return false;
}
let Ok(snapshot) = entry.session.read_page_snapshot() else {
return false;
};
entry.snapshot = snapshot;
entry.revision = entry.session.revision();
entry.meta.updated_at_ms = now_ms;
let delta = entry.session.encode_diff_v1(&before).ok();
let doc_id = row.doc_id.clone();
self.index_doc_links(&doc_id);
if let Some(delta) = delta {
self.enqueue_doc_update(&doc_id, delta);
}
self.touch_meta();
true
}
}
fn column_of<'a>(data: &'a DatabaseData, column_id: &str) -> Option<&'a DatabaseColumn> {
data.columns.iter().find(|column| column.id == column_id)
}
/// The UTF-16 `(start, delete, insert)` splice that turns `old` into `new`.
fn utf16_splice(old: &str, new: &str) -> (u64, u64, String) {
let old: Vec<char> = old.chars().collect();
let new: Vec<char> = new.chars().collect();
let prefix = old.iter().zip(&new).take_while(|(a, b)| a == b).count();
let suffix = old[prefix..]
.iter()
.rev()
.zip(new[prefix..].iter().rev())
.take_while(|(a, b)| a == b)
.count();
let utf16 = |chars: &[char]| chars.iter().map(|c| c.len_utf16() as u64).sum::<u64>();
(
utf16(&old[..prefix]),
utf16(&old[prefix..old.len() - suffix]),
new[prefix..new.len() - suffix].iter().collect(),
)
}
@@ -21,6 +21,7 @@ use serde::{Deserialize, Serialize};
use blocksuite_playground_doc::{
read::PageSnapshot, session::PageDocSession, try_random_client_id,
};
pub(crate) use database_backlinks::{DatabaseBacklink, DatabaseCellEdit, select_option_rgb};
pub(crate) use explorer_prefs::{
DisplayPreference, ExplorerGroupBy, ExplorerOrder, ExplorerPrefsStore,
ExplorerPropertySnapshot, ExplorerRouteScope, ExplorerViewMode, RouteExplorerState,
@@ -494,6 +495,7 @@ impl DesktopDocStore {
}
}
mod database_backlinks;
mod explorer_prefs;
mod hydration;
mod load;
@@ -185,6 +185,7 @@ impl Panel<'_> {
self.properties.custom_key("add-scroll"),
content,
self.stops[first_menu_stop..].to_vec(),
(px(220.0), px(260.0)),
self.window,
self.app,
)
@@ -714,7 +715,7 @@ fn date_month(value: &str) -> Option<i32> {
Some(year * 12 + month - 1)
}
fn icon(glyph: IconDef, color: ui::Hsla) -> ui::Svg {
pub(super) fn icon(glyph: IconDef, color: ui::Hsla) -> ui::Svg {
svg()
.data(glyph.svg.as_bytes())
.size(px(16.0))
@@ -733,7 +734,7 @@ fn close_menu(controls: &Entity<Controls>, window: &mut Window, app: &mut App) -
})
}
fn activate(
pub(super) fn activate(
button: Stateful<Div>,
stop: PropertyFocusStop,
action: impl Fn(&mut Window, &mut App) + 'static,
@@ -0,0 +1,135 @@
//! The `link` cell of a database backlink row, as `0.27.5` `LinkCell` shows it: a link that
//! opens its URL or document, and a field to edit it.
use std::rc::Rc;
use blocksuite_playground_doc::{
read::{DatabaseCellValue, DatabaseColumn},
schema::DatabaseCellSpec,
};
use ui::{
InteractiveElement, IntoElement, ParentElement, StatefulInteractiveElement, Styled, div, px,
};
use ui_tokens::icons;
use super::{Panel, PropertiesLocation, activate};
use crate::{
DesktopFlexExt,
doc_store::{DatabaseBacklink, DatabaseCellEdit},
};
impl Panel<'_> {
pub(super) fn link(
&mut self,
row: &DatabaseBacklink,
column: &DatabaseColumn,
value: &DatabaseCellValue,
key: &str,
) -> ui::AnyElement {
let palette = self.properties.palette;
let url = value.as_str().unwrap_or_default().trim().to_owned();
let edit = self
.sections
.read(self.app)
.editing
.as_ref()
.filter(|(editing, _)| self.writable && editing == key)
.map(|(_, seen)| *seen);
if let Some(seen) = edit {
let sections = self.sections.clone();
let save = self.commit(row, &column.id, |text| {
Some(DatabaseCellEdit::Value(DatabaseCellSpec::Text(
text.trim().to_owned(),
)))
});
let close = Rc::new(move |text: String, app: &mut ui::App| {
let saved = save(text, app);
sections.update(app, |state, cx| {
state.editing = None;
cx.notify();
});
saved
});
let field = self.input(&format!("{key}.value"), &url, "Empty", close, false);
let handle = field.read(self.app).focus_stop().handle;
let focused = handle.is_focused(self.window);
if seen && !focused {
// The field lost focus: leave edit mode, as the `0.27.5` field does on blur.
self.stops.pop();
self.sections
.update(self.app, |state, _| state.editing = None);
} else {
if focused {
self.sections.update(self.app, |state, _| {
if let Some((_, seen)) = state.editing.as_mut() {
*seen = true;
}
});
} else {
self.window
.defer(self.app, move |window, app| handle.focus(window, app));
}
return field.into_any_element();
}
}
let prefix = self.properties.location.snapshot_prefix();
let parent = Some(self.properties.location.parent_snapshot());
let mut cell = div()
.flex()
.items_center()
.gap(px(4.0))
.min_h(px(30.0))
.px(px(6.0));
if url.is_empty() {
cell = cell.child(div().flex_1().text_color(palette.text_muted).child("Empty"));
} else {
let label = url
.strip_prefix("https://")
.or_else(|| url.strip_prefix("http://"))
.unwrap_or(&url)
.to_owned();
let shell = self.properties.shell.clone();
let workspace = self.properties.workspace.clone();
let in_dialog = matches!(
self.properties.location,
PropertiesLocation::PageInformation(_)
);
let target = url.clone();
cell = cell.child(
div()
.id(self.properties.database_key(&format!("{key}.open")))
.snapshot(ui::snap_id!("{prefix}.database.{key}.open"), parent)
.snapshot_text(label.clone())
.flex_1()
.min_w_0()
.truncate()
.text_color(palette.accent)
.cursor_pointer()
.child(label)
.on_click(move |_, window, app| {
shell.update(app, |shell, cx| {
if shell.state.store.active_workspace().id != workspace {
return;
}
if in_dialog {
shell.close_header_overlay(window, cx);
}
shell.open_cell_link(&target, cx);
});
}),
);
}
if self.writable {
let sections = self.sections.clone();
let edit_key = key.to_owned();
let (control, stop) = self.control(&format!("{key}.edit"), Some(icons::EDIT));
cell = cell.child(activate(control.px(px(4.0)), stop, move |_, app| {
sections.update(app, |state, cx| {
state.editing = Some((edit_key.clone(), false));
cx.notify();
});
}));
}
cell.into_any_element()
}
}
@@ -0,0 +1,691 @@
//! Database rows of other documents that link to the document, as `0.27.5`
//! `DocDatabaseBacklinkInfo` shows them in the inspector and in Page information.
mod link;
mod options;
use std::{collections::BTreeSet, rc::Rc};
use blocksuite_editor::{
block_flow::civil_from_days,
database::{column_icon_name, parse_date_input_ms},
};
use blocksuite_playground_doc::{
read::{DatabaseCellValue, DatabaseColumn},
schema::DatabaseCellSpec,
};
use ui::{
App, Div, ElementId, Entity, InteractiveElement, IntoElement, ParentElement, SharedString,
Stateful, StatefulInteractiveElement, Styled, Window, canvas, div, px,
};
use ui_tokens::icons::{self, IconDef};
use super::{
Properties, PropertiesLocation, PropertyFocusStop, button,
custom_rows::{activate, icon},
menu_scroll::scroll_menu,
property_input::{Commit, PropertyInput},
};
use crate::{
DesktopFlexExt, DesktopPalette,
doc_store::{DatabaseBacklink, DatabaseCellEdit},
views_extra::journals::LocalZone,
};
const DAY_MS: i64 = 86_400_000;
#[derive(Default)]
struct Sections {
/// Keys of the expanded rows. Rows start collapsed, as in `0.27.5`.
open: BTreeSet<String>,
/// The row key and column of the open option picker.
picker: Option<(String, String)>,
/// The option whose name, color and delete controls the picker shows.
option_menu: Option<String>,
/// Bumped after an option is created, which starts the picker search field empty again.
query_epoch: u32,
/// The link cell in edit mode, and whether its field has had focus since.
editing: Option<(String, bool)>,
}
fn row_key(row: &DatabaseBacklink) -> String {
format!("{}/{}/{}", row.doc_id, row.database_id, row.row_id)
}
struct Panel<'a> {
properties: &'a Properties,
sections: Entity<Sections>,
writable: bool,
stops: &'a mut Vec<PropertyFocusStop>,
/// The local zone that `date` cells read and write calendar days in, as `dayjs` does.
zone: Rc<LocalZone>,
window: &'a mut Window,
app: &'a mut App,
}
impl Properties {
/// The database backlink sections, or `None` when no database row links to the document.
pub(super) fn database_backlinks(
&self,
writable: bool,
stops: &mut Vec<PropertyFocusStop>,
window: &mut Window,
app: &mut App,
) -> Option<Div> {
let rows = self.shell.update(app, |shell, _| {
shell.state.store.database_backlinks(&self.doc)
});
if rows.is_empty() {
return None;
}
let sections = window.use_keyed_state(self.database_key("sections"), app, |_, _| {
Sections::default()
});
let mut panel = Panel {
properties: self,
sections,
writable,
stops,
zone: Rc::new(LocalZone::system()),
window,
app,
};
let mut root = div().flex().flex_col().w_full();
for row in rows {
root = root.child(panel.section(row)).child(
div()
.my(px(8.0))
.h(px(1.0))
.w_full()
.bg(self.palette.border),
);
}
Some(root)
}
fn database_key(&self, id: &str) -> ElementId {
ElementId::NamedInteger(
SharedString::new_static("database-backlink"),
ui::hash(&(
&self.doc,
&self.workspace,
self.location.snapshot_prefix(),
id,
)),
)
}
}
impl Panel<'_> {
fn section(&mut self, row: DatabaseBacklink) -> Div {
let key = row_key(&row);
let open = self.sections.read(self.app).open.contains(&key);
let palette = self.properties.palette;
let prefix = self.properties.location.snapshot_prefix();
let parent = Some(self.properties.location.parent_snapshot());
let stop = self.focus_stop(&format!("{key}.header"));
let focused = stop.handle.is_focused(self.window);
let name = if row.database_name.is_empty() {
"unnamed".to_owned()
} else {
row.database_name.clone()
};
let sections = self.sections.clone();
let toggle_key = key.clone();
let toggle = Rc::new(move |app: &mut App| {
sections.update(app, |state, cx| {
if !state.open.remove(&toggle_key) {
state.open.insert(toggle_key.clone());
}
state.picker = None;
cx.notify();
});
});
let click = toggle.clone();
let trigger = div()
.id(&stop.handle)
.snapshot(ui::snap_id!("{prefix}.database.{key}"), parent)
.snapshot_text(format!("{name} properties"))
.snapshot_focused(focused)
.track_focus(&stop.handle)
.tab_stop(true)
.relative()
.flex()
.flex_grow(1.0)
.flex_shrink(1.0)
.min_w_0()
.items_center()
.gap(px(6.0))
.rounded(px(4.0))
.border(px(PropertyFocusStop::BORDER_WIDTH))
.border_color(ui::transparent_black())
.cursor_pointer()
.focus_visible(move |style| style.border_color(palette.text_primary))
.child(icon(icons::SQUARE, palette.text_primary))
.child(
div()
.flex()
.min_w_0()
.items_center()
.gap(px(4.0))
.overflow_hidden()
.whitespace_nowrap()
.text_size(px(14.0))
.font_weight(ui::FontWeight::MEDIUM)
.text_color(if open {
palette.text_primary
} else {
palette.text_secondary
})
.child(div().min_w(px(40.0)).truncate().child(name))
.child(div().flex_shrink(0.0).child("properties")),
)
.child(icon(
if open {
icons::TOGGLE_DOWN
} else {
icons::TOGGLE_RIGHT
},
palette.text_muted,
))
.child(stop.measure())
.on_click(move |_, _, app| click(app))
.on_key_down(move |event, window, app| {
let key = &event.keystroke;
if matches!(key.key.as_str(), "enter" | "space") && !key.modifiers.modified() {
toggle(app);
window.prevent_default();
app.stop_propagation();
}
});
let header = div()
.flex()
.items_center()
.gap(px(20.0))
.p(px(4.0))
.min_h(px(30.0))
.child(trigger)
.child(self.doc_reference(&row));
let mut section = div().flex().flex_col().gap(px(8.0)).child(header);
if open {
let mut cells = div().flex().flex_col().gap(px(4.0)).px(px(2.0));
for (column, value) in &row.cells {
cells = cells.child(self.cell(&row, column, value));
}
section = section.child(cells);
}
section
}
/// The parent document link at the end of the header, which opens the database block.
fn doc_reference(&self, row: &DatabaseBacklink) -> Stateful<Div> {
let palette = self.properties.palette;
let prefix = self.properties.location.snapshot_prefix();
let key = row_key(row);
let title = if row.doc_title.is_empty() {
"Untitled".to_owned()
} else {
row.doc_title.clone()
};
let shell = self.properties.shell.clone();
let workspace = self.properties.workspace.clone();
let in_dialog = matches!(
self.properties.location,
PropertiesLocation::PageInformation(_)
);
let (doc, database) = (row.doc_id.clone(), row.database_id.clone());
let mut reference = div()
.id(self.properties.database_key(&format!("{key}.ref")))
.snapshot(
ui::snap_id!("{prefix}.database.{key}.ref"),
Some(self.properties.location.parent_snapshot()),
)
.snapshot_text(title.clone())
.flex()
.items_center()
.gap(px(4.0))
.min_w_0()
.flex_shrink(4.0)
.text_size(px(14.0))
.text_color(palette.text_muted)
.cursor_pointer()
.child(icon(icons::PAGE, palette.text_muted))
.child(div().min_w_0().truncate().child(title))
.on_click(move |event, window, app| {
let modifiers = event.modifiers();
shell.update(app, |shell, cx| {
if shell.state.store.active_workspace().id != workspace {
return;
}
if in_dialog {
shell.close_header_overlay(window, cx);
}
shell.open_doc_block(&doc, &database, modifiers, cx);
});
});
// `0.27.5` `docRefLink` keeps the link within half of the header. It gives up its width
// before the database name does.
reference.style().max_size.width = Some(ui::relative(0.5).into());
reference
}
fn cell(
&mut self,
row: &DatabaseBacklink,
column: &DatabaseColumn,
value: &DatabaseCellValue,
) -> Div {
let palette = self.properties.palette;
let prefix = self.properties.location.snapshot_prefix();
let key = format!("{}.cell.{}", row_key(row), column.id);
let glyph = icons::icon_by_name(column_icon_name(&column.column_type))
.copied()
.unwrap_or(icons::SQUARE);
let name = div()
.flex()
.items_center()
.gap(px(6.0))
.w(ui::relative(0.4))
.min_h(px(30.0))
.px(px(6.0))
.min_w_0()
.flex_shrink(0.0)
.text_color(palette.text_muted)
.child(icon(glyph, palette.text_muted))
.child(div().min_w_0().truncate().child(column.name.clone()));
div()
.snapshot(
ui::snap_id!("{prefix}.database.{key}"),
Some(self.properties.location.parent_snapshot()),
)
.flex()
.items_start()
.gap(px(6.0))
.min_h(px(30.0))
.w_full()
.text_size(px(13.0))
.child(name)
.child(
div()
.flex_1()
.min_w_0()
.text_color(palette.text_primary)
.child(self.value(row, column, value, &key)),
)
}
fn value(
&mut self,
row: &DatabaseBacklink,
column: &DatabaseColumn,
value: &DatabaseCellValue,
key: &str,
) -> ui::AnyElement {
let palette = self.properties.palette;
match column.column_type.as_str() {
"checkbox" => {
let checked = value.as_bool().unwrap_or(false);
let glyph = if checked {
icons::CHECKBOX_CHECKED_LINEAR
} else {
icons::CHECKBOX_UNCHECKED
};
if !self.writable {
return div()
.flex()
.items_center()
.min_h(px(30.0))
.child(icon(glyph, palette.text_muted))
.into_any_element();
}
let save = self.commit(row, &column.id, |value| {
Some(DatabaseCellEdit::Value(DatabaseCellSpec::Bool(
value == "true",
)))
});
let (control, stop) = self.control(&format!("{key}.value"), Some(glyph));
activate(control, stop, move |_, app| {
save((!checked).to_string(), app);
})
.into_any_element()
}
"progress" => self.progress(row, column, value, key),
"select" | "multi-select" => self.options(row, column, value, key),
"link" => self.link(row, column, value, key),
"date" => {
let zone = self.zone.clone();
let text = value
.as_i64()
.map(|ms| format_date(ms, &zone))
.unwrap_or_default();
if !self.writable {
return plain_value(text, palette);
}
let save = self.commit(row, &column.id, move |text| parse_date(&text, &zone));
self.input(&format!("{key}.value"), &text, "YYYY-MM-DD", save, false)
.into_any_element()
}
kind => {
let (text, hint, multiline, edit): (
_,
_,
_,
fn(String) -> Option<DatabaseCellEdit>,
) = match kind {
"number" => (
value.as_f64().map(format_number).unwrap_or_default(),
"Empty",
false,
parse_number,
),
_ => (
value.as_str().unwrap_or_default().to_owned(),
"Empty",
true,
|text| Some(DatabaseCellEdit::RichText(text)),
),
};
if !self.writable {
return plain_value(text, palette);
}
let save = self.commit(row, &column.id, edit);
self.input(&format!("{key}.value"), &text, hint, save, multiline)
.into_any_element()
}
}
}
fn progress(
&mut self,
row: &DatabaseBacklink,
column: &DatabaseColumn,
value: &DatabaseCellValue,
key: &str,
) -> ui::AnyElement {
let palette = self.properties.palette;
let percent = value.as_i64().unwrap_or(0).clamp(0, 100);
let bounds = Rc::new(std::cell::Cell::new(None));
let measure = {
let bounds = bounds.clone();
canvas(move |frame, _, _| bounds.set(Some(frame)), |_, (), _, _| {})
.absolute()
.inset_0()
};
let track = div()
.relative()
.flex_1()
.h(px(10.0))
.rounded(px(5.0))
.bg(palette.bg_pill)
.child(
div()
.h_full()
.w(ui::relative(percent as f32 / 100.0))
.rounded(px(5.0))
.bg(palette.accent),
)
.child(measure);
let mut bar = div()
.id(self.properties.database_key(&format!("{key}.progress")))
.snapshot(
ui::snap_id!(
"{}.database.{key}.progress",
self.properties.location.snapshot_prefix()
),
Some(self.properties.location.parent_snapshot()),
)
.snapshot_text(format!("{percent}%"))
.flex()
.items_center()
.gap(px(8.0))
.min_h(px(30.0))
.px(px(6.0))
.child(track)
.child(
div()
.w(px(36.0))
.flex_shrink(0.0)
.text_color(palette.text_secondary)
.child(format!("{percent}%")),
);
if self.writable {
let save = self.commit(row, &column.id, |text| {
text.parse::<i64>()
.ok()
.map(|value| DatabaseCellEdit::Value(DatabaseCellSpec::Integer(value)))
});
bar = bar.cursor_pointer().on_click(move |event, _, app| {
let Some(frame) = bounds.get() else {
return;
};
let width = f32::from(frame.size.width);
if width <= 0.0 {
return;
}
let x = f32::from(event.position().x - frame.origin.x);
let next = ((x / width) * 100.0).round().clamp(0.0, 100.0) as i64;
if next != percent {
save(next.to_string(), app);
}
});
}
bar.into_any_element()
}
/// A writer that applies one edit to the row's cell in its document.
fn write(
&self,
row: &DatabaseBacklink,
column: &str,
) -> impl Fn(DatabaseCellEdit, &mut App) -> bool + use<> {
let shell = self.properties.shell.clone();
let workspace = self.properties.workspace.clone();
let (row, column) = (row.clone(), column.to_owned());
move |edit, app| {
shell.update(app, |shell, cx| {
if shell.state.store.active_workspace().id != workspace {
return false;
}
shell.sync_editors(cx);
let now = shell.state.logical_clock_ms;
if !shell
.state
.store
.edit_database_backlink_cell(&row, &column, edit, now)
{
return false;
}
shell.sync_editors(cx);
shell.flush_persistence();
cx.notify();
true
})
}
}
fn commit(
&self,
row: &DatabaseBacklink,
column: &str,
parse: impl Fn(String) -> Option<DatabaseCellEdit> + 'static,
) -> Commit {
let write = self.write(row, column);
Rc::new(move |text: String, app: &mut App| parse(text).is_some_and(|edit| write(edit, app)))
}
fn input(
&mut self,
id: &str,
text: &str,
hint: &'static str,
commit: Commit,
multiline: bool,
) -> Entity<PropertyInput> {
let snapshot = format!(
"{}.database.{id}",
self.properties.location.snapshot_prefix()
);
let palette = self.properties.palette;
let field =
self.window
.use_keyed_state(self.properties.database_key(id), self.app, |_, cx| {
PropertyInput::new(
text.to_owned(),
hint,
snapshot,
palette,
Some(commit),
multiline,
cx,
)
});
field.update(self.app, |field, _| field.sync_source(text, self.window));
self.stops.push(field.read(self.app).focus_stop());
field
}
fn focus_stop(&mut self, id: &str) -> PropertyFocusStop {
let stop = self
.window
.use_keyed_state(self.properties.database_key(id), self.app, |_, cx| {
PropertyFocusStop::new(cx)
})
.read(self.app)
.clone();
self.stops.push(stop.clone());
stop
}
fn control(&mut self, id: &str, glyph: Option<IconDef>) -> (Stateful<Div>, PropertyFocusStop) {
let stop = self.focus_stop(id);
let focused = stop.handle.is_focused(self.window);
let palette = self.properties.palette;
let snapshot = ui::snap_id!(
"{}.database.{id}",
self.properties.location.snapshot_prefix()
);
let mut control = button(self.properties.database_key(id), "", palette, true)
.snapshot(snapshot, None)
.snapshot_focused(focused)
.track_focus(&stop.handle)
.relative()
.border_1()
.border_color(if focused {
palette.accent
} else {
ui::transparent_black()
})
.gap(px(6.0))
.child(stop.measure())
.children(glyph.map(|glyph| icon(glyph, palette.text_muted)));
control.style().justify_content = Some(ui::JustifyContent::FlexStart);
(control, stop)
}
}
fn format_number(value: f64) -> String {
if value.fract() == 0.0 && value.abs() < 1e15 {
format!("{}", value as i64)
} else {
value.to_string()
}
}
/// `Number(text)` of `0.27.5` `NumberCell`: blank text is zero, other text that is no
/// number writes nothing.
fn parse_number(text: String) -> Option<DatabaseCellEdit> {
let trimmed = text.trim();
let value = if trimmed.is_empty() {
0.0
} else {
trimmed
.parse::<f64>()
.ok()
.filter(|value| value.is_finite())?
};
Some(DatabaseCellEdit::Value(DatabaseCellSpec::Number(value)))
}
/// The local calendar day of a `date` cell value, as `dayjs(value).format('YYYY-MM-DD')`.
fn format_date(ms: i64, zone: &LocalZone) -> String {
let local = ms + i64::from(zone.offset_minutes(ms)) * 60_000;
let (year, month, day) = civil_from_days(local.div_euclid(DAY_MS));
format!("{year:04}-{month:02}-{day:02}")
}
/// A `YYYY-MM-DD` day as the Unix milliseconds of its local midnight, or a cleared cell for
/// blank text. Dates that do not exist, such as `2026-02-31`, write nothing.
fn parse_date(text: &str, zone: &LocalZone) -> Option<DatabaseCellEdit> {
if text.trim().is_empty() {
return Some(DatabaseCellEdit::Value(DatabaseCellSpec::Null));
}
parse_date_input_ms(text, &|ms| zone.offset_minutes(ms))
.map(|ms| DatabaseCellEdit::Value(DatabaseCellSpec::Integer(ms)))
}
/// A read-only cell value, or a muted `Empty`.
fn plain_value(text: String, palette: DesktopPalette) -> ui::AnyElement {
let empty = text.is_empty();
div()
.min_h(px(30.0))
.py(px(4.0))
.line_height(px(22.0))
.text_color(if empty {
palette.text_muted
} else {
palette.text_primary
})
.child(if empty { "Empty".to_owned() } else { text })
.into_any_element()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cell_text_parsers_follow_number_cells_and_local_date_cells() {
let number = |value: f64| Some(DatabaseCellEdit::Value(DatabaseCellSpec::Number(value)));
for (text, expected) in [
("", number(0.0)),
(" 12.5 ", number(12.5)),
("-3", number(-3.0)),
("abc", None),
("inf", None),
] {
assert_eq!(parse_number(text.into()), expected, "{text:?}");
}
for (value, text) in [(3.0, "3"), (0.25, "0.25"), (-12.0, "-12")] {
assert_eq!(format_number(value), text);
}
// 2026-12-04 00:00 UTC.
const UTC_MIDNIGHT: i64 = 1_796_342_400_000;
let ms = |value: i64| Some(DatabaseCellEdit::Value(DatabaseCellSpec::Integer(value)));
for (tz, local_midnight, utc_midnight_day) in [
("UTC", UTC_MIDNIGHT, "2026-12-04"),
("JST-9", UTC_MIDNIGHT - 9 * 3_600_000, "2026-12-04"),
(
"PST8PDT,M3.2.0,M11.1.0",
UTC_MIDNIGHT + 8 * 3_600_000,
"2026-12-03",
),
] {
let zone = LocalZone::from_tz(Some(tz));
assert_eq!(parse_date("2026-12-04", &zone), ms(local_midnight), "{tz}");
assert_eq!(format_date(local_midnight, &zone), "2026-12-04", "{tz}");
assert_eq!(
format_date(local_midnight + DAY_MS - 1, &zone),
"2026-12-04",
"{tz}"
);
assert_eq!(format_date(UTC_MIDNIGHT, &zone), utc_midnight_day, "{tz}");
for text in ["2026-02-31", "2026-13-01", "tomorrow"] {
assert_eq!(parse_date(text, &zone), None, "{tz}: {text}");
}
assert_eq!(
parse_date(" ", &zone),
Some(DatabaseCellEdit::Value(DatabaseCellSpec::Null))
);
}
}
}
@@ -0,0 +1,446 @@
//! The `select` and `multi-select` cells of a database backlink row and their option picker.
use std::rc::Rc;
use blocksuite_editor::database::TAG_COLOR_PALETTE;
use blocksuite_playground_doc::{
read::{DatabaseCellValue, DatabaseColumn, DatabaseSelectOption},
schema::DatabaseCellSpec,
};
use ui::{
Anchor, App, Div, InteractiveElement, IntoElement, ParentElement, StatefulInteractiveElement,
Styled, anchored, deferred, div, point, px,
};
use ui_tokens::icons;
use super::{Panel, PropertyFocusStop, activate, icon, row_key, scroll_menu};
use crate::{
DesktopFlexExt, DesktopPalette,
doc_store::{DatabaseBacklink, DatabaseCellEdit, select_option_rgb},
};
impl Panel<'_> {
pub(super) fn options(
&mut self,
row: &DatabaseBacklink,
column: &DatabaseColumn,
value: &DatabaseCellValue,
key: &str,
) -> ui::AnyElement {
let palette = self.properties.palette;
let theme = self.properties.shell.read(self.app).state.theme;
let options = column.select_options();
let selected = value.as_string_list();
let mut chips = div()
.flex()
.flex_wrap()
.items_center()
.gap(px(4.0))
.min_h(px(30.0))
.px(px(6.0));
let mut any = false;
for option in options
.iter()
.filter(|option| selected.contains(&option.id))
{
any = true;
chips = chips.child(option_chip(
&option.value,
select_option_rgb(&option.color, theme),
palette,
));
}
if !any {
chips = chips.child(div().text_color(palette.text_muted).child("Empty"));
}
if !self.writable {
return chips.into_any_element();
}
let row_key = row_key(row);
let open = self.sections.read(self.app).picker.as_ref()
== Some(&(row_key.clone(), column.id.clone()));
let stop = self.focus_stop(&format!("{key}.value"));
let focused = stop.handle.is_focused(self.window);
let sections = self.sections.clone();
let picker_key = (row_key, column.id.clone());
let toggle = Rc::new(move |app: &mut App| {
sections.update(app, |state, cx| {
state.picker = if state.picker.as_ref() == Some(&picker_key) {
None
} else {
Some(picker_key.clone())
};
cx.notify();
});
});
let click = toggle.clone();
let close = self.sections.clone();
let trigger = chips
.id(&stop.handle)
.snapshot(
ui::snap_id!(
"{}.database.{key}.value",
self.properties.location.snapshot_prefix()
),
Some(self.properties.location.parent_snapshot()),
)
.snapshot_focused(focused)
.track_focus(&stop.handle)
.tab_stop(true)
.relative()
.rounded(px(4.0))
.border(px(PropertyFocusStop::BORDER_WIDTH))
.border_color(if focused {
palette.accent
} else {
ui::transparent_black()
})
.cursor_pointer()
.hover(move |style| style.bg(palette.hover_overlay))
.child(stop.measure())
.on_click(move |_, _, app| click(app))
.on_key_down(move |event, window, app| {
if matches!(event.keystroke.key.as_str(), "enter" | "space") {
toggle(app);
} else if open && event.keystroke.key == "escape" {
// An open picker takes `Escape` before the dialog around it.
close.update(app, |state, cx| {
state.picker = None;
cx.notify();
});
} else {
return;
}
window.prevent_default();
app.stop_propagation();
});
let mut cell = div().relative().child(trigger);
if let Some(bounds) = open.then(|| stop.bounds.get()).flatten() {
cell = cell.child(self.picker(row, column, &options, &selected, key, bounds, stop));
}
cell.into_any_element()
}
#[allow(clippy::too_many_arguments)]
fn picker(
&mut self,
row: &DatabaseBacklink,
column: &DatabaseColumn,
options: &[DatabaseSelectOption],
selected: &[String],
key: &str,
bounds: ui::Bounds<ui::Pixels>,
anchor: PropertyFocusStop,
) -> impl IntoElement + use<> {
let palette = self.properties.palette;
let theme = self.properties.shell.read(self.app).state.theme;
let multiple = column.column_type == "multi-select";
let prefix = self.properties.location.snapshot_prefix();
let mut menu = div()
.w(px(220.0))
.occlude()
.snapshot(ui::snap_id!("{prefix}.database.{key}.picker"), None)
.flex()
.flex_col()
.gap(px(2.0))
.p(px(4.0))
.rounded(px(8.0))
.border_1()
.border_color(palette.border)
.bg(palette.bg_elevated)
.text_size(px(13.0))
.text_color(palette.text_primary);
let epoch = self.sections.read(self.app).query_epoch;
let search = self.input(
&format!("{key}.search.{epoch}"),
"",
"Select an option or create one",
Rc::new(|_, _| false),
false,
);
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 list = div().flex().flex_col().gap(px(2.0));
let needle = query.to_lowercase();
let shown: Vec<_> = options
.iter()
.filter(|option| option.value.to_lowercase().contains(&needle))
.collect();
if !query.is_empty()
&& !options
.iter()
.any(|option| option.value.to_lowercase() == needle)
{
let save = self.write(row, &column.id);
let sections = self.sections.clone();
let (control, stop) = self.control(&format!("{key}.create"), Some(icons::PLUS));
let control = control
.child(div().text_color(palette.text_muted).child("Create"))
.child(option_chip(
&query,
select_option_rgb(
TAG_COLOR_PALETTE[options.len() % TAG_COLOR_PALETTE.len()],
theme,
),
palette,
));
let value = query.clone();
list = list.child(activate(control, stop, move |_, app| {
if save(DatabaseCellEdit::CreateOption(value.clone()), app) {
sections.update(app, |state, cx| {
state.query_epoch += 1;
cx.notify();
});
}
}));
} else if shown.is_empty() {
list = list.child(
div()
.px(px(8.0))
.py(px(4.0))
.text_color(palette.text_muted)
.child("No options"),
);
}
let option_menu = self.sections.read(self.app).option_menu.clone();
for option in shown {
let checked = selected.contains(&option.id);
let edit = if multiple {
DatabaseCellEdit::ToggleOption(option.id.clone())
} else {
DatabaseCellEdit::Value(if checked {
DatabaseCellSpec::Null
} else {
DatabaseCellSpec::Text(option.id.clone())
})
};
let save = self.write(row, &column.id);
let sections = self.sections.clone();
let (control, stop) = self.control(&format!("{key}.option.{}", option.id), None);
let control = control
.child(option_chip(
&option.value,
select_option_rgb(&option.color, theme),
palette,
))
.child(div().flex_1())
.children(checked.then(|| icon(icons::DONE, palette.text_primary)));
let more = {
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| {
sections.update(app, |state, cx| {
state.option_menu = if state.option_menu.as_deref() == Some(&id) {
None
} else {
Some(id.clone())
};
cx.notify();
});
})
};
let anchor = anchor.clone();
let pick = activate(control.flex_1().min_w_0(), stop, move |window, app| {
save(edit.clone(), app);
if !multiple {
sections.update(app, |state, cx| {
state.picker = None;
cx.notify();
});
anchor.handle.focus(window, app);
}
});
list = list.child(
div()
.flex()
.items_center()
.gap(px(2.0))
.child(pick)
.child(more),
);
if option_menu.as_deref() == Some(option.id.as_str()) {
list = list.child(self.option_editor(row, column, option, key));
}
}
// `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();
menu = menu.child(scroll_menu(
self.properties.database_key(&format!("{key}.options")),
list,
rows.clone(),
(px(212.0), px(200.0)),
self.window,
self.app,
));
let sections = self.sections.clone();
let escape = self.sections.clone();
let anchor_bounds = anchor.bounds.clone();
deferred(
anchored()
.attach(bounds, Anchor::BottomLeft)
.offset(point(px(0.0), px(4.0)))
.child(
menu.on_mouse_down_out(move |event, _, app| {
if !anchor_bounds
.get()
.is_some_and(|bounds| bounds.contains(&event.position))
{
sections.update(app, |state, cx| {
state.picker = None;
cx.notify();
});
}
})
.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,
};
if let Some(row) = row {
row.handle.focus(window, app);
window.prevent_default();
app.stop_propagation();
}
})
.on_key_down(move |event, window, app| {
if event.keystroke.key == "escape" {
escape.update(app, |state, cx| {
state.picker = None;
cx.notify();
});
anchor.handle.focus(window, app);
window.prevent_default();
app.stop_propagation();
}
}),
),
)
.priority(2)
}
/// Rename, recolor or delete one option, as the option menu of `0.27.5` `TagsInlineEditor`.
fn option_editor(
&mut self,
row: &DatabaseBacklink,
column: &DatabaseColumn,
option: &DatabaseSelectOption,
key: &str,
) -> Div {
let palette = self.properties.palette;
let theme = self.properties.shell.read(self.app).state.theme;
let base = format!("{key}.option.{}", option.id);
let rename = {
let write = self.write(row, &column.id);
let (id, color) = (option.id.clone(), option.color.clone());
Rc::new(move |value: String, app: &mut App| {
let value = value.trim().to_owned();
!value.is_empty()
&& write(
DatabaseCellEdit::UpdateOption {
id: id.clone(),
value,
color: color.clone(),
},
app,
)
})
};
let name = self.input(
&format!("{base}.name"),
&option.value,
"Option name",
rename,
false,
);
let mut swatches = div().flex().flex_wrap().gap(px(2.0));
for color in TAG_COLOR_PALETTE {
let write = self.write(row, &column.id);
let (id, value) = (option.id.clone(), option.value.clone());
let name = color
.trim_start_matches("var(--affine-tag-")
.trim_end_matches(')');
let (control, stop) = self.control(&format!("{base}.color.{name}"), None);
let selected = option.color == color;
let control = control.px(px(4.0)).child(
div()
.size(px(16.0))
.rounded(px(8.0))
.border_1()
.border_color(if selected {
palette.text_primary
} else {
ui::transparent_black()
})
.bg(ui::rgb(select_option_rgb(color, theme) & 0x00ff_ffff)),
);
swatches = swatches.child(activate(control, stop, move |_, app| {
write(
DatabaseCellEdit::UpdateOption {
id: id.clone(),
value: value.clone(),
color: color.to_owned(),
},
app,
);
}));
}
let delete = {
let write = self.write(row, &column.id);
let sections = self.sections.clone();
let id = option.id.clone();
let (control, stop) = self.control(&format!("{base}.delete"), Some(icons::DELETE));
activate(
control
.text_color(palette.danger)
.child(div().child("Delete")),
stop,
move |_, app| {
if write(DatabaseCellEdit::DeleteOption(id.clone()), app) {
sections.update(app, |state, cx| {
state.option_menu = None;
cx.notify();
});
}
},
)
};
div()
.flex()
.flex_col()
.gap(px(4.0))
.p(px(4.0))
.rounded(px(6.0))
.bg(palette.bg_hover)
.child(name)
.child(swatches)
.child(delete)
}
}
/// A `select` option as the `0.27.5` inline tag draws it: the option color fills the chip.
fn option_chip(label: &str, rgb: u32, palette: DesktopPalette) -> Div {
div()
.flex()
.items_center()
.min_w_0()
.px(px(8.0))
.py(px(2.0))
.rounded(px(4.0))
.bg(ui::rgb(rgb & 0x00ff_ffff))
.text_size(px(12.0))
.text_color(palette.text_primary)
.child(div().truncate().child(label.to_owned()))
}
@@ -15,10 +15,13 @@ struct MenuScroll {
focused: Rc<Cell<Option<FocusHandle>>>,
}
/// `content` in a viewport `width` wide and at most `max_height` tall (less in a short window)
/// that the wheel scrolls and that keeps the focused stop in view.
pub(super) fn scroll_menu(
id: ElementId,
content: Div,
stops: Vec<PropertyFocusStop>,
(width, max_height): (Pixels, Pixels),
window: &mut Window,
app: &mut App,
) -> Div {
@@ -46,7 +49,7 @@ pub(super) fn scroll_menu(
.set(ScrollAxis::new(axis.offset + f32::from(delta), axis.max));
}
}
let limit = (window.viewport_size().height - px(16.0)).clamp(px(0.0), px(260.0));
let limit = (window.viewport_size().height - px(16.0)).clamp(px(0.0), max_height);
let axis = region.axis.clone();
let measured = region.clone();
let offset = region.axis.get().offset;
@@ -55,7 +58,7 @@ pub(super) fn scroll_menu(
viewport
.flex()
.flex_col()
.w(px(220.0))
.w(width)
.overflow_hidden()
.on_key_down(move |event, window, app| {
let direction = match event.keystroke.key.as_str() {
@@ -1,4 +1,5 @@
mod custom_rows;
mod database_backlinks;
mod focus;
mod input_line;
mod links;
@@ -285,6 +286,7 @@ impl RenderOnce for Properties {
});
let (ordered, custom, mut stops) =
self.custom_rows(&custom_rows, writable, &builtins, tag_stop, window, app);
let database_backlinks = self.database_backlinks(writable, &mut stops, window, app);
let state_ref = self.shell.read(app);
let theme = state_ref.state.theme;
let store = &state_ref.state.store;
@@ -476,6 +478,7 @@ impl RenderOnce for Properties {
}
properties = properties
.children(database_backlinks)
.children(self.outgoing_section(outgoing, &scroll, window, app))
.children(self.backlinks_section(
&backlinks,
@@ -0,0 +1,152 @@
//! The option picker of database backlink `select` cells: closing with Page information,
//! keyboard picks after a search, and scrolling through many options.
use blocksuite_playground_doc::{read::DatabaseCellValue, schema::DatabaseCellSpec};
use ui_tokens::ThemeMode;
use super::{
Shell,
database_backlinks::{DATABASE, PARENT, ROW, TARGET, backlink_shell, backlink_state, cell},
};
use crate::doc_store::DatabaseCellEdit;
#[test]
fn database_backlink_option_picker_closes_with_page_information_by_pointer_and_escape() {
let key = format!("{PARENT}/{DATABASE}/{ROW}");
let prefix = "desktop.header.info";
let value = format!("{prefix}.database.{key}.cell.col-status.value");
let picker = format!("{prefix}.database.{key}.cell.col-status.picker");
for escape in [false, true] {
let (_, app) = backlink_shell(true);
app.click(&format!("{prefix}.database.{key}"));
app.click(&value);
assert!(app.contains(&picker), "escape {escape}");
if escape {
app.key("escape");
assert!(!app.contains(&picker), "Escape closes the picker first");
assert!(app.contains("desktop.header.dialog"));
app.key("escape");
} else {
// The backdrop outside the dialog card.
app.window
.simulate_click(ui::point(ui::px(8.0), ui::px(792.0)));
app.window.request_frame();
}
assert!(!app.contains("desktop.header.dialog"), "escape {escape}");
assert!(!app.contains(&picker), "escape {escape}");
app.open_page_information();
app.click(&format!("{prefix}.database.{key}"));
assert!(
!app.contains(&picker),
"escape {escape}: the dialog opens again without the picker"
);
}
}
#[test]
fn database_backlink_option_picker_picks_a_filtered_option_with_down_and_enter() {
for dialog in [false, true] {
let (prefix, app) = backlink_shell(dialog);
let key = format!("{PARENT}/{DATABASE}/{ROW}");
let cell_id = |part: &str| format!("{prefix}.database.{key}.cell.col-status.{part}");
app.click(&format!("{prefix}.database.{key}"));
app.click(&cell_id("value"));
app.click(&cell_id("search.0"));
app.input(|input| input.replace_text_in_range(None, "Done"));
assert!(app.contains(&cell_id("option.opt-done")), "{prefix}");
assert!(!app.contains(&cell_id("option.opt-todo")), "{prefix}");
app.key("down");
app.key("enter");
app.update(|shell, _, _| {
assert_eq!(
cell(&shell.state.store, "col-status"),
DatabaseCellValue::Text("opt-done".into()),
"{prefix}"
);
});
assert!(!app.contains(&cell_id("picker")), "{prefix}");
if dialog {
assert!(app.contains("desktop.header.dialog"));
}
}
}
#[test]
fn database_backlink_option_picker_scrolls_to_and_picks_the_last_of_many_options() {
let key = format!("{PARENT}/{DATABASE}/{ROW}");
let prefix = "desktop.header.info";
for (width, height) in [(1280_u32, 800_u32), (640, 400)] {
let mut state = backlink_state(ThemeMode::Light);
let row = state.store.database_backlinks(TARGET).remove(0);
for index in 3..=42 {
assert!(state.store.edit_database_backlink_cell(
&row,
"col-status",
DatabaseCellEdit::CreateOption(format!("Option {index:02}")),
1_000 * index,
));
}
let last = cell(&state.store, "col-status").as_string_list().remove(0);
assert!(state.store.edit_database_backlink_cell(
&row,
"col-status",
DatabaseCellEdit::Value(DatabaseCellSpec::Text("opt-todo".into())),
100_000,
));
// Page information only, so that the 640 px window keeps its top bar menu.
state.open_doc_in_active_pane(TARGET);
let app = Shell::with_size(width, height, state);
app.open_page_information();
let header = format!("{prefix}.database.{key}");
reveal(&app, &header, width, height);
app.click(&header);
let value = format!("{prefix}.database.{key}.cell.col-status.value");
reveal(&app, &value, width, height);
app.click(&value);
let picker = app.bounds(&format!("{prefix}.database.{key}.cell.col-status.picker"));
let bottom = picker.y + picker.height;
assert!(
picker.y >= 0.0 && bottom <= height as f32,
"{width}x{height}: {picker:?}"
);
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.update(|shell, _, _| {
assert_eq!(
cell(&shell.state.store, "col-status"),
DatabaseCellValue::Text(last.clone()),
"{width}x{height}"
);
});
}
}
/// Scrolls the Page information dialog until `id` lies inside its clip.
fn reveal(app: &Shell, id: &str, width: u32, height: u32) {
for _ in 0..24 {
let shown = app.update(|_, window, _| {
window.frame_snapshot().elements.get(id).is_some_and(|row| {
row.bounds.y >= row.content_mask.y - 0.5
&& row.bounds.bottom() <= row.content_mask.bottom() + 0.5
})
});
if shown {
return;
}
app.scroll(width as f32 / 2.0, height as f32 / 2.0, -60.0);
}
panic!("{id} stays outside the dialog at {width}x{height}");
}
@@ -0,0 +1,736 @@
use std::collections::BTreeMap;
use affine_store::workspace_db::WorkspaceDbTableName;
use blocksuite_editor::database::parse_date_input_ms;
use blocksuite_playground_doc::{
read::{BlockContent, DatabaseCellValue},
schema::{
BlockSpec, DatabaseCellSpec, DatabaseColumnSpec, DatabaseSpec, DatabaseViewSpec,
ParagraphType,
},
};
use serde_json::json;
use ui::{Modifiers, MouseButton};
use ui_tokens::ThemeMode;
use y_octo::{AHashMap, Any, TextDeltaOp, TextInsert, TypePath, TypeTarget};
use super::Shell;
use crate::{
DesktopAppState, DesktopRoute, DocInspectorTab, DocViewMode,
doc_store::{DatabaseCellEdit, DesktopDocStore},
views_extra::journals::LocalZone,
};
pub(super) const TARGET: &str = "doc-sync";
pub(super) const PARENT: &str = "doc-arch";
pub(super) const DATABASE: &str = "db-roadmap";
pub(super) const ROW: &str = "row-sync";
/// 2026-12-04 00:00 UTC.
const DUE_MS: f64 = 1_796_342_400_000.0;
fn column(id: &str, kind: &str, name: &str, data: serde_json::Value) -> DatabaseColumnSpec {
DatabaseColumnSpec {
id: id.into(),
column_type: kind.into(),
name: name.into(),
data,
}
}
fn roadmap_columns() -> Vec<DatabaseColumnSpec> {
let options = |items: &[(&str, &str, &str)]| json!({"options": items.iter().map(|(id, value, color)| json!({"id": id, "value": value, "color": color})).collect::<Vec<_>>()});
vec![
column("col-title", "title", "Title", json!({})),
column(
"col-status",
"select",
"Status",
options(&[
("opt-todo", "Todo", "var(--affine-tag-blue)"),
("opt-done", "Done", "var(--affine-tag-green)"),
]),
),
column("col-phase", "select", "Phase", options(&[])),
column(
"col-tags",
"multi-select",
"Tags",
options(&[
("opt-rust", "Rust", "var(--affine-tag-purple)"),
("opt-ui", "UI", "var(--affine-tag-orange)"),
]),
),
column("col-estimate", "number", "Estimate", json!({})),
column("col-done", "checkbox", "Done", json!({})),
column("col-due", "date", "Due", json!({})),
column("col-notes", "rich-text", "Notes", json!({})),
column("col-url", "link", "URL", json!({})),
column("col-progress", "progress", "Progress", json!({})),
column("col-cover", "image", "Cover", json!({})),
]
}
/// Adds the `Roadmap` database to `doc`: its row `ROW` links to `TARGET` and holds a value in
/// each column, and its row `<db>-plain` has plain text only.
fn add_database(store: &mut DesktopDocStore, doc: &str, db: &str, title: &str) {
let cells = BTreeMap::from([
(
"col-status".into(),
DatabaseCellSpec::Text("opt-todo".into()),
),
(
"col-tags".into(),
DatabaseCellSpec::MultiSelect(vec!["opt-rust".into()]),
),
("col-estimate".into(), DatabaseCellSpec::Number(3.0)),
("col-done".into(), DatabaseCellSpec::Bool(false)),
("col-due".into(), DatabaseCellSpec::Number(DUE_MS)),
(
"col-notes".into(),
DatabaseCellSpec::RichText("Ship the panel".into()),
),
(
"col-url".into(),
DatabaseCellSpec::Text("https://affine.pro".into()),
),
("col-progress".into(), DatabaseCellSpec::Integer(40)),
]);
let linked = if db == DATABASE {
ROW.to_owned()
} else {
format!("{db}-linked")
};
add_database_rows(
store,
doc,
db,
title,
roadmap_columns(),
BTreeMap::from([(linked.clone(), cells)]),
(TARGET, &[linked]),
);
}
/// Adds a database to `doc` whose `linked` rows reference `page_id`, followed by one plain row.
fn add_database_rows(
store: &mut DesktopDocStore,
doc: &str,
db: &str,
title: &str,
columns: Vec<DatabaseColumnSpec>,
cells: BTreeMap<String, BTreeMap<String, DatabaseCellSpec>>,
(page_id, linked): (&str, &[String]),
) {
let entry = store.docs.get_mut(doc).unwrap();
let note = entry.note_id.clone();
let mut reference = AHashMap::default();
reference.insert("type".to_owned(), Any::String("LinkedPage".into()));
reference.insert("pageId".to_owned(), Any::String(page_id.into()));
let format = BTreeMap::from([("reference".to_owned(), Any::Object(Box::new(reference)))]);
let (db, title, plain) = (db.to_owned(), title.to_owned(), format!("{db}-plain"));
let linked = linked.to_vec();
entry
.session
.structural_edit(100, move |page| {
page.add_block(
&db,
BlockSpec::Database(DatabaseSpec {
title: title.clone(),
columns: columns.clone(),
views: vec![DatabaseViewSpec {
id: "view-table".into(),
name: "Table".into(),
mode: "table".into(),
raw: json!({"columns": []}),
}],
cells: cells.clone(),
}),
Some(&note),
None,
101,
)?;
for row in linked.iter().chain([&plain]) {
page.add_block(
row,
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: String::new(),
},
Some(&db),
None,
102,
)?;
let (text, format) = if row == &plain {
("Plain row", None)
} else {
(" ", Some(format.clone()))
};
page.inner_mut().text_apply_delta(
&TypeTarget::Path(TypePath::root("blocks").key(row).key("prop:text")),
&[TextDeltaOp::Insert {
insert: TextInsert::Text(text.into()),
format,
}],
)?;
}
Ok(())
})
.unwrap();
entry.snapshot = entry.session.read_page_snapshot().unwrap();
entry.revision = entry.session.revision();
store.index_doc_links(doc);
}
pub(super) fn backlink_state(theme: ThemeMode) -> DesktopAppState {
let mut state = DesktopAppState::seed_showcase(theme, "2026-12-02");
add_database(&mut state.store, PARENT, DATABASE, "Roadmap");
let trashed = state.store.trashed_docs()[0].id.clone();
add_database(&mut state.store, &trashed, "db-trashed", "Archive");
state
}
pub(super) fn cell(store: &DesktopDocStore, column: &str) -> DatabaseCellValue {
let snapshot = &store.get_doc(PARENT).unwrap().snapshot;
let Some(BlockContent::Database(data)) = snapshot.block(DATABASE).map(|node| &node.content)
else {
panic!("missing database");
};
data.cells
.get(&(ROW.to_owned(), column.to_owned()))
.cloned()
.unwrap_or(DatabaseCellValue::Null)
}
#[test]
fn database_backlinks_list_only_linked_rows_of_live_documents_with_sorted_cells() {
let mut state = backlink_state(ThemeMode::Light);
let store = &mut state.store;
let rows = store.database_backlinks(TARGET);
assert_eq!(rows.len(), 1, "{rows:?}");
let row = &rows[0];
assert_eq!(
(
row.doc_id.as_str(),
row.database_id.as_str(),
row.row_id.as_str()
),
(PARENT, DATABASE, ROW)
);
assert_eq!(row.database_name, "Roadmap");
let title = store.get_doc(PARENT).unwrap().meta.title.clone();
assert_eq!(row.doc_title, title);
let names: Vec<_> = row
.cells
.iter()
.map(|(column, _)| column.name.as_str())
.collect();
assert_eq!(
names,
[
"Done", "Due", "Estimate", "Notes", "Phase", "Progress", "Status", "Tags", "URL"
]
);
for doc in [PARENT, "doc-board"] {
assert!(store.database_backlinks(doc).is_empty(), "{doc}");
}
}
#[test]
fn database_backlinks_match_references_with_a_query_or_fragment_after_the_document() {
for suffix in ["?blockIds=p-focus", "#p-focus"] {
let mut state = backlink_state(ThemeMode::Light);
add_database_rows(
&mut state.store,
PARENT,
"db-anchor",
"Anchors",
roadmap_columns(),
BTreeMap::new(),
(&format!("{TARGET}{suffix}"), &["anchor-row".into()]),
);
let rows: Vec<_> = (state.store.database_backlinks(TARGET).into_iter())
.map(|row| format!("{}/{}/{}", row.doc_id, row.database_id, row.row_id))
.collect();
assert_eq!(
rows,
[
format!("{PARENT}/db-anchor/anchor-row"),
format!("{PARENT}/{DATABASE}/{ROW}"),
],
"{suffix}"
);
state.open_doc_in_active_pane(TARGET);
state.inspector_tab = Some(DocInspectorTab::Info);
let app = Shell::with_state(1280, state);
for row in &rows {
assert!(
app.contains(&format!("desktop.inspector.database.{row}")),
"{suffix} {row}"
);
}
}
}
#[test]
fn database_backlinks_sort_before_the_limit_and_skip_templates_and_rows_without_columns() {
let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02");
let store = &mut state.store;
let many: Vec<String> = (0..100).map(|i| format!("zeta-{i:03}")).collect();
add_database_rows(
store,
PARENT,
"db-zeta",
"Zeta",
roadmap_columns(),
BTreeMap::new(),
(TARGET, &many),
);
add_database_rows(
store,
"doc-board",
"db-alpha",
"Alpha",
roadmap_columns(),
BTreeMap::new(),
(TARGET, &["alpha-0".into()]),
);
add_database_rows(
store,
"doc-journal-today",
"db-bare",
"Bare",
vec![
column("col-title", "title", "Title", json!({})),
column("col-cover", "image", "Cover", json!({})),
],
BTreeMap::new(),
(TARGET, &["bare-0".into()]),
);
let rows = store.database_backlinks(TARGET);
assert_eq!(rows.len(), 100);
assert_eq!(rows[0].database_name, "Alpha");
assert_eq!(rows[1].row_id, "zeta-000");
assert!(rows.iter().all(|row| row.database_name != "Bare"));
let db = store.directory.db_mut();
let template = [("isTemplate", Some(json!(true)))];
if db
.patch_db_row_fields(WorkspaceDbTableName::DocProperties, "doc-board", &template)
.unwrap()
.is_none()
{
db.upsert_db_row(
WorkspaceDbTableName::DocProperties,
&json!({"id": "doc-board", "isTemplate": true}),
)
.unwrap();
}
let rows = store.database_backlinks(TARGET);
assert_eq!(rows.len(), 100);
assert!(rows.iter().all(|row| row.database_name == "Zeta"));
}
#[test]
fn database_backlink_cell_edits_write_the_parent_document_in_one_undo_step() {
let cases = [
(
"col-notes",
DatabaseCellEdit::RichText("Ship the inspector panel".into()),
"Ship the inspector panel",
),
(
"col-estimate",
DatabaseCellEdit::Value(DatabaseCellSpec::Number(5.5)),
"5.5",
),
(
"col-done",
DatabaseCellEdit::Value(DatabaseCellSpec::Bool(true)),
"true",
),
(
"col-due",
DatabaseCellEdit::Value(DatabaseCellSpec::Null),
"",
),
(
"col-url",
DatabaseCellEdit::Value(DatabaseCellSpec::Text("https://example.com".into())),
"https://example.com",
),
(
"col-progress",
DatabaseCellEdit::Value(DatabaseCellSpec::Integer(75)),
"75",
),
(
"col-status",
DatabaseCellEdit::Value(DatabaseCellSpec::Text("opt-done".into())),
"opt-done",
),
(
"col-tags",
DatabaseCellEdit::ToggleOption("opt-ui".into()),
"opt-rust,opt-ui",
),
(
"col-status",
DatabaseCellEdit::DeleteOption("opt-todo".into()),
"",
),
];
let render = |value: &DatabaseCellValue| match value {
DatabaseCellValue::Bool(value) => value.to_string(),
DatabaseCellValue::MultiSelect(items) => items.join(","),
DatabaseCellValue::Null => String::new(),
other => other
.as_str()
.map(str::to_owned)
.or_else(|| other.as_f64().map(|n| n.to_string()))
.unwrap_or_default(),
};
for (column, edit, expected) in cases {
let mut state = backlink_state(ThemeMode::Light);
let store = &mut state.store;
let row = store.database_backlinks(TARGET).remove(0);
let before = cell(store, column);
let revision = store.get_doc(PARENT).unwrap().revision;
assert!(store.edit_database_backlink_cell(&row, column, edit, 500));
assert_eq!(render(&cell(store, column)), expected, "{column}");
assert!(
store.get_doc(PARENT).unwrap().revision > revision,
"{column}"
);
let entry = store.docs.get_mut(PARENT).unwrap();
entry.session.undo().unwrap();
entry.snapshot = entry.session.read_page_snapshot().unwrap();
assert_eq!(
cell(store, column),
before,
"{column}: one undo step restores it"
);
}
let mut state = backlink_state(ThemeMode::Light);
state.store.sqlite_backing = Some(crate::sqlite_loader::SqliteLazyBacking::new(
"readonly.affine",
"ws-readonly",
0,
));
let row = state.store.database_backlinks(TARGET).remove(0);
assert!(!state.store.edit_database_backlink_cell(
&row,
"col-done",
DatabaseCellEdit::Value(DatabaseCellSpec::Bool(true)),
500
));
}
#[test]
fn database_backlink_option_edits_create_rename_recolor_and_delete_in_one_undo_step() {
let options = |store: &DesktopDocStore, column: &str| {
let snapshot = &store.get_doc(PARENT).unwrap().snapshot;
let Some(BlockContent::Database(data)) = snapshot.block(DATABASE).map(|node| &node.content)
else {
panic!("missing database");
};
let column = data.columns.iter().find(|c| c.id == column).unwrap();
column
.select_options()
.into_iter()
.map(|option| (option.value, option.color))
.collect::<Vec<_>>()
};
for (column, expected_cell) in [("col-phase", false), ("col-tags", true)] {
let mut state = backlink_state(ThemeMode::Light);
let store = &mut state.store;
let row = store.database_backlinks(TARGET).remove(0);
let before = options(store, column);
assert!(store.edit_database_backlink_cell(
&row,
column,
DatabaseCellEdit::CreateOption("Beta".into()),
500
));
let after = options(store, column);
assert_eq!(after.len(), before.len() + 1, "{column}");
assert_eq!(after.last().unwrap().0, "Beta", "{column}");
let selected = cell(store, column).as_string_list();
assert_eq!(
selected.len(),
if expected_cell { 2 } else { 1 },
"{column}"
);
let entry = store.docs.get_mut(PARENT).unwrap();
entry.session.undo().unwrap();
entry.snapshot = entry.session.read_page_snapshot().unwrap();
assert_eq!(options(store, column), before, "{column}: one undo step");
}
let mut state = backlink_state(ThemeMode::Light);
let store = &mut state.store;
let row = store.database_backlinks(TARGET).remove(0);
assert!(store.edit_database_backlink_cell(
&row,
"col-status",
DatabaseCellEdit::UpdateOption {
id: "opt-todo".into(),
value: "Backlog".into(),
color: "var(--affine-tag-red)".into(),
},
500
));
assert_eq!(
options(store, "col-status")[0],
("Backlog".to_owned(), "var(--affine-tag-red)".to_owned())
);
assert_eq!(
cell(store, "col-status"),
DatabaseCellValue::Text("opt-todo".into())
);
}
pub(super) fn backlink_shell(dialog: bool) -> (&'static str, Shell) {
let mut state = backlink_state(ThemeMode::Light);
state.open_doc_in_active_pane(TARGET);
state.inspector_tab = Some(DocInspectorTab::Info);
let app = Shell::with_state(1280, state);
if dialog {
app.open_page_information();
("desktop.header.info", app)
} else {
("desktop.inspector", app)
}
}
#[test]
fn database_backlink_sections_toggle_write_cells_and_open_the_database_from_both_entries() {
for dialog in [false, true] {
let (prefix, app) = backlink_shell(dialog);
let key = format!("{PARENT}/{DATABASE}/{ROW}");
let header = format!("{prefix}.database.{key}");
let done = format!("{prefix}.database.{key}.cell.col-done");
let cover = format!("{prefix}.database.{key}.cell.col-cover");
assert!(app.contains(&header), "{prefix}");
assert!(!app.contains(&done), "{prefix}: rows start collapsed");
app.click(&header);
assert!(app.contains(&done), "{prefix}");
assert!(
!app.contains(&cover),
"{prefix}: unsupported columns stay hidden"
);
app.click(&format!("{done}.value"));
app.update(|shell, _, _| {
assert_eq!(
cell(&shell.state.store, "col-done"),
DatabaseCellValue::Bool(true)
);
});
app.click(&format!("{prefix}.database.{key}.cell.col-status.value"));
let picker = format!("{prefix}.database.{key}.cell.col-status.picker");
assert!(app.contains(&picker), "{prefix}");
app.click(&format!(
"{prefix}.database.{key}.cell.col-status.option.opt-done"
));
assert!(
!app.contains(&picker),
"{prefix}: a single select closes the picker"
);
app.update(|shell, _, _| {
assert_eq!(
cell(&shell.state.store, "col-status"),
DatabaseCellValue::Text("opt-done".into())
);
});
let cell_id =
|column: &str, part: &str| format!("{prefix}.database.{key}.cell.{column}.{part}");
app.click(&cell_id("col-due", "value"));
let typed = "2026-12-25";
app.input(|input| input.replace_text_in_range(Some(0..10), typed));
app.key("enter");
let zone = LocalZone::system();
let local_midnight = parse_date_input_ms(typed, &|ms| zone.offset_minutes(ms));
app.update(|shell, _, _| {
assert_eq!(
cell(&shell.state.store, "col-due").as_i64(),
local_midnight,
"{prefix}"
);
});
app.click(&cell_id("col-phase", "value"));
app.click(&cell_id("col-phase", "search.0"));
app.input(|input| input.replace_text_in_range(None, "Beta"));
app.click(&cell_id("col-phase", "create"));
app.update(|shell, _, _| {
assert_eq!(
cell(&shell.state.store, "col-phase").as_string_list().len(),
1,
"{prefix}: the first option of an empty column is created and selected"
);
});
app.click(&header);
assert!(!app.contains(&done), "{prefix}");
app.click(&format!("{header}.ref"));
assert_eq!(app.route(), DesktopRoute::Doc(PARENT.into()), "{prefix}");
if dialog {
assert!(!app.contains("desktop.header.dialog"));
}
}
}
#[test]
fn database_backlink_panel_renders_nothing_without_linked_rows() {
let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02");
add_database(&mut state.store, PARENT, DATABASE, "Roadmap");
state.open_doc_in_active_pane("doc-board");
state.inspector_tab = Some(DocInspectorTab::Info);
let app = Shell::with_state(1280, state);
app.update(|_, window, _| {
assert!(
!window
.frame_snapshot()
.elements
.keys()
.any(|id| id.contains(".database.")),
);
});
}
#[test]
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] = [
(
"https://app.affine.pro/workspace/{ws}/{parent}",
Some(PARENT),
None,
),
(
"https://app.affine.pro/workspace/{ws}/{parent}?mode=edgeless",
Some(PARENT),
edgeless,
),
(
"/desktop/?workspace={ws}&doc={parent}&mode=edgeless",
Some(PARENT),
edgeless,
),
("/workspace/{ws}/doc-board", Some("doc-board"), None),
("/workspace/{ws}/{parent}?blockIds={db}", Some(PARENT), None),
("https://example.org/workspace/{ws}/{parent}", None, None),
(
"https://example.org/workspace/{ws}/{parent}?blockIds={db}",
None,
None,
),
("https://example.org/docs", None, None),
];
for dialog in [false, true] {
for (template, opened, mode) in cases {
let (prefix, app) = backlink_shell(dialog);
let key = format!("{PARENT}/{DATABASE}/{ROW}");
app.click(&format!("{prefix}.database.{key}"));
let url = |part: &str| format!("{prefix}.database.{key}.cell.col-url.{part}");
assert!(app.contains(&url("open")), "{prefix}");
app.click(&url("edit"));
app.window.request_frame();
let (workspace, tabs) = app.update(|shell, _, _| {
let tabs = shell.state.split.active().tabs.len();
(shell.state.store.active_workspace().id.clone(), tabs)
});
let link = template
.replace("{ws}", &workspace)
.replace("{parent}", PARENT)
.replace("{db}", DATABASE);
let old = "https://affine.pro".encode_utf16().count();
app.input(|input| input.replace_text_in_range(Some(0..old), &link));
app.key("enter");
app.update(|shell, _, _| {
assert_eq!(
cell(&shell.state.store, "col-url"),
DatabaseCellValue::Text(link.clone()),
"{prefix} {link}"
);
});
assert!(
!app.contains(&url("value")),
"{prefix}: the field closes after a commit"
);
app.click(&url("open"));
let expected = opened.unwrap_or(TARGET);
assert_eq!(
app.route(),
DesktopRoute::Doc(expected.into()),
"{prefix} {link}"
);
app.update(|shell, _, _| {
let pane = shell.state.split.active();
assert_eq!(pane.tabs.len(), tabs, "{prefix} {link}");
if let Some(mode) = mode {
assert_eq!(pane.active_mode(), mode, "{prefix} {link}");
}
});
if dialog && opened.is_some() {
assert!(!app.contains("desktop.header.dialog"), "{link}");
}
}
}
}
#[test]
fn database_backlink_header_link_opens_the_database_with_link_modifiers() {
let header = format!("desktop.inspector.database.{PARENT}/{DATABASE}/{ROW}.ref");
let (_, app) = backlink_shell(false);
let tabs = app.update(|shell, _, _| shell.state.split.active().tabs.len());
app.press(
&header,
MouseButton::Left,
Modifiers {
control: true,
..Modifiers::default()
},
);
app.update(|shell, _, _| {
let pane = shell.state.split.active();
assert_eq!(pane.tabs.len(), tabs + 1);
assert_eq!(pane.active_route(), &DesktopRoute::Doc(PARENT.into()));
assert_eq!(pane.active_mode(), DocViewMode::Page);
});
let (_, app) = backlink_shell(false);
app.press(
&header,
MouseButton::Left,
Modifiers {
shift: true,
..Modifiers::default()
},
);
app.window.request_frame();
app.update(|shell, _, cx| {
assert_eq!(shell.state.peek_view.doc_id.as_deref(), Some(PARENT));
assert_eq!(shell.state.peek_view.mode, Some(DocViewMode::Page));
assert_eq!(app_route_doc(shell), Some(TARGET.to_owned()));
assert_eq!(shell.state.peek_view.pending_selection, None);
let peek = shell.editor_host().peek_entity().unwrap();
assert_eq!(peek.read(cx).block_selection(), [DATABASE]);
});
}
fn app_route_doc(shell: &crate::DesktopShellView) -> Option<String> {
shell
.state
.split
.active()
.active_route()
.doc_id()
.map(str::to_owned)
}
@@ -1,3 +1,5 @@
mod database_backlink_pickers;
mod database_backlinks;
mod explorer_menus;
mod inspector_outline;
mod journal_panel;
@@ -1,7 +1,8 @@
use playground::{BlockLink, ParsedBlockLink};
use ui::Context;
use ui::{Context, Modifiers};
use crate::{
peek_view::PeekSelection,
split_view::DocViewMode,
workbench::{BlockReveal, DesktopShellView, PendingBlockLink},
};
@@ -52,6 +53,102 @@ impl DesktopShellView {
});
}
/// Open `block_id` of `doc_id` in the active workspace with the link modifiers: `Shift`
/// opens Peek View, `Cmd`/`Ctrl` a new tab, and a plain click the active pane. Panes and
/// new tabs open in Page mode and select the block.
pub(crate) fn open_doc_block(
&mut self,
doc_id: &str,
block_id: &str,
modifiers: Modifiers,
cx: &mut Context<Self>,
) {
if !self.state.is_openable_doc(doc_id)
|| self.state.store.ensure_doc_hydrated(doc_id) != Ok(true)
{
return;
}
let workspace_id = self.state.store.active_workspace().id.clone();
let reveal = BlockReveal::Page(vec![block_id.to_owned()]);
self.sync_editors(cx);
if modifiers.shift {
self.state
.open_peek_view_with_mode(doc_id, Some(DocViewMode::Page));
if self.state.peek_view.doc_id.as_deref() == Some(doc_id) {
self.state.peek_view.pending_selection = Some(PeekSelection {
block_ids: vec![block_id.to_owned()],
element_ids: Vec::new(),
});
}
} else if modifiers.platform || modifiers.control {
#[cfg(target_arch = "wasm32")]
if self.state.web_chrome {
let url = BlockLink::document_url(
"",
&workspace_id,
doc_id,
Some("page"),
&[block_id],
&[] as &[&str],
true,
);
self.save_local_workspaces();
crate::wasm_entry::open_document_tab(&url, "_blank", "noopener");
return;
}
self.state.peek_view.close();
self.state.open_header_doc_in_new_tab(doc_id);
self.state.split.active_mut().set_mode(DocViewMode::Page);
self.queue_block_reveal(workspace_id, doc_id.to_owned(), reveal);
} else {
self.state.peek_view.close();
if self.state.split.active().active_route().doc_id() == Some(doc_id) {
self.state.split.active_mut().set_mode(DocViewMode::Page);
} else {
self.state
.open_doc_in_active_pane_with_mode(doc_id, Some(DocViewMode::Page));
}
self.queue_block_reveal(workspace_id, doc_id.to_owned(), reveal);
}
cx.notify();
}
/// Open the URL of a database `link` cell: a document link of this workspace in the active
/// pane, as `0.27.5` `resolveLinkToDoc` does, and any other URL in the browser. A path
/// resolves against the workspace origin, and a full URL of another origin stays external.
pub(crate) fn open_cell_link(&mut self, url: &str, cx: &mut Context<Self>) {
let workspace_id = self.state.store.active_workspace().id.clone();
let origin = self.workspace_link_origin(&workspace_id);
let Some(url) = absolute_cell_url(url, &origin) else {
return;
};
if let Some(target) = BlockLink::parse(&url)
&& self.open_document_block_link(target, cx)
{
return;
}
if let Some((doc_id, mode)) = workspace_doc_of(&url, &origin, &workspace_id)
&& self.state.is_openable_doc(&doc_id)
&& self.state.store.ensure_doc_hydrated(&doc_id) == Ok(true)
{
self.sync_editors(cx);
self.state.peek_view.close();
self.state.open_doc_in_active_pane_with_mode(&doc_id, mode);
cx.notify();
return;
}
cx.open_url(&url);
}
/// The origin of the block and document links of a workspace.
fn workspace_link_origin(&self, workspace_id: &str) -> String {
self.editor_host
.workspace_origins
.get(workspace_id)
.cloned()
.unwrap_or_else(playground::default_block_link_origin)
}
pub(crate) fn open_block_link(&mut self, target: BlockLink, cx: &mut Context<Self>) -> bool {
self.open_link_target(
target.origin,
@@ -102,21 +199,14 @@ impl DesktopShellView {
reveal: BlockReveal,
cx: &mut Context<Self>,
) -> bool {
let store = &mut self.state.store;
let Some(index) = store.workspaces.iter().position(|ws| ws.id == workspace_id) else {
let Some(index) = (self.state.store.workspaces.iter()).position(|ws| ws.id == workspace_id)
else {
return false;
};
if origin
!= self
.editor_host
.workspace_origins
.get(&workspace_id)
.cloned()
.unwrap_or_else(playground::default_block_link_origin)
{
if origin != self.workspace_link_origin(&workspace_id) {
return false;
}
let previous = store.active_workspace_idx;
let previous = self.state.store.active_workspace_idx;
self.sync_editors(cx);
self.state.switch_workspace(index);
if self.state.store.active_workspace_idx != index
@@ -148,10 +238,185 @@ impl DesktopShellView {
}
}
/// The full URL of a `link` cell value: a path joins `origin`, a value without a scheme gets
/// `https://`, and any other value stays as it is. Only `http`, `https`, and `mailto` URLs
/// are returned.
fn absolute_cell_url(url: &str, origin: &str) -> Option<String> {
let url = url.trim();
let mailto = url
.get(..7)
.is_some_and(|scheme| scheme.eq_ignore_ascii_case("mailto:"));
let absolute = if url.starts_with('/') && !url.starts_with("//") {
format!("{}{url}", origin.trim_end_matches('/'))
} else if url.contains("://") || mailto {
url.to_owned()
} else {
format!("https://{}", url.trim_start_matches('/'))
};
(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 workspace_doc_of(
url: &str,
origin: &str,
workspace_id: &str,
) -> Option<(String, Option<DocViewMode>)> {
if BlockLink::server_origin(url)? != origin.trim_end_matches('/') {
return None;
}
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/") {
let (id, page) = tail.trim_end_matches('/').split_once('/')?;
if page.contains('/') {
return None;
}
(workspace, doc) = (decode(id), decode(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),
("mode", "page") => mode = Some(DocViewMode::Page),
("mode", "edgeless") => mode = Some(DocViewMode::Edgeless),
_ => return None,
}
}
let doc = doc.filter(|doc| !doc.is_empty())?;
(workspace? == workspace_id).then_some((doc, mode))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cell_links_open_safe_schemes_and_documents_of_the_workspace_origin_only() {
const ORIGIN: &str = "https://app.affine.pro";
for (value, url, doc) in [
(
"https://app.affine.pro/workspace/ws-1/doc-a",
"https://app.affine.pro/workspace/ws-1/doc-a",
Some(("doc-a", None)),
),
(
"/workspace/ws-1/doc-a",
"https://app.affine.pro/workspace/ws-1/doc-a",
Some(("doc-a", None)),
),
(
"https://app.affine.pro/workspace/ws-1/%E6%96%87",
"https://app.affine.pro/workspace/ws-1/%E6%96%87",
Some(("文", None)),
),
(
"/desktop/?workspace=ws-1&doc=doc-b&mode=page",
"https://app.affine.pro/desktop/?workspace=ws-1&doc=doc-b&mode=page",
Some(("doc-b", Some(DocViewMode::Page))),
),
(
"https://app.affine.pro/workspace/ws-1/doc-a?mode=edgeless",
"https://app.affine.pro/workspace/ws-1/doc-a?mode=edgeless",
Some(("doc-a", Some(DocViewMode::Edgeless))),
),
(
"/desktop?doc=doc-b&mode=edgeless&workspace=ws-1",
"https://app.affine.pro/desktop?doc=doc-b&mode=edgeless&workspace=ws-1",
Some(("doc-b", Some(DocViewMode::Edgeless))),
),
(
"/workspace/ws-1/doc-a?mode=slides",
"https://app.affine.pro/workspace/ws-1/doc-a?mode=slides",
None,
),
(
"/workspace/ws-1/doc-a?doc=doc-b",
"https://app.affine.pro/workspace/ws-1/doc-a?doc=doc-b",
None,
),
(
"https://example.org/workspace/ws-1/doc-a",
"https://example.org/workspace/ws-1/doc-a",
None,
),
(
"https://example.org/desktop/?workspace=ws-1&doc=doc-b",
"https://example.org/desktop/?workspace=ws-1&doc=doc-b",
None,
),
(
"https://app.affine.pro/workspace/ws-2/doc-a",
"https://app.affine.pro/workspace/ws-2/doc-a",
None,
),
(
"https://app.affine.pro/workspace/ws-1/doc-a?blockIds=b",
"https://app.affine.pro/workspace/ws-1/doc-a?blockIds=b",
None,
),
(
"//example.org/workspace/ws-1/doc-a",
"https://example.org/workspace/ws-1/doc-a",
None,
),
("affine.pro", "https://affine.pro", None),
("mailto:a@example.com", "mailto:a@example.com", None),
("MAILTO:a@example.com", "MAILTO:a@example.com", None),
("HTTPS://example.org/a", "HTTPS://example.org/a", None),
("localhost:3000/a", "https://localhost:3000/a", None),
] {
let absolute = absolute_cell_url(value, ORIGIN);
assert_eq!(absolute.as_deref(), Some(url), "{value}");
let absolute = absolute.unwrap_or_default();
assert_eq!(
workspace_doc_of(&absolute, ORIGIN, "ws-1"),
doc.map(|(doc, mode)| (doc.to_owned(), mode)),
"{value}"
);
}
for value in [
"javascript:alert(1)",
"JavaScript://example.org/%0Aalert(1)",
"data:text/html,<script>alert(1)</script>",
"file:///etc/passwd",
"vbscript:msgbox(1)",
"ftp://example.org/a",
] {
assert_eq!(absolute_cell_url(value, ORIGIN), None, "{value}");
}
}
#[test]
fn share_url_encodes_workspace_and_document_on_both_hosts() {
let target = DocTarget {