feat(desktop): add explorer row menu and journal day activity

Align the document explorer and the right-sidebar journal panel with
AFFiNE 0.27.5:

- Add the explorer row menu (favorite, new tab, split view, center peek,
  duplicate, and move to trash with confirmation), hover favorite star,
  Shift+Click range selection, two-step Escape dismissal, New doc menu,
  and searchable tag switcher breadcrumb.
- Add right-sidebar journal calendar activity dots, local-time-zone
  Created and Updated document lists (pre-parsed TZif and IEEE 1003.1
  POSIX Mm.w.d, Jn, and n date rules), and same-day journal list with
  trash confirmation.
This commit is contained in:
DarkSky committed 2026-12-04 08:55:43 +09:00
1 parent 657a2b0b03
commit c7e48d5cb3
16 files changed
+4349 -1533

No files matched your search

@@ -0,0 +1,229 @@
//! The `Delete doc?` confirmation that every document `Move to trash` entry opens.
use ui::{
AnyElement, App, Entity, FocusHandle, Focusable as _, FontWeight, InteractiveElement,
IntoElement, ParentElement, SharedString, StatefulInteractiveElement, Styled, Window, div, px,
};
use ui_tokens::{FONT_SANS, ThemeMode};
use crate::{
DesktopPalette,
views_extra::{button, button_with_fill, max_width},
workbench::DesktopShellView,
};
/// Documents that wait for the user to confirm `Move to trash`.
pub(in crate::views_extra) struct TrashPrompt {
ids: Vec<String>,
focus: FocusHandle,
/// Takes the focus back when the confirmation closes. Without it the shell takes it.
opener: Option<FocusHandle>,
}
impl TrashPrompt {
pub(in crate::views_extra) fn keyed(
key: SharedString,
window: &mut Window,
app: &mut App,
) -> Entity<Self> {
window.use_keyed_state(key, app, |_, cx| Self {
ids: Vec::new(),
focus: cx.focus_handle(),
opener: None,
})
}
pub(in crate::views_extra) fn open(
prompt: &Entity<Self>,
ids: Vec<String>,
opener: Option<FocusHandle>,
window: &mut Window,
app: &mut App,
) {
if ids.is_empty() {
return;
}
let focus = prompt.update(app, |prompt, cx| {
prompt.ids = ids;
prompt.opener = opener;
cx.notify();
prompt.focus.clone()
});
window.focus(&focus, app);
}
}
fn close(
prompt: &Entity<TrashPrompt>,
shell: &Entity<DesktopShellView>,
window: &mut Window,
app: &mut App,
) {
let opener = prompt.update(app, |prompt, cx| {
prompt.ids.clear();
cx.notify();
prompt.opener.take()
});
let focus = opener.unwrap_or_else(|| shell.read(app).focus_handle(app));
window.focus(&focus, app);
}
/// Render the open confirmation over the whole window. `on_trashed` receives the documents that
/// moved to Trash.
pub(in crate::views_extra) fn render_trash_prompt(
prompt: &Entity<TrashPrompt>,
shell: &Entity<DesktopShellView>,
(palette, theme): (DesktopPalette, ThemeMode),
window: &Window,
app: &App,
on_trashed: impl Fn(&[String], &mut App) + 'static,
) -> Option<AnyElement> {
let state = prompt.read(app);
let ids = state.ids.clone();
let focus = state.focus.clone();
let (title, description) = match ids.as_slice() {
[] => return None,
[id] => (
"Delete doc?".to_string(),
format!(
"{} will be moved to trash",
shell
.read(app)
.state
.route_title(&crate::split_view::DesktopRoute::Doc(id.clone()))
),
),
_ => (
format!("Delete {} docs?", ids.len()),
format!("{} docs will be moved to Trash", ids.len()),
),
};
let cancel = {
let (prompt, shell) = (prompt.clone(), shell.clone());
move |_: &ui::ClickEvent, window: &mut Window, app: &mut App| {
app.stop_propagation();
close(&prompt, &shell, window, app);
}
};
let confirm = {
let (prompt, shell) = (prompt.clone(), shell.clone());
move |_: &ui::ClickEvent, window: &mut Window, app: &mut App| {
app.stop_propagation();
let ids = prompt.read(app).ids.clone();
let trashed: Vec<String> = shell.update(app, |shell, cx| {
shell.sync_editors(cx);
let trashed = ids
.into_iter()
.filter(|id| shell.state.trash_doc(id))
.collect();
cx.notify();
trashed
});
close(&prompt, &shell, window, app);
on_trashed(&trashed, app);
}
};
let escape = {
let (prompt, shell) = (prompt.clone(), shell.clone());
move |event: &ui::KeyDownEvent, window: &mut Window, app: &mut App| {
if event.keystroke.key == "escape" {
window.prevent_default();
app.stop_propagation();
close(&prompt, &shell, window, app);
}
}
};
let writable = !shell.read(app).state.store.is_readonly_sqlite();
let delete = button_with_fill(
"desktop.trash_prompt.confirm",
"Delete",
palette,
writable,
Some(palette.danger),
)
.snapshot("desktop.trash_prompt.confirm", Some("desktop.trash_prompt"));
let delete = if writable {
delete.on_click(confirm)
} else {
delete
};
let viewport = window.viewport_size();
let dialog = div()
.id("desktop.trash_prompt.layer")
.track_focus(&focus)
.on_key_down(escape)
.w(viewport.width)
.h(viewport.height)
.relative()
.flex()
.items_center()
.justify_center()
.p(px(16.0))
.font_family(FONT_SANS)
.text_color(palette.text_primary)
.child(
div()
.id("desktop.trash_prompt.backdrop")
.absolute()
.inset_0()
.occlude()
.bg(palette.scrim)
.on_click(cancel.clone()),
)
.child(
max_width(div().id("desktop.trash_prompt").occlude(), px(480.0))
.snapshot("desktop.trash_prompt", Some("desktop.shell.root"))
.relative()
.flex()
.flex_col()
.gap(px(12.0))
.w_full()
.p(px(20.0))
.rounded(px(12.0))
.bg(palette.bg_elevated)
.shadow(crate::theme_shadow(theme, "--affine-popover-shadow"))
.child(
div()
.text_size(px(18.0))
.font_weight(FontWeight::SEMIBOLD)
.child(title),
)
.child(
div()
.snapshot("desktop.trash_prompt.body", Some("desktop.trash_prompt"))
.snapshot_text(description.clone())
.text_size(px(15.0))
.text_color(palette.text_secondary)
.child(description),
)
.child(
div()
.flex()
.flex_wrap()
.gap(px(8.0))
.pt(px(8.0))
.child(div().flex_1())
.child(
button("desktop.trash_prompt.cancel", "Cancel", palette, true)
.snapshot(
"desktop.trash_prompt.cancel",
Some("desktop.trash_prompt"),
)
.border_1()
.border_color(palette.border)
.px(px(12.0))
.on_click(cancel),
)
.child(delete.px(px(12.0))),
),
);
Some(
ui::deferred(
ui::anchored()
.position(ui::point(px(0.0), px(0.0)))
.child(dialog),
)
.priority(1)
.into_any_element(),
)
}
@@ -0,0 +1,177 @@
//! The `New doc` button of All Docs and the `Tags / <tag>` breadcrumb of a tag page.
use ui::{
AppContext as _, Div, InteractiveElement, ParentElement, StatefulInteractiveElement, Styled,
div, prelude::FluentBuilder as _, px, svg,
};
use ui_tokens::{ThemeMode, icons::ARROW_DOWN_SMALL};
use super::{Controls, Destination, Menu, Popup, tag_search::TagSearch};
use crate::{
DesktopFlexExt, DesktopPalette, doc_store::DesktopDocStore, split_view::DesktopRoute,
views_extra::resolve_tag_color,
};
/// `PageListNewPageButton`: the label creates a document of the default mode, and the arrow
/// opens the Page and Edgeless choices.
pub(super) fn new_doc_button(controls: &Controls, palette: DesktopPalette, writable: bool) -> Div {
let segment = |id: &'static str| {
div()
.id(id)
.snapshot(id, Some("desktop.workbench"))
.h_full()
.flex()
.items_center()
.when(writable, |segment| {
segment
.cursor_pointer()
.hover(move |style| style.bg(palette.hover_overlay))
})
};
let label = segment("desktop.explorer.new_doc")
.px(px(8.0))
.text_size(px(12.0))
.font_weight(ui::FontWeight::MEDIUM)
.child("New doc")
.when(writable, |label| label.on_click(controls.new_doc(None)));
let arrow = segment("desktop.explorer.new_doc.menu")
.w(px(24.0))
.justify_center()
.child(
svg()
.data(ARROW_DOWN_SMALL.svg.as_bytes())
.size(px(16.0))
.text_color(palette.text_secondary),
)
.when(writable, |arrow| {
arrow.on_click(controls.open_popup(|| Menu::NewDoc))
});
div()
.flex()
.flex_shrink(0.0)
.items_center()
.h(px(28.0))
.rounded(px(8.0))
.overflow_hidden()
.border_1()
.border_color(palette.border)
.bg(palette.bg_elevated)
.text_color(palette.text_primary)
.when(!writable, |button| button.opacity(0.55))
.child(label)
.child(div().w(px(1.0)).h(px(16.0)).bg(palette.border))
.child(arrow)
}
/// `TagListHeader`: `Tags` returns to the tag overview, and the tag chip opens the tag switcher.
pub(super) fn tag_breadcrumb(
tag: &str,
controls: &Controls,
(palette, theme): (DesktopPalette, ThemeMode),
store: &DesktopDocStore,
menu: Option<ui::Stateful<Div>>,
) -> Div {
let color = ui::rgb(resolve_tag_color(tag, store, theme) & 0x00ff_ffff);
let current = tag.to_owned();
div()
.flex()
.items_center()
.text_size(px(14.0))
.line_height(px(22.0))
.text_color(palette.text_secondary)
.child(
div()
.id("desktop.explorer.breadcrumb.tags")
.snapshot(
"desktop.explorer.breadcrumb.tags",
Some("desktop.workbench"),
)
.cursor_pointer()
.child("Tags")
.on_click(controls.navigate(DesktopRoute::AllDocs, Some(Destination::Tags))),
)
.child(div().w(px(4.0)))
.child(div().mr(px(8.0)).child("/"))
.child(
div()
.relative()
.min_w_0()
.child(
div()
.id("desktop.explorer.breadcrumb.tag")
.snapshot("desktop.explorer.breadcrumb.tag", Some("desktop.workbench"))
.snapshot_text(store.tag_label(tag))
.flex()
.min_w_0()
.items_center()
.gap(px(2.0))
.px(px(2.0))
.rounded(px(100.0))
.border_1()
.border_color(palette.border)
.cursor_pointer()
.child(
div()
.w(px(18.0))
.h(px(16.0))
.flex()
.flex_shrink(0.0)
.items_center()
.justify_center()
.child(div().size(px(7.0)).rounded(px(3.5)).bg(color)),
)
.child(
div()
.snapshot(
"desktop.explorer.heading",
Some("desktop.explorer.breadcrumb.tag"),
)
.snapshot_text(store.tag_label(tag))
.min_w_0()
.truncate()
.text_color(palette.text_primary)
.child(store.tag_label(tag)),
)
.child(
div()
.size(px(24.0))
.flex()
.flex_shrink(0.0)
.items_center()
.justify_center()
.child(
svg()
.data(ARROW_DOWN_SMALL.svg.as_bytes())
.size(px(20.0))
.text_color(palette.text_secondary),
),
)
.on_click({
let state = controls.state.clone();
move |event, window, app| {
app.stop_propagation();
let search = app.new(|cx| {
TagSearch::new(cx.focus_handle(), palette, state.clone())
});
let focus = search.read(app).focus.clone();
state.update(app, |state, cx| {
state.popup = Some(Popup {
menu: Menu::TagSwitch(current.clone(), search),
position: event.position(),
});
cx.notify();
});
window.focus(&focus, app);
}
}),
)
.children(menu.map(|menu| {
// `TagListHeader` opens the switcher 4px below the chip, aligned to its start.
div().absolute().top_0().left_0().child(ui::deferred(
ui::anchored()
.offset(ui::point(px(0.0), px(30.0)))
.child(menu),
))
})),
)
}
@@ -1,14 +1,16 @@
use affine_store::directory::DocMode;
use ui::{
Div, ElementId, InteractiveElement, ParentElement, SharedString, Stateful,
StatefulInteractiveElement, Styled, div, prelude::FluentBuilder as _, px,
StatefulInteractiveElement, Styled, div, prelude::FluentBuilder as _, px, svg,
};
use ui_tokens::ThemeMode;
use ui_tokens::{ThemeMode, icons};
use super::{Controls, DocAction, Menu, Popup};
use crate::{
DesktopPalette,
DOC_ICON_SVG, DesktopFlexExt, DesktopPalette, EDGELESS_ICON_SVG, PEEK_ICON_SVG,
STAR_FILLED_SVG, STAR_ICON_SVG, TRASH_ICON_SVG,
split_view::DesktopRoute,
views_extra::{button, doc_order::DocOrder, vertical_scroll},
};
@@ -16,10 +18,11 @@ pub(super) fn render_menu(
popup: &Popup,
controls: &Controls,
palette: DesktopPalette,
(writable, can_split): (bool, bool),
tags: Vec<(String, String)>,
(writable, can_split, favorite): (bool, bool, bool),
tags: Vec<(String, String, u32)>,
selected: Vec<String>,
theme: ThemeMode,
app: &ui::App,
) -> Stateful<Div> {
let state = controls.state.clone();
let mut menu = div()
@@ -34,6 +37,7 @@ pub(super) fn render_menu(
.border_1()
.border_color(palette.border)
.bg(palette.bg_elevated)
.text_color(palette.text_primary)
.shadow(crate::theme_shadow(theme, "--affine-menu-shadow"));
menu.interactivity().on_mouse_down_out(move |_, _, app| {
state.update(app, |state, cx| {
@@ -46,6 +50,56 @@ pub(super) fn render_menu(
row.style().justify_content = Some(ui::JustifyContent::FlexStart);
row
};
let item =
|id: &'static str, label: &'static str, icon: &'static [u8], enabled: bool| {
let color = if id == "trash" && enabled {
palette.danger
} else if enabled {
palette.text_primary
} else {
palette.text_muted
};
div()
.id(id)
.snapshot(
ui::snap_id!("desktop.explorer.menu.{id}"),
Some("desktop.explorer.menu"),
)
.snapshot_text(label)
.flex()
.flex_shrink(0.0)
.items_center()
.gap(px(8.0))
.h(px(32.0))
.px(px(8.0))
.rounded(px(4.0))
.text_size(px(14.0))
.text_color(color)
.map(|row| {
if enabled {
row.tab_stop(true)
.cursor_pointer()
.hover(move |style| style.bg(palette.hover_color))
} else {
row.opacity(0.55)
}
})
.child(svg().data(icon).size(px(20.0)).flex_shrink(0.0).text_color(
if id == "trash" {
color
} else {
palette.text_secondary
},
))
.child(div().min_w_0().truncate().child(label))
};
let separator = || {
div()
.h(px(1.0))
.my(px(4.0))
.flex_shrink(0.0)
.bg(palette.border)
};
match &popup.menu {
Menu::Order => {
for (label, order) in [
@@ -81,29 +135,158 @@ pub(super) fn render_menu(
}
}
Menu::Row(id) => {
let one = || vec![id.clone()];
let (favorite_label, favorite_icon) = if favorite {
("Remove from favourites", STAR_FILLED_SVG)
} else {
("Add to favourites", STAR_ICON_SVG)
};
menu = menu
.w(px(240.0))
.child(
option("Open in center peek".into(), true)
.snapshot("desktop.explorer.menu.peek", Some("desktop.explorer.menu"))
.on_click(controls.doc_action(vec![id.clone()], DocAction::Peek)),
item("favorite", favorite_label, favorite_icon, writable)
.when(writable, |row| {
row.on_click(controls.doc_action(one(), DocAction::Favorite))
}),
)
.child(
item(
"new_tab",
"Open in new tab",
icons::OPEN_IN_NEW.svg.as_bytes(),
true,
)
.on_click(controls.doc_action(one(), DocAction::NewTab)),
)
.when(can_split, |menu| {
menu.child(
option("Open in split view".into(), true)
.snapshot("desktop.explorer.menu.split", Some("desktop.workbench"))
.on_click(controls.doc_action(vec![id.clone()], DocAction::Split)),
item(
"split",
"Open in split view",
icons::SPLIT_VIEW.svg.as_bytes(),
true,
)
.on_click(controls.doc_action(one(), DocAction::Split)),
)
})
.child(
option("Move to Trash".into(), writable)
.snapshot("desktop.explorer.menu.trash", Some("desktop.explorer.menu"))
.when(writable, |button| {
button
.text_color(palette.danger)
.on_click(controls.doc_action(vec![id.clone()], DocAction::Trash))
}),
item("peek", "Open in center peek", PEEK_ICON_SVG, true)
.on_click(controls.doc_action(one(), DocAction::Peek)),
)
.child(
item(
"duplicate",
"Duplicate",
icons::DUPLICATE.svg.as_bytes(),
writable,
)
.when(writable, |row| {
row.on_click(controls.doc_action(one(), DocAction::Duplicate))
}),
)
.child(separator())
.child(
item("trash", "Move to trash", TRASH_ICON_SVG, writable)
.when(writable, |row| row.on_click(controls.trash(one()))),
);
}
Menu::NewDoc => {
menu = menu
.child(
item("new_page", "Page", DOC_ICON_SVG, true)
.on_click(controls.new_doc(Some(DocMode::Page))),
)
.child(
item("new_edgeless", "Edgeless", EDGELESS_ICON_SVG, true)
.on_click(controls.new_doc(Some(DocMode::Edgeless))),
);
}
Menu::TagSwitch(current, search) => {
let query = search.read(app);
let tags: Vec<_> = tags
.into_iter()
.filter(|(_, label, _)| query.matches(label))
.collect();
let empty = tags.is_empty();
menu.style().max_size.height = Some(px(400.0).into());
menu =
menu.w(px(240.0))
.p(px(0.0))
.child(div().px(px(4.0)).pt(px(4.0)).child(search.clone()))
.child(div().h(px(1.0)).mt(px(2.0)).bg(palette.border))
.when(empty, |menu| {
menu.child(
div()
.snapshot(
"desktop.explorer.tag_switch.empty",
Some("desktop.explorer.menu"),
)
.snapshot_text("Found 0 results")
.px(px(12.0))
.py(px(8.0))
.text_size(px(14.0))
.text_color(palette.text_secondary)
.child("Found 0 results"),
)
})
.child(vertical_scroll(
"desktop.explorer.tag_switcher",
div().flex().flex_col().gap(px(2.0)).p(px(4.0)).children(
tags.into_iter().map(|(tag, label, color)| {
let checked = tag == *current;
let mut row = div()
.id(ElementId::NamedInteger(
SharedString::new_static("explorer-tag-switch"),
ui::hash(&tag),
))
.snapshot(
ui::snap_id!("desktop.explorer.tag_switch.{tag}"),
Some("desktop.explorer.menu"),
)
.flex()
.items_center()
.gap(px(8.0))
.h(px(32.0))
.px(px(4.0))
.rounded(px(4.0))
.cursor_pointer()
.text_size(px(14.0))
.hover(move |style| style.bg(palette.hover_color))
.child(
div()
.w(px(18.0))
.flex()
.flex_shrink(0.0)
.justify_center()
.child(
div()
.size(px(7.0))
.rounded(px(3.5))
.bg(ui::rgb(color & 0x00ff_ffff)),
),
)
.child(div().flex_1().min_w_0().truncate().child(label))
.when(checked, |row| {
row.child(
svg()
.data(icons::DONE.svg.as_bytes())
.size(px(20.0))
.flex_shrink(0.0)
.text_color(palette.accent),
)
});
if !checked {
row = row
.on_click(controls.navigate(DesktopRoute::Tag(tag), None));
} else {
row = row
.on_click(controls.change(|state, _| state.popup = None));
}
row
}),
),
));
}
Menu::Tag => {
if tags.is_empty() {
menu = menu.child(option("No workspace tags".into(), false));
@@ -114,7 +297,7 @@ pub(super) fn render_menu(
div()
.flex()
.flex_col()
.children(tags.into_iter().map(|(tag, label)| {
.children(tags.into_iter().map(|(tag, label, _)| {
let mut row = button(
ElementId::NamedInteger(
SharedString::new_static("explorer-tag-option"),
@@ -1,17 +1,24 @@
mod confirm;
mod header;
mod menu;
mod new_tab;
mod rows;
mod tag_search;
use std::collections::BTreeSet;
use std::{collections::BTreeSet, rc::Rc};
use affine_store::directory::DocMode;
use ui::{
App, ClickEvent, Context, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement,
Pixels, Point, RenderOnce, SharedString, StatefulInteractiveElement, Styled, Window, div,
prelude::FluentBuilder as _, px, svg,
App, ClickEvent, Context, Entity, FocusHandle, FontWeight, InteractiveElement, IntoElement,
ParentElement, Pixels, Point, RenderOnce, SharedString, StatefulInteractiveElement, Styled,
Window, div, prelude::FluentBuilder as _, px, svg,
};
use ui_tokens::FONT_SANS;
pub(super) use confirm::{TrashPrompt, render_trash_prompt};
use header::{new_doc_button, tag_breadcrumb};
use menu::render_menu;
pub(super) use new_tab::open_in_new_tab;
use rows::{doc_row, empty};
use super::{
@@ -57,6 +64,8 @@ enum Menu {
Order,
Filter,
Tag,
TagSwitch(String, Entity<tag_search::TagSearch>),
NewDoc,
}
struct Popup {
@@ -72,6 +81,8 @@ struct ExplorerState {
filter: Option<DocMode>,
selecting: bool,
selected: BTreeSet<String>,
/// The row that the last selection click toggled. `Shift+Click` selects from it.
anchor: Option<String>,
popup: Option<Popup>,
}
@@ -89,6 +100,8 @@ struct Controls {
location: PaneLocation,
state: Entity<ExplorerState>,
overview: Entity<Destination>,
focus: FocusHandle,
prompt: Entity<TrashPrompt>,
}
impl Controls {
@@ -97,8 +110,10 @@ impl Controls {
action: impl Fn(&mut ExplorerState, &ClickEvent) + 'static,
) -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static {
let state = self.state.clone();
move |event, _, app| {
let focus = self.focus.clone();
move |event, window, app| {
app.stop_propagation();
window.focus(&focus, app);
state.update(app, |state, cx| {
action(state, event);
cx.notify();
@@ -130,12 +145,12 @@ impl Controls {
shell.state.split.focus_pane(index);
if let Some(destination) = overview {
this.overview.write(cx, destination);
this.state.update(cx, |state, cx| {
state.selected.clear();
state.popup = None;
cx.notify();
});
}
this.state.update(cx, |state, cx| {
state.leave_selection();
state.popup = None;
cx.notify();
});
shell.state.navigate_active_pane(route.clone());
cx.notify();
}
@@ -149,49 +164,157 @@ impl Controls {
action: DocAction,
) -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static {
let this = self.clone();
move |event, _, app| {
move |_, _, app| {
app.stop_propagation();
this.shell.update(app, |shell, cx| {
let Some(index) = this.location.pane_index(shell) else {
return;
};
shell.state.split.focus_pane(index);
let mut completed = Vec::new();
for id in &ids {
if shell
.state
.store
.get_doc(id)
.is_none_or(|doc| doc.meta.trashed)
{
continue;
this.run(&ids, &action, app);
}
}
fn run(&self, ids: &[String], action: &DocAction, app: &mut App) {
self.shell.update(app, |shell, cx| {
let Some(index) = self.location.pane_index(shell) else {
return;
};
shell.state.split.focus_pane(index);
let mut completed = Vec::new();
for id in ids {
if shell
.state
.store
.get_doc(id)
.is_none_or(|doc| doc.meta.trashed)
{
continue;
}
if matches!(action, DocAction::NewTab) {
open_in_new_tab(shell, id);
continue;
}
let state = &mut shell.state;
match action {
DocAction::Open | DocAction::NewTab => state.open_doc_in_active_pane(id),
DocAction::Peek => state.open_peek_view(id),
DocAction::Split => state.open_doc_in_split(id),
DocAction::Duplicate => {
state.duplicate_header_doc(id);
}
match &action {
DocAction::Open if event.modifiers().shift => {
shell.state.open_peek_view(id)
DocAction::Favorite => {
if !state.store.is_readonly_sqlite() {
state.store.toggle_favorite(id);
}
DocAction::Open => shell.state.open_doc_in_active_pane(id),
DocAction::Peek => shell.state.open_peek_view(id),
DocAction::Split => shell.state.open_doc_in_split(id),
DocAction::Trash => {
if shell.state.trash_doc(id) {
completed.push(id);
}
}
DocAction::Tag(tag) => {
if update_tag(&mut shell.state, id, tag, true) {
completed.push(id);
}
}
DocAction::Tag(tag) => {
if update_tag(state, id, tag, true) {
completed.push(id);
}
}
}
this.state.update(cx, |state, cx| {
for id in completed {
state.selected.remove(id);
}
self.state.update(cx, |state, cx| {
for id in completed {
state.selected.remove(id);
}
state.popup = None;
cx.notify();
});
cx.notify();
});
}
fn trash(&self, ids: Vec<String>) -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static {
let this = self.clone();
move |_, window, app| {
app.stop_propagation();
this.state.update(app, |state, cx| {
state.popup = None;
cx.notify();
});
TrashPrompt::open(
&this.prompt,
ids.clone(),
Some(this.focus.clone()),
window,
app,
);
}
}
/// A primary click on a row: toggles the row while selecting, enters selection on
/// `Shift+Click`, opens a new tab on `Cmd/Ctrl+Click`, and opens the document otherwise.
fn row_click(
&self,
id: String,
order: Rc<Vec<String>>,
writable: bool,
) -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static {
let this = self.clone();
move |event, window, app| {
app.stop_propagation();
let modifiers = event.modifiers();
let selecting = this.state.read(app).selecting;
if writable && (selecting || modifiers.shift) {
window.focus(&this.focus, app);
this.state.update(app, |state, cx| {
if !state.selecting {
state.selecting = true;
state.selected.clear();
state.anchor = None;
state.toggle(&id);
} else if modifiers.shift {
state.select_range(&order, &id);
} else {
state.toggle(&id);
}
state.popup = None;
cx.notify();
});
} else if modifiers.platform || modifiers.control {
this.run(std::slice::from_ref(&id), &DocAction::NewTab, app);
} else {
this.run(std::slice::from_ref(&id), &DocAction::Open, app);
}
}
}
/// A secondary click: the middle button opens a new tab, and the right button or a long
/// press opens the row menu.
fn row_aux_click(&self, id: String) -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static {
let this = self.clone();
let menu = self.open_popup({
let id = id.clone();
move || Menu::Row(id.clone())
});
move |event, window, app| match event {
ClickEvent::Mouse(click) if click.down.button == ui::MouseButton::Middle => {
app.stop_propagation();
this.run(std::slice::from_ref(&id), &DocAction::NewTab, app);
}
// The browser back and forward buttons keep their navigation meaning.
ClickEvent::Mouse(click) if click.down.button != ui::MouseButton::Right => {}
_ => menu(event, window, app),
}
}
fn new_doc(
&self,
mode: Option<DocMode>,
) -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static {
let this = self.clone();
move |_, _, app| {
app.stop_propagation();
this.state.update(app, |state, cx| {
state.popup = None;
cx.notify();
});
this.shell.update(app, |shell, cx| {
let Some(index) = this.location.pane_index(shell) else {
return;
};
shell.sync_editors(cx);
shell.state.split.focus_pane(index);
let mode = mode
.unwrap_or_else(|| crate::settings_modal::new_doc_default_mode(&shell.state));
shell.state.create_new_doc(mode);
cx.notify();
});
}
@@ -200,9 +323,11 @@ impl Controls {
enum DocAction {
Open,
NewTab,
Peek,
Split,
Trash,
Duplicate,
Favorite,
Tag(String),
}
@@ -219,11 +344,18 @@ impl RenderOnce for DocsExplorer {
app,
|_, _| Destination::Docs,
);
let focus = window.use_keyed_state(location.key("desktop.explorer.focus"), app, |_, cx| {
cx.focus_handle()
});
let focus = focus.read(app).clone();
let prompt = TrashPrompt::keyed(location.key("desktop.explorer.trash_prompt"), window, app);
let controls = Controls {
shell: self.shell.clone(),
location,
state,
overview,
focus,
prompt,
};
let state = controls.state.read(app);
let palette = self.palette;
@@ -283,7 +415,32 @@ impl RenderOnce for DocsExplorer {
Vec::new()
};
let writable = !store.is_readonly_sqlite();
let escape = {
let state = controls.state.clone();
move |event: &ui::KeyDownEvent, window: &mut Window, app: &mut App| {
if event.keystroke.key != "escape" {
return;
}
let handled = state.update(app, |state, cx| {
// A first Escape closes the open menu, and a second one ends the selection.
let handled = state.popup.take().is_some() || {
let selecting = state.selecting;
state.leave_selection();
selecting
};
cx.notify();
handled
});
if handled {
window.prevent_default();
app.stop_propagation();
}
}
};
let mut root = div()
.id("desktop.explorer")
.track_focus(&controls.focus)
.on_key_down(escape)
.relative()
.flex()
.flex_col()
@@ -348,15 +505,75 @@ impl RenderOnce for DocsExplorer {
.snapshot("desktop.explorer.select", Some("desktop.workbench"))
.when(writable, |button| {
button.on_click(controls.change(|state, _| {
state.selecting = !state.selecting;
state.selected.clear();
if state.selecting {
state.leave_selection();
} else {
state.selecting = true;
}
state.popup = None;
}))
}),
);
)
.when(*on_route == DesktopRoute::AllDocs, |header| {
header.child(
div()
.pl(px(8.0))
.child(new_doc_button(&controls, palette, writable)),
)
});
}
let mut tag_menu = None;
let mut popup_menu = None;
let mut position = ui::point(px(0.0), px(0.0));
if let Some(popup) = &state.popup {
let tags = if matches!(popup.menu, Menu::Tag | Menu::TagSwitch(..)) {
store
.all_tags_with_counts()
.into_iter()
.map(|(tag, _, _)| {
let label = store.tag_label(&tag);
let color = super::resolve_tag_color(&tag, store, shell.state.theme);
(tag, label, color)
})
.collect()
} else {
Vec::new()
};
let favorite = match &popup.menu {
Menu::Row(id) => store.get_doc(id).is_some_and(|doc| doc.meta.is_favorite),
_ => false,
};
let menu = render_menu(
popup,
&controls,
palette,
(
writable,
window.viewport_size().width >= px(640.0),
favorite,
),
tags,
selected.clone(),
shell.state.theme,
app,
);
position = popup.position;
if matches!(popup.menu, Menu::TagSwitch(..)) {
tag_menu = Some(menu);
} else {
popup_menu = Some((&popup.menu, menu));
}
}
root = root.child(header);
if !overview && !matches!(on_route, DesktopRoute::AllDocs) {
if let DesktopRoute::Tag(tag) = on_route {
root = root.child(tag_breadcrumb(
tag,
&controls,
(palette, shell.state.theme),
store,
tag_menu,
));
} else if !overview && !matches!(on_route, DesktopRoute::AllDocs) {
root = root.child(
div()
.snapshot("desktop.explorer.heading", Some("desktop.workbench"))
@@ -379,7 +596,13 @@ impl RenderOnce for DocsExplorer {
.flex_wrap()
.items_center()
.gap(px(8.0))
.child(format!("{} selected", selected.len()))
.child({
let label = format!("{} selected", selected.len());
div()
.snapshot("desktop.explorer.selected", Some("desktop.workbench"))
.snapshot_text(label.clone())
.child(label)
})
.child(
button(
"desktop.explorer.select_all",
@@ -412,7 +635,7 @@ impl RenderOnce for DocsExplorer {
)
.snapshot("desktop.explorer.trash", Some("desktop.workbench"))
.when(!selected.is_empty(), |button| {
button.on_click(controls.doc_action(selected.clone(), DocAction::Trash))
button.on_click(controls.trash(selected.clone()))
}),
),
);
@@ -504,6 +727,7 @@ impl RenderOnce for DocsExplorer {
RowStyle::List { selecting }
};
let views = store.views();
let order = Rc::new(docs.iter().map(|doc| doc.id.clone()).collect::<Vec<_>>());
root.child(virtual_scroll(
scroll_key,
controls.location.key("desktop.explorer.scroll"),
@@ -511,33 +735,43 @@ impl RenderOnce for DocsExplorer {
.map(|doc| DocRowKey::explorer(doc, &views))
.collect(),
style,
move |keys, app| doc_row(keys, grid, writable, palette, &render_controls, app),
move |keys, app| {
doc_row(
keys,
(grid, writable),
&order,
palette,
&render_controls,
app,
)
},
))
};
if let Some(popup) = &state.popup {
let tags = if matches!(popup.menu, Menu::Tag) {
store
.all_tags_with_counts()
.into_iter()
.map(|(tag, _, _)| {
let label = store.tag_label(&tag);
(tag, label)
})
.collect()
} else {
Vec::new()
};
root = root.child(ui::deferred(ui::anchored().position(popup.position).child(
render_menu(
popup,
&controls,
palette,
(writable, window.viewport_size().width >= px(640.0)),
tags,
selected,
shell.state.theme,
),
)));
if let Some((popup, menu)) = popup_menu {
if !matches!(popup, Menu::TagSwitch(..)) {
root = root.child(ui::deferred(ui::anchored().position(position).child(menu)));
}
}
let on_trashed = {
let state = controls.state.clone();
move |trashed: &[String], app: &mut App| {
state.update(app, |state, cx| {
for id in trashed {
state.selected.remove(id);
}
cx.notify();
});
}
};
if let Some(prompt) = render_trash_prompt(
&controls.prompt,
&self.shell,
(palette, shell.state.theme),
window,
app,
on_trashed,
) {
root = root.child(prompt);
}
root.into_any_element()
}
@@ -0,0 +1,22 @@
//! Opening a document in a new tab: a browser tab on Web Desktop, an app tab elsewhere.
use crate::workbench::DesktopShellView;
pub(in crate::views_extra) fn open_in_new_tab(shell: &mut DesktopShellView, id: &str) {
// Web Desktop hides the app tab bar and leaves tabs to the browser.
#[cfg(target_arch = "wasm32")]
if shell.state.web_chrome {
let workspace = String::from(js_sys::encode_uri_component(
&shell.state.store.active_workspace().id,
));
let doc = String::from(js_sys::encode_uri_component(id));
shell.save_local_workspaces();
crate::wasm_entry::open_document_tab(
&format!("/desktop/?workspace={workspace}&doc={doc}"),
"_blank",
"noopener",
);
return;
}
shell.state.open_header_doc_in_new_tab(id);
}
@@ -1,3 +1,5 @@
use std::rc::Rc;
use affine_store::directory::DocMode;
use ui::{
AnyElement, App, BoxShadow, Div, FontWeight, InteractiveElement, IntoElement, ParentElement,
@@ -6,9 +8,10 @@ use ui::{
};
use ui_tokens::{ThemeMode, icons::MORE_VERTICAL};
use super::{Controls, DocAction, Menu};
use super::{Controls, DocAction, ExplorerState};
use crate::{
DOC_ICON_SVG, DesktopFlexExt, DesktopPalette, EDGELESS_ICON_SVG,
DOC_ICON_SVG, DesktopFlexExt, DesktopPalette, EDGELESS_ICON_SVG, STAR_FILLED_SVG,
STAR_ICON_SVG,
doc_store::{DesktopDocMeta, DocViews},
theme_color, theme_tokens_for,
views_extra::{
@@ -18,10 +21,47 @@ use crate::{
},
};
impl ExplorerState {
pub(super) fn leave_selection(&mut self) {
self.selecting = false;
self.selected.clear();
self.anchor = None;
}
/// Toggle every row from the anchor to `id` except the anchor itself, then move the anchor to
/// `id`. Without an anchor in `order`, toggle `id` alone.
pub(super) fn select_range(&mut self, order: &[String], id: &str) {
let anchor = self
.anchor
.as_deref()
.and_then(|anchor| order.iter().position(|row| row == anchor));
let (Some(anchor), Some(target)) = (anchor, order.iter().position(|row| row == id)) else {
self.toggle(id);
return;
};
for row in &order[anchor.min(target)..=anchor.max(target)] {
if *row == order[anchor] {
continue;
}
if !self.selected.remove(row) {
self.selected.insert(row.clone());
}
}
self.anchor = Some(id.to_owned());
}
pub(super) fn toggle(&mut self, id: &str) {
if !self.selected.remove(id) {
self.selected.insert(id.to_owned());
}
self.anchor = Some(id.to_owned());
}
}
pub(super) fn doc_row(
keys: &[DocRowKey],
grid: bool,
writable: bool,
(grid, writable): (bool, bool),
order: &Rc<Vec<String>>,
palette: DesktopPalette,
controls: &Controls,
app: &App,
@@ -37,14 +77,13 @@ pub(super) fn doc_row(
Some(doc_item(
doc,
(&views, &tag_color),
grid,
(grid, writable),
(
state.selecting && writable,
state.selected.contains(&doc.id),
),
palette,
theme,
controls,
(palette, theme),
(controls, order),
))
});
let Some(first) = cards.next() else {
@@ -80,16 +119,12 @@ pub(super) fn empty(label: &'static str, palette: DesktopPalette) -> Div {
fn doc_item(
doc: &DesktopDocMeta,
(views, tag_color): (&DocViews, &impl Fn(&str) -> u32),
grid: bool,
(grid, writable): (bool, bool),
(selecting, selected): (bool, bool),
palette: DesktopPalette,
theme: ThemeMode,
controls: &Controls,
(palette, theme): (DesktopPalette, ThemeMode),
(controls, order): (&Controls, &Rc<Vec<String>>),
) -> AnyElement {
let id = doc.id.clone();
let menu_id = id.clone();
let check_id = id.clone();
let aux_id = id.clone();
let identity = doc_identity(&id);
let group: SharedString = format!("desktop.explorer.hover.{identity}").into();
let icon = if doc.default_mode == DocMode::Edgeless {
@@ -106,17 +141,52 @@ fn doc_item(
.group(group.clone())
.min_w_0()
.cursor_pointer();
let mut base = if selecting {
base.on_click(controls.change(move |state, _| {
if !state.selected.remove(&check_id) {
state.selected.insert(check_id.clone());
}
}))
} else {
base.on_click(controls.doc_action(vec![id.clone()], DocAction::Open))
};
let mut base = base.on_click(controls.row_click(id.clone(), order.clone(), writable));
base.interactivity()
.on_aux_click(controls.open_popup(move || Menu::Row(aux_id.clone())));
.on_aux_click(controls.row_aux_click(id.clone()));
let hover_only = |mut element: ui::Stateful<Div>| {
element.style().visibility = Some(ui::Visibility::Hidden);
element.group_hover(group.clone(), |mut style| {
style.visibility = Some(ui::Visibility::Visible);
style
})
};
let star = div()
.id(("DesktopExplorerFavorite", identity))
.snapshot(
ui::snap_id!("desktop.explorer.favorite.{id}"),
Some("desktop.workbench"),
)
.size(px(28.0))
.flex_shrink(0.0)
.flex()
.items_center()
.justify_center()
.rounded(px(4.0))
.when(writable, |star| {
star.cursor_pointer()
.hover(move |style| style.bg(palette.hover_overlay))
.on_click(controls.doc_action(vec![id.clone()], DocAction::Favorite))
})
.child(
svg()
.data(if doc.is_favorite {
STAR_FILLED_SVG
} else {
STAR_ICON_SVG
})
.size(px(18.0))
.text_color(if doc.is_favorite {
palette.accent
} else {
palette.text_secondary
}),
);
let star = if doc.is_favorite {
star
} else {
hover_only(star)
};
let more = div()
.id(("DesktopExplorerMenu", identity))
.snapshot(
@@ -131,19 +201,17 @@ fn doc_item(
.rounded(px(4.0))
.cursor_pointer()
.hover(move |style| style.bg(palette.hover_overlay))
.group_hover(group, |mut style| {
style.visibility = Some(ui::Visibility::Visible);
style
})
.on_click(controls.open_popup(move || Menu::Row(menu_id.clone())))
.on_click(controls.open_popup({
let id = id.clone();
move || super::Menu::Row(id.clone())
}))
.child(
svg()
.data(MORE_VERTICAL.svg.as_bytes())
.size(px(18.0))
.text_color(palette.text_secondary),
);
let mut more = more;
more.style().visibility = Some(ui::Visibility::Hidden);
let more = hover_only(more);
let title = if doc.title.is_empty() {
"Untitled".to_string()
} else {
@@ -155,7 +223,17 @@ fn doc_item(
.gap(px(8.0))
.min_w_0()
.when(selecting, |row| {
row.child(selection_icon(selected, palette))
row.child(
div()
.flex_shrink(0.0)
.when(selected, |icon| {
icon.snapshot(
ui::snap_id!("desktop.explorer.selected.{id}"),
Some("desktop.workbench"),
)
})
.child(selection_icon(selected, palette)),
)
})
.child(
svg()
@@ -227,7 +305,7 @@ fn doc_item(
.border_color(hover_border)
.shadow([hover_shadow].into_iter().collect())
})
.child(title_row.child(more))
.child(title_row.child(star).child(more))
.child(
div()
.flex_1()
@@ -257,6 +335,7 @@ fn doc_item(
.child(title_row.flex_1().min_w(px(96.0)))
.child(tags)
.child(timestamp)
.child(star)
.child(more)
}
.into_any_element()
@@ -0,0 +1,353 @@
//! The `Search tags` field at the top of the tag switcher (`TagSelectorMenu`).
use std::ops::Range;
use blocksuite_editor::inline_input::{Utf16ImeBuffer, utf16_len, utf16_to_byte};
use ui::{
Bounds, ClipboardItem, Context, ElementInputHandler, Entity, EntityInputHandler, FocusHandle,
InteractiveElement, IntoElement, KeyDownEvent, MouseButton, ParentElement, Pixels, Point,
Render, ShapedLine, Styled, TextAlign, TextRun, UTF16Selection, Window, canvas, div, fill,
point, px, size, svg,
};
use ui_tokens::icons::SEARCH;
use super::ExplorerState;
use crate::DesktopPalette;
pub(super) struct TagSearch {
buffer: Utf16ImeBuffer,
pub(super) focus: FocusHandle,
palette: DesktopPalette,
bounds: Option<Bounds<Pixels>>,
/// The explorer filters the switcher rows by the query, so each edit renders it again.
explorer: Entity<ExplorerState>,
}
impl TagSearch {
pub(super) fn new(
focus: FocusHandle,
palette: DesktopPalette,
explorer: Entity<ExplorerState>,
) -> Self {
Self {
buffer: Utf16ImeBuffer::new(String::new(), false),
focus,
palette,
bounds: None,
explorer,
}
}
/// Whether `label` contains the query, ignoring case.
pub(super) fn matches(&self, label: &str) -> bool {
label
.to_lowercase()
.contains(&self.buffer.text().trim().to_lowercase())
}
fn changed(&self, window: &Window, cx: &mut Context<Self>) {
window.notify_text_input_changed(&self.focus);
window.notify_text_selection_changed(&self.focus);
self.explorer.update(cx, |_, cx| cx.notify());
cx.notify();
}
fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
let stroke = &event.keystroke;
let key = stroke.key.as_str();
let command = stroke.modifiers.platform || stroke.modifiers.control;
if self.buffer.composing() {
if key == "escape" {
self.buffer.cancel_preedit();
self.changed(window, cx);
window.prevent_default();
cx.stop_propagation();
}
return;
}
match key {
"c" | "x" if command => {
let selection = self.buffer.selected_text();
if !selection.is_empty() {
cx.write_to_clipboard(ClipboardItem::new_string(selection.to_owned()));
if key == "x" {
self.buffer.replace(None, "");
}
}
}
"v" if command => {
let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else {
// Web clipboard events deliver text through the input handler.
return;
};
self.buffer.replace(None, &text);
}
_ if self
.buffer
.key(key, stroke.modifiers.shift, command)
.is_some() => {}
// `Escape` reaches the explorer, which closes the switcher.
_ => return,
}
self.changed(window, cx);
window.prevent_default();
cx.stop_propagation();
}
fn line(&self, bounds: Bounds<Pixels>, window: &Window) -> InputLine {
let shown = self.buffer.display_text();
let (selection, reversed) = self.buffer.shown_selection();
let caret = if reversed {
selection.start
} else {
selection.end
};
let mut font = ui::font(ui_tokens::FONT_SANS);
font.fallbacks = Some(blocksuite_editor::default_font_fallbacks());
let empty = shown.is_empty();
let text = if empty {
"Search tags".to_owned()
} else {
shown
};
let run = TextRun {
len: text.len(),
font,
color: if empty {
self.palette.text_muted
} else {
self.palette.text_primary
},
background_color: None,
underline: None,
strikethrough: None,
};
let line = window
.text_system()
.shape_line(text.into(), px(14.0), &[run], None);
let x = line.x_for_index(utf16_to_byte(&line.text, caret));
let scroll = (x - (bounds.size.width - px(1.0)).max(px(0.0))).max(px(0.0));
InputLine {
line,
origin: point(bounds.origin.x - scroll, bounds.origin.y),
bounds,
empty,
}
}
}
struct InputLine {
line: ShapedLine,
origin: Point<Pixels>,
bounds: Bounds<Pixels>,
empty: bool,
}
impl InputLine {
fn index_at_x(&self, x: Pixels) -> usize {
if self.empty {
return 0;
}
let index = self.line.closest_index_for_x(x - self.origin.x);
utf16_len(&self.line.text[..index])
}
fn range_bounds(&self, range: Range<usize>) -> Bounds<Pixels> {
let x_at =
|index| self.origin.x + self.line.x_for_index(utf16_to_byte(&self.line.text, index));
let (start, end) = (x_at(range.start), x_at(range.end));
let right = self.bounds.right();
let left = start.min(end).clamp(
self.bounds.origin.x,
(right - px(1.0)).max(self.bounds.origin.x),
);
let width = end.max(start).max(left + px(1.0)).min(right) - left;
Bounds::new(
point(left, self.bounds.origin.y),
size(width, self.bounds.size.height),
)
}
}
impl Render for TagSearch {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (selection, _) = self.buffer.shown_selection();
let marked = self.buffer.marked_range();
let focused = self.focus.is_focused(window);
let entity = cx.entity();
let layout_entity = entity.clone();
let focus = self.focus.clone();
let palette = self.palette;
div()
.id("desktop.explorer.tag_search")
.snapshot("desktop.explorer.tag_search", Some("desktop.explorer.menu"))
.track_focus(&self.focus)
.flex()
.items_center()
.gap(px(8.0))
.h(px(30.0))
.px(px(8.0))
.cursor(ui::CursorStyle::IBeam)
.child(
svg()
.data(SEARCH.svg.as_bytes())
.size(px(16.0))
.flex_shrink(0.0)
.text_color(palette.text_secondary),
)
.child(
div()
.relative()
.flex_1()
.h(px(22.0))
.overflow_hidden()
.child(
canvas(
move |bounds, window, cx| layout_entity.read(cx).line(bounds, window),
move |bounds, layout, window, cx| {
entity.update(cx, |field, _| field.bounds = Some(bounds));
window.handle_input(
&focus,
ElementInputHandler::new(bounds, entity),
cx,
);
if !selection.is_empty() {
let bytes = utf16_to_byte(&layout.line.text, selection.start)
..utf16_to_byte(&layout.line.text, selection.end);
for rect in layout.line.selection_rects_for_range(bytes) {
window.paint_quad(fill(
Bounds::new(
point(
layout.origin.x + rect.origin.x,
bounds.origin.y,
),
size(rect.size.width, bounds.size.height),
),
palette.accent_soft,
));
}
}
let _ = layout.line.paint(
layout.origin,
bounds.size.height,
TextAlign::Left,
None,
window,
cx,
);
if let Some(range) = marked {
let mark = layout.range_bounds(range);
window.paint_quad(fill(
Bounds::new(
point(mark.origin.x, mark.bottom() - px(1.0)),
size(mark.size.width, px(1.0)),
),
palette.accent,
));
}
if focused && selection.is_empty() {
window.paint_quad(fill(
layout.range_bounds(selection),
palette.accent,
));
}
},
)
.size_full(),
),
)
.on_key_down(cx.listener(Self::key_down))
.on_mouse_down(
MouseButton::Left,
cx.listener(|this, event: &ui::MouseDownEvent, window, cx| {
this.focus.focus(window, cx);
if let Some(bounds) = this.bounds {
let index = this.line(bounds, window).index_at_x(event.position.x);
this.buffer.unmark();
this.buffer.move_caret(index, event.modifiers.shift);
this.changed(window, cx);
}
window.request_virtual_keyboard();
cx.stop_propagation();
}),
)
}
}
impl EntityInputHandler for TagSearch {
fn text_for_range(
&mut self,
range: Range<usize>,
adjusted: &mut Option<Range<usize>>,
_: &mut Window,
_: &mut Context<Self>,
) -> Option<String> {
let (text, range) = self.buffer.text_for_range(range);
*adjusted = Some(range);
Some(text)
}
fn selected_text_range(
&mut self,
_: bool,
_: &mut Window,
_: &mut Context<Self>,
) -> Option<UTF16Selection> {
let (range, reversed) = self.buffer.shown_selection();
Some(UTF16Selection { range, reversed })
}
fn marked_text_range(&self, _: &mut Window, _: &mut Context<Self>) -> Option<Range<usize>> {
self.buffer.marked_range()
}
fn unmark_text(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.buffer.unmark();
self.changed(window, cx);
}
fn replace_text_in_range(
&mut self,
range: Option<Range<usize>>,
text: &str,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.buffer.replace(range, text);
self.changed(window, cx);
}
fn replace_and_mark_text_in_range(
&mut self,
range: Option<Range<usize>>,
text: &str,
selected: Option<Range<usize>>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.buffer.mark(range, text, selected);
self.changed(window, cx);
}
fn bounds_for_range(
&mut self,
range: Range<usize>,
bounds: Bounds<Pixels>,
window: &mut Window,
_: &mut Context<Self>,
) -> Option<Bounds<Pixels>> {
Some(self.line(bounds, window).range_bounds(range))
}
fn character_index_for_point(
&mut self,
position: Point<Pixels>,
window: &mut Window,
_: &mut Context<Self>,
) -> Option<usize> {
let bounds = self.bounds?;
bounds
.contains(&position)
.then(|| self.line(bounds, window).index_at_x(position.x))
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,613 @@
mod panel;
mod tz;
use std::collections::BTreeSet;
use affine_client::nav::{LocationChoice, LocationRef};
use blocksuite_editor::{block_flow::civil_from_days, database::parse_date_input_ms};
use ui::{
App, ClickEvent, Context, Div, ElementId, Entity, FontWeight, InteractiveElement, IntoElement,
ParentElement, RenderOnce, SharedString, SnapshotId, Stateful, StatefulInteractiveElement,
Styled, Window, div, px, svg,
};
use ui_tokens::FONT_SANS;
use super::{PaneLocation, button, button_with_fill, max_width, vertical_scroll};
use crate::{
DesktopAppState, DesktopFlexExt, DesktopPalette, JOURNAL_ICON_SVG,
split_view::{DesktopRoute, PaneState},
workbench::DesktopShellView,
};
const DAY_MS: i64 = 86_400_000;
const MONTHS: [&str; 12] = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const WEEKDAYS: [&str; 7] = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
pub(crate) fn render_journals(
pane_idx: usize,
palette: DesktopPalette,
cx: &mut Context<DesktopShellView>,
) -> impl IntoElement {
ui::ViewElement::new(JournalPlaceholder {
pane_idx,
palette,
shell: cx.entity(),
})
}
fn iso_date(day: i64) -> String {
let (year, month, date) = civil_from_days(day);
format!("{year:04}-{month:02}-{date:02}")
}
fn parse_day(date: &str) -> Option<i64> {
let day = parse_date_input_ms(date, &|_| 0)?.div_euclid(DAY_MS);
(iso_date(day) == date).then_some(day)
}
fn weekday(day: i64) -> usize {
(day + 4).rem_euclid(7) as usize
}
fn week_start(day: i64) -> i64 {
day - weekday(day) as i64
}
fn month_start(day: i64) -> i64 {
day - i64::from(civil_from_days(day).2) + 1
}
fn next_month(day: i64) -> i64 {
month_start(month_start(day) + 32)
}
struct JournalPlaceholder {
pane_idx: usize,
palette: DesktopPalette,
shell: Entity<DesktopShellView>,
}
impl RenderOnce for JournalPlaceholder {
fn render(self, _: &mut Window, app: &mut App) -> impl IntoElement {
let shell = self.shell.read(app);
let Some(location) = PaneLocation::read(shell, self.pane_idx) else {
return div().into_any_element();
};
let date = shell
.state
.journal_date(&shell.state.split.panes[self.pane_idx]);
let Some(day) = parse_day(date) else {
return div().child("Journal date unavailable.").into_any_element();
};
let palette = self.palette;
let writable = !shell.state.store.is_readonly_sqlite();
let create = button_with_fill(
"desktop.journals.create",
if date == shell.state.today_date {
"Create today's journal"
} else {
"Create journal"
},
palette,
writable,
Some(palette.accent),
)
.snapshot("desktop.journals.create", Some("desktop.journals.view"));
let create = if writable {
let date = date.to_owned();
create.on_click(journal_action(&self.shell, &location, move |state| {
state.create_journal(&date);
}))
} else {
create
};
let (year, month, number) = civil_from_days(day);
let scroll_key = location.key("desktop.journals.scroll");
let mut placeholder = div()
.h(px(200.0))
.border_1()
.border_color(palette.border)
.rounded(px(8.0))
.flex()
.flex_col()
.items_center()
.justify_center()
.gap(px(12.0))
.child(
div()
.size(px(36.0))
.rounded(px(18.0))
.bg(palette.bg_pill)
.flex()
.items_center()
.justify_center()
.child(
svg()
.data(JOURNAL_ICON_SVG)
.size(px(20.0))
.text_color(palette.text_secondary),
),
)
.child(
div()
.text_size(px(14.0))
.text_color(palette.text_muted)
.child("No journal for this day"),
)
.child(create);
placeholder.style().border_style = Some(ui::BorderStyle::Dashed);
let body = max_width(div().w_full(), px(944.0))
.p(px(32.0))
.flex()
.flex_col()
.gap(px(28.0))
.child(
div()
.text_size(px(40.0))
.font_weight(FontWeight::BOLD)
.child(format!(
"{}, {} {number}, {year}",
WEEKDAYS[weekday(day)],
MONTHS[month as usize - 1],
)),
)
.child(placeholder);
div()
.id("desktop.journals.view")
.snapshot("desktop.journals.view", Some("desktop.workbench"))
.flex()
.flex_col()
.size_full()
.font_family(FONT_SANS)
.text_color(palette.text_primary)
.child(vertical_scroll(
scroll_key,
div().flex().justify_center().w_full().child(body),
))
.into_any_element()
}
}
fn journal_action<F: Fn(&mut DesktopAppState) + 'static>(
shell: &Entity<DesktopShellView>,
location: &PaneLocation,
action: F,
) -> impl Fn(&ClickEvent, &mut Window, &mut App) + use<F> {
let shell = shell.clone();
let location = location.clone();
move |_, _, app| {
shell.update(app, |shell, cx| {
if let Some(pane) = location.pane_index(shell) {
shell.sync_editors(cx);
shell.state.split.focus_pane(pane);
action(&mut shell.state);
cx.notify();
}
});
}
}
impl DesktopAppState {
pub(crate) fn journal_date<'a>(&'a self, pane: &'a PaneState) -> &'a str {
if let Some(id) = pane.active_route().doc_id()
&& let Some(date) = self
.store
.get_doc(id)
.and_then(|e| e.meta.journal_date.as_deref())
{
return date;
}
if pane.active_route() == &DesktopRoute::Journals
&& let Some(LocationChoice::Location(LocationRef::JournalDate(date))) =
pane.history.current().and_then(|entry| entry.pick.as_ref())
{
return date;
}
&self.today_date
}
}
impl DesktopShellView {
pub(crate) fn journal_week_picker(
pane_idx: usize,
width: f32,
show_doc_today: bool,
split_visible: bool,
palette: DesktopPalette,
cx: &Context<Self>,
) -> impl IntoElement + use<> {
// Keep one pixel between the split indicator and the calendar after layout snapping.
div()
.min_w_0()
.pt(px(if split_visible { 2.0 } else { 0.0 }))
.overflow_hidden()
.child(ui::ViewElement::new(CalendarView {
kind: CalendarKind::Week {
pane_idx,
width,
show_doc_today,
},
palette,
shell: cx.entity(),
}))
}
}
pub(super) fn journal_month_picker(
palette: DesktopPalette,
cx: &Context<DesktopShellView>,
) -> impl IntoElement + use<> {
ui::ViewElement::new(CalendarView {
kind: CalendarKind::Month,
palette,
shell: cx.entity(),
})
}
enum CalendarKind {
Week {
pane_idx: usize,
width: f32,
show_doc_today: bool,
},
Month,
}
struct CalendarView {
kind: CalendarKind,
palette: DesktopPalette,
shell: Entity<DesktopShellView>,
}
impl RenderOnce for CalendarView {
fn render(self, window: &mut Window, app: &mut App) -> impl IntoElement {
let shell = self.shell.read(app);
let (index, width, prefix) = match self.kind {
CalendarKind::Week {
pane_idx, width, ..
} => {
let prefix = if pane_idx == 0 {
String::from("desktop.topbar")
} else {
format!("desktop.pane.{pane_idx}.topbar")
};
(pane_idx, width, prefix)
}
CalendarKind::Month => (
shell.state.split.active_pane,
0.0,
"desktop.inspector.journal".into(),
),
};
let Some(location) = PaneLocation::read(shell, index) else {
return div().into_any_element();
};
let pane = &shell.state.split.panes[index];
let Some(today) = parse_day(&shell.state.today_date) else {
return div().into_any_element();
};
let placeholder = pane.active_route() == &DesktopRoute::Journals;
let selected = parse_day(shell.state.journal_date(pane)).unwrap_or(today);
let key: SharedString = format!("{}.{selected}", location.key(&prefix)).into();
let cursor = window.use_keyed_state(key, app, |_, _| selected);
let day = *cursor.read(app);
let shell = self.shell.read(app);
let palette = self.palette;
let (_, month_number, _) = civil_from_days(day);
let select = |target| {
journal_action(&self.shell, &location, move |state| {
state.select_journal_date(&iso_date(target))
})
};
let browse = |target| {
let cursor = cursor.clone();
move |_: &ClickEvent, _: &mut Window, app: &mut App| {
cursor.update(app, |cursor, cx| {
*cursor = target;
cx.notify();
});
}
};
let control = |id: ElementId, snapshot: SnapshotId, label, enabled| {
button(id, label, palette, enabled).snapshot(snapshot, None)
};
if let CalendarKind::Week { show_doc_today, .. } = self.kind {
let show_today = if placeholder {
selected != today && width >= 120.0
} else {
show_doc_today
};
let size_factor = ((width - 180.0) / 180.0).clamp(0.0, 1.0);
let cell_width = (20.0 + 14.0 * size_factor).floor();
let arrow_width = (14.0 + 10.0 * size_factor).floor();
let today_width = (46.0 + 8.0 * size_factor).floor();
let gap = 2.0;
let reserve =
2.0 * arrow_width + gap + if show_today { today_width + gap } else { 0.0 };
let count = (((width - reserve) / (cell_width + gap)) as i64).clamp(1, 7);
let start = week_start(day);
let first = (day - count / 2).clamp(start, start + 7 - count);
let browse_step = |direction: i64| {
if count == 7 {
day + 7 * direction
} else if direction < 0 && first == start {
start - count + count / 2
} else if direction > 0 && first + count == start + 7 {
start + 7 + count / 2
} else {
(day + count * direction).clamp(start, start + 6)
}
};
let week = div()
.id(("calendar-week", index))
.snapshot(ui::snap_id!("{prefix}.journal_week"), None)
.flex()
.items_center()
.gap(px(gap))
.child(
control(
"calendar-back".into(),
ui::snap_id!("{prefix}.journal_previous"),
"‹",
true,
)
.px(px(0.0))
.w(px(arrow_width))
.on_click(browse(browse_step(-1))),
)
.children((first..first + count).map(|target| {
let label =
&WEEKDAYS[weekday(target)][..if cell_width >= 30.0 { 3 } else { 1 }];
let date = civil_from_days(target).2;
day_button(
ui::snap_id!("{prefix}.day.{}", iso_date(target)),
target,
selected,
today,
true,
palette,
)
.w(px(cell_width))
.h(px(38.0))
.child(div().text_size(px(10.0)).child(label))
.child(date.to_string())
.on_click(select(target))
}))
.child(
control(
"calendar-forward".into(),
ui::snap_id!("{prefix}.journal_next"),
"›",
true,
)
.px(px(0.0))
.w(px(arrow_width))
.on_click(browse(browse_step(1))),
);
let mut row = div()
.min_w_0()
.flex()
.items_center()
.gap(px(gap))
.child(week);
if show_today {
let enabled = placeholder
|| !shell.state.store.is_readonly_sqlite()
|| shell
.state
.journal_doc_id(&shell.state.today_date)
.is_some();
let today_button = control(
("calendar-week-today", index).into(),
ui::snap_id!("{prefix}.today"),
"Today",
enabled,
)
.px(px(0.0))
.w(px(today_width));
row = row.child(if enabled {
today_button.on_click(journal_action(&self.shell, &location, move |state| {
if placeholder {
state.select_journal_date(&state.today_date.clone());
} else {
state.replace_with_today_journal();
}
}))
} else {
today_button
});
}
return row.into_any_element();
}
let activity = panel::Activity::cached(&location, &self.shell, window, app);
let shell = self.shell.read(app);
let (year, _, _) = civil_from_days(day);
let title = format!("{} {year}", MONTHS[month_number as usize - 1]);
let theme = shell.state.theme;
let journal_dates: BTreeSet<String> = shell
.state
.store
.docs
.values()
.filter(|entry| !entry.meta.trashed)
.filter_map(|entry| entry.meta.journal_date.clone())
.collect();
let reset_month = browse(today);
let select_today = select(today);
let previous = month_start(month_start(day) - 1);
let next = next_month(day);
let start = week_start(month_start(day));
let end = week_start(next - 1) + 7;
let calendar = div()
.flex()
.flex_col()
.gap(px(4.0))
.text_color(palette.text_primary)
.child(
div()
.flex()
.items_center()
.gap(px(4.0))
.child(
div()
.flex_1()
.truncate()
.font_weight(FontWeight::SEMIBOLD)
.child(title),
)
.child(
control(
"calendar-month-back".into(),
ui::snap_id!("desktop.inspector.journal.previous"),
"‹",
true,
)
.on_click(browse(previous)),
)
.child(
control(
"calendar-month-today".into(),
ui::snap_id!("desktop.inspector.journal.today"),
"Today",
true,
)
.on_click(move |event, window, app| {
reset_month(event, window, app);
select_today(event, window, app);
}),
)
.child(
control(
"calendar-month-forward".into(),
ui::snap_id!("desktop.inspector.journal.next"),
"›",
true,
)
.on_click(browse(next)),
),
)
.child(div().flex().gap(px(4.0)).children(WEEKDAYS.map(|label| {
div()
.flex_1()
.min_w_0()
.flex()
.justify_center()
.text_size(px(11.0))
.text_color(palette.text_secondary)
.child(&label[..3])
})))
.children((start..end).step_by(7).map(|week| {
div()
.flex()
.gap(px(4.0))
.children((week..week + 7).map(|target| {
let (_, target_month, number) = civil_from_days(target);
let in_month = target_month == month_number;
let date = iso_date(target);
let dots = (
journal_dates.contains(&date),
activity.dates.contains(&date),
);
day_button(
ui::snap_id!("desktop.inspector.journal.day.{date}"),
target,
selected,
today,
in_month,
palette,
)
.flex_1()
.min_w_0()
.h(px(36.0))
.child(number.to_string())
.gap(px(2.0))
.child(panel::date_dots(&date, dots, target == selected, theme))
.on_click(select(target))
}))
}));
let panel = panel::journal_panel(
selected,
&activity,
&self.shell,
&location,
palette,
window,
app,
);
div()
.flex()
.flex_col()
.gap(px(16.0))
.child(calendar)
.child(panel)
.into_any_element()
}
}
fn day_button(
snapshot: SnapshotId,
day: i64,
selected: i64,
today: i64,
in_month: bool,
palette: DesktopPalette,
) -> Stateful<Div> {
div()
.id(("calendar-date", day as u64))
.snapshot(snapshot, None)
.flex()
.flex_col()
.items_center()
.justify_center()
.rounded(px(6.0))
.tab_stop(true)
.cursor_pointer()
.hover(move |style| {
style.bg(if day == selected {
palette.accent
} else {
palette.hover_color
})
})
.focus_visible(move |style| style.border_1().border_color(palette.accent))
.bg(if day == selected {
palette.accent
} else {
ui::transparent_black()
})
.text_size(px(13.0))
.text_color(if day == selected {
ui::white()
} else if day == today {
palette.accent
} else if in_month {
palette.text_primary
} else {
palette.text_muted
})
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,591 @@
//! What the Journal tab of the right sidebar shows under its month calendar: the journals that
//! share the selected date, and the documents created or updated on that date.
use std::{
collections::{BTreeSet, HashMap},
rc::Rc,
};
use affine_store::directory::{DocId, DocMode, DocQuery};
use ui::{
AnyElement, App, ClickEvent, Div, Entity, FontWeight, InteractiveElement, IntoElement,
ParentElement, SharedString, StatefulInteractiveElement, Styled, Window, div,
prelude::FluentBuilder as _, px, svg,
};
use ui_tokens::ThemeMode;
use super::{DAY_MS, iso_date, tz::LocalZone};
use crate::{
DOC_ICON_SVG, DesktopFlexExt, DesktopPalette, EDGELESS_ICON_SVG, JOURNAL_ICON_SVG,
TRASH_ICON_SVG,
doc_store::DesktopDocStore,
split_view::DesktopRoute,
theme_color, theme_tokens_for,
views_extra::{
PaneLocation,
docs_explorer::{TrashPrompt, open_in_new_tab, render_trash_prompt},
normalize_timestamp,
},
workbench::DesktopShellView,
};
/// `MAX_CONFLICT_COUNT` of the web panel: more journals of one date fold under a toggle.
const MAX_CONFLICTS: usize = 5;
/// Created and updated times of the documents outside Trash, with their local calendar days.
pub(super) struct Activity {
/// The workspace and metadata revision that the times come from.
key: (String, u64),
created: Vec<(String, i64, i64)>,
updated: Vec<(String, i64, i64)>,
/// Days on which a document was created or updated, for the second calendar dot.
pub(super) dates: BTreeSet<String>,
}
impl Activity {
fn key(store: &DesktopDocStore) -> (String, u64) {
(store.active_workspace().id.clone(), store.derived.meta_rev)
}
/// Read the times of `store`. `offset` gives the minutes that the local calendar runs ahead
/// of UTC at a time.
pub(super) fn read(store: &DesktopDocStore, offset: impl Fn(i64) -> i32) -> Self {
let created_at: HashMap<DocId, i64> = store
.directory
.query_docs(&DocQuery::default(), None)
.map(|page| {
page.entries
.into_iter()
.filter_map(|entry| {
Some((entry.id, normalize_timestamp(entry.create_date_ms)?))
})
.collect()
})
.unwrap_or_default();
let day = |ms: i64| {
ms.saturating_add(i64::from(offset(ms)) * 60_000)
.div_euclid(DAY_MS)
};
let mut activity = Self {
key: Self::key(store),
created: Vec::new(),
updated: Vec::new(),
dates: BTreeSet::new(),
};
for entry in store.docs.values().filter(|entry| !entry.meta.trashed) {
let id = &entry.meta.id;
if let Some(&ms) = DocId::new(id.as_str())
.ok()
.and_then(|doc| created_at.get(&doc))
{
activity.created.push((id.clone(), ms, day(ms)));
}
if let Some(ms) = normalize_timestamp(entry.meta.updated_at_ms) {
activity.updated.push((id.clone(), ms, day(ms)));
}
}
activity.dates = activity
.created
.iter()
.chain(&activity.updated)
.map(|&(_, _, day)| iso_date(day))
.collect();
activity
}
/// The activity of the pane, read again only when the workspace or its metadata changed.
pub(super) fn cached(
location: &PaneLocation,
shell: &Entity<DesktopShellView>,
window: &mut Window,
app: &mut App,
) -> Rc<Self> {
let state = panel_state(location, window, app);
let store = &shell.read(app).state.store;
if let Some(activity) = state
.read(app)
.activity
.clone()
.filter(|activity| activity.key == Self::key(store))
{
return activity;
}
let activity = Rc::new({
let zone = LocalZone::system();
Self::read(store, |ms| zone.offset_minutes(ms))
});
state.update(app, |state, _| state.activity = Some(activity.clone()));
activity
}
/// Documents of `field` on `day`, most recent first.
fn on(&self, field: Field, day: i64) -> Vec<String> {
let list = match field {
Field::Created => &self.created,
Field::Updated => &self.updated,
};
let mut docs: Vec<_> = list.iter().filter(|entry| entry.2 == day).collect();
docs.sort_by(|(a, a_ms, _), (b, b_ms, _)| b_ms.cmp(a_ms).then_with(|| a.cmp(b)));
docs.into_iter().map(|(id, ..)| id.clone()).collect()
}
}
#[derive(Clone, Copy, Default, PartialEq, Eq)]
enum Field {
#[default]
Created,
Updated,
}
#[derive(Default)]
struct PanelState {
field: Field,
show_all_conflicts: bool,
activity: Option<Rc<Activity>>,
}
fn panel_state(location: &PaneLocation, window: &mut Window, app: &mut App) -> Entity<PanelState> {
window.use_keyed_state(
location.tab_key("desktop.inspector.journal.panel"),
app,
|_, _| PanelState::default(),
)
}
pub(super) fn journal_panel(
day: i64,
activity: &Activity,
shell: &Entity<DesktopShellView>,
location: &PaneLocation,
palette: DesktopPalette,
window: &mut Window,
app: &mut App,
) -> Div {
let state = panel_state(location, window, app);
let prompt = TrashPrompt::keyed(
location.tab_key("desktop.inspector.journal.trash_prompt"),
window,
app,
);
let view = shell.read(app);
let theme = view.state.theme;
let date = iso_date(day);
let journals: Vec<String> = view
.state
.store
.docs
.values()
.filter(|entry| !entry.meta.trashed && entry.meta.journal_date.as_deref() == Some(&date))
.map(|entry| entry.meta.id.clone())
.collect();
let current = view
.state
.split
.active()
.active_route()
.doc_id()
.map(str::to_owned);
let panel = state.read(app);
let field = panel.field;
let mut root = div().flex().flex_col().gap(px(16.0)).w_full();
if journals.len() > 1 {
let writable = !view.state.store.is_readonly_sqlite();
let shown = if panel.show_all_conflicts {
journals.len()
} else {
MAX_CONFLICTS
};
let more = journals.len().saturating_sub(shown);
let mut block = div()
.snapshot(
"desktop.inspector.journal.conflict",
Some("desktop.inspector"),
)
.flex()
.flex_col()
.gap(px(4.0));
for id in journals.iter().take(shown) {
let trash = div()
.id(SharedString::from(format!("journal-conflict-trash-{id}")))
.snapshot(
ui::snap_id!("desktop.inspector.journal.conflict.trash.{id}"),
Some("desktop.inspector.journal.conflict"),
)
.size(px(24.0))
.flex()
.flex_shrink(0.0)
.items_center()
.justify_center()
.rounded(px(4.0))
.map(|button| {
if writable {
let ids = vec![id.clone()];
let prompt = prompt.clone();
button
.cursor_pointer()
.hover(move |style| style.bg(palette.hover_color))
.on_click(move |_, window, app| {
app.stop_propagation();
TrashPrompt::open(&prompt, ids.clone(), None, window, app);
})
} else {
button.opacity(0.55)
}
})
.child(
svg()
.data(TRASH_ICON_SVG)
.size(px(16.0))
.text_color(palette.text_secondary),
);
block = block.child(
doc_item(
id,
"conflict.item",
current.as_deref() == Some(id.as_str()),
(shell, location),
palette,
app,
)
.child(duplicate_tag(theme))
.child(trash),
);
}
if more > 0 {
block = block.child(
div()
.id("journal-conflict-more")
.snapshot(
"desktop.inspector.journal.conflict.more",
Some("desktop.inspector.journal.conflict"),
)
.flex()
.items_center()
.h(px(30.0))
.px(px(8.0))
.rounded(px(4.0))
.cursor_pointer()
.text_size(px(14.0))
.text_color(palette.text_secondary)
.hover(move |style| style.bg(palette.hover_color))
.child(format!("{more} more articles"))
.on_click({
let state = state.clone();
move |_, _, app| {
state.update(app, |state, cx| {
state.show_all_conflicts = true;
cx.notify();
});
}
}),
);
}
root = root.child(block);
}
let created = activity.on(Field::Created, day);
let updated = activity.on(Field::Updated, day);
let tokens = theme_tokens_for(theme);
let selected_bg = theme_color(
tokens,
"--affine-background-tertiary-color",
tokens.background_secondary,
);
let tab = |target: Field, label: &str, count: usize| {
let active = field == target;
let name = match target {
Field::Created => "created",
Field::Updated => "updated",
};
let state = state.clone();
div()
.id(SharedString::from(format!("journal-tab-{name}")))
.snapshot(
ui::snap_id!("desktop.inspector.journal.tab.{name}"),
Some("desktop.inspector"),
)
.flex_1()
.min_w_0()
.h(px(28.0))
.px(px(8.0))
.flex()
.items_center()
.justify_center()
.gap(px(4.0))
.rounded(px(8.0))
.cursor_pointer()
.text_size(px(14.0))
.font_weight(FontWeight::MEDIUM)
.text_color(if active {
palette.text_primary
} else {
palette.text_secondary
})
.bg(if active {
selected_bg
} else {
ui::transparent_black()
})
.hover(move |style| {
if active {
style
} else {
style.bg(palette.hover_color)
}
})
.child(label.to_owned())
.child(if count > 99 {
"99+".to_string()
} else {
count.to_string()
})
.on_click(move |_, _, app| {
state.update(app, |state, cx| {
state.field = target;
cx.notify();
});
})
};
let list = match field {
Field::Created => &created,
Field::Updated => &updated,
};
let mut items = div().flex().flex_col().gap(px(4.0));
if list.is_empty() {
items = items.child(
div()
.snapshot(
"desktop.inspector.journal.activity.empty",
Some("desktop.inspector"),
)
.flex()
.justify_center()
.px(px(24.0))
.py(px(32.0))
.text_size(px(15.0))
.line_height(px(24.0))
.text_color(palette.text_secondary)
.child(match field {
Field::Created => "You haven't created anything yet",
Field::Updated => "You haven't updated anything yet",
}),
);
}
for id in list {
items = items.child(doc_item(
id,
"activity",
false,
(shell, location),
palette,
app,
));
}
root = root.child(
div()
.flex()
.flex_col()
.gap(px(8.0))
.child(
div()
.flex()
.items_center()
.gap(px(8.0))
.child(tab(Field::Created, "Created", created.len()))
.child(tab(Field::Updated, "Updated", updated.len())),
)
.child(items),
);
if let Some(prompt) =
render_trash_prompt(&prompt, shell, (palette, theme), window, app, |_, _| {})
{
root = root.child(prompt);
}
root
}
/// The `PageItem` row of the web panel: opens the document in the active pane, or in a new tab
/// with `Cmd/Ctrl`.
fn doc_item(
id: &str,
kind: &str,
current: bool,
(shell, location): (&Entity<DesktopShellView>, &PaneLocation),
palette: DesktopPalette,
app: &App,
) -> ui::Stateful<Div> {
let state = &shell.read(app).state;
let icon = match state.store.get_doc(id).map(|entry| &entry.meta) {
Some(meta) if meta.journal_date.is_some() => JOURNAL_ICON_SVG,
Some(meta) if meta.default_mode == DocMode::Edgeless => EDGELESS_ICON_SVG,
_ => DOC_ICON_SVG,
};
let title = state.route_title(&DesktopRoute::Doc(id.to_owned()));
let open = {
let shell = shell.clone();
let location = location.clone();
let id = id.to_owned();
move |event: &ClickEvent, _: &mut Window, app: &mut App| {
let modifiers = event.modifiers();
shell.update(app, |shell, cx| {
let Some(pane) = location.pane_index(shell) else {
return;
};
shell.sync_editors(cx);
shell.state.split.focus_pane(pane);
if modifiers.platform || modifiers.control {
open_in_new_tab(shell, &id);
} else {
shell.state.open_doc_in_active_pane(&id);
}
cx.notify();
});
}
};
let label = if current {
palette.accent
} else {
palette.text_primary
};
div()
.id(SharedString::from(format!("journal-{kind}-{id}")))
.snapshot(
ui::snap_id!("desktop.inspector.journal.{kind}.{id}"),
Some("desktop.inspector"),
)
.snapshot_text(title.clone())
.flex()
.items_center()
.gap(px(8.0))
.h(px(30.0))
.px(px(4.0))
.rounded(px(4.0))
.cursor_pointer()
.bg(if current {
palette.hover_color
} else {
ui::transparent_black()
})
.hover(move |style| style.bg(palette.hover_color))
.child(
svg()
.data(icon)
.size(px(20.0))
.flex_shrink(0.0)
.text_color(palette.text_secondary),
)
.child(
div()
.flex_1()
.min_w_0()
.truncate()
.text_size(px(14.0))
.font_weight(FontWeight::MEDIUM)
.text_color(label)
.child(title),
)
.on_click(open)
}
/// The red `Duplicated` tag beside each journal of a date that has more than one.
fn duplicate_tag(theme: ThemeMode) -> AnyElement {
let tokens = theme_tokens_for(theme);
div()
.flex_shrink(0.0)
.px(px(8.0))
.rounded(px(4.0))
.border_1()
.border_color(theme_color(
tokens,
"--affine-v2-database-border",
tokens.border,
))
.bg(theme_color(
tokens,
"--affine-v2-layer-background-error",
tokens.background_secondary,
))
.text_color(theme_color(
tokens,
"--affine-v2-toast-iconState-error",
tokens.primary,
))
.text_size(px(12.0))
.line_height(px(20.0))
.child("Duplicated")
.into_any_element()
}
/// The calendar dots of one date: a journal exists (blue), and a document was created or
/// updated (red). The selected date shows none.
pub(super) fn date_dots(
date: &str,
(journal, activity): (bool, bool),
selected: bool,
theme: ThemeMode,
) -> Div {
let tokens = theme_tokens_for(theme);
let dot = |kind: &str, token: &str| {
div()
.snapshot(
ui::snap_id!("desktop.inspector.journal.dot.{kind}.{date}"),
None,
)
.size(px(4.0))
.rounded(px(2.0))
.bg(theme_color(tokens, token, tokens.primary))
};
div()
.flex()
.justify_center()
.gap(px(4.0))
.h(px(4.0))
.when(!selected && journal, |dots| {
dots.child(dot("journal", "--affine-v2-calendar-blue"))
})
.when(!selected && activity, |dots| {
dots.child(dot("activity", "--affine-v2-calendar-red"))
})
}
#[cfg(test)]
mod tests {
use affine_store::directory::DocMode;
use ui_tokens::ThemeMode;
use super::{Activity, Field};
use crate::DesktopAppState;
#[test]
fn activity_days_follow_the_local_calendar_across_utc_midnight() {
// (zone, UTC time in ms, local day with the document, a zone that puts it on the day
// before)
let cases = [
// 2026-12-05 00:30 in Tokyo is 2026-12-04 15:30 UTC.
("Asia/Tokyo", 1_796_398_200_000, 20_792, "UTC"),
// 2026-07-15 00:30 and 2026-07-01 00:30 under daylight saving time of `Jn` rules
// are 23:30 on the day before under standard time alone.
("EST5EDT,J60/2,J300/2", 1_784_089_800_000, 20_649, "EST5"),
("EST5EDT,J60/2,J305/2", 1_782_880_200_000, 20_635, "EST5"),
];
for (tz, ms, day, earlier) in cases {
let other = day - 1;
let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-05");
let id = state.store.create_doc("Late note", DocMode::Page, None, ms);
let zone = super::LocalZone::from_tz(Some(tz));
let activity = Activity::read(&state.store, |ms| zone.offset_minutes(ms));
for field in [Field::Created, Field::Updated] {
assert!(activity.on(field, day).contains(&id), "{tz}");
assert!(!activity.on(field, other).contains(&id), "{tz}");
}
assert!(activity.dates.contains(&super::iso_date(day)), "{tz}");
assert!(!activity.dates.contains(&super::iso_date(other)), "{tz}");
let earlier_zone = super::LocalZone::from_tz(Some(earlier));
let activity = Activity::read(&state.store, |ms| earlier_zone.offset_minutes(ms));
assert!(
activity.on(Field::Created, other).contains(&id),
"{tz} in {earlier}"
);
}
}
}
@@ -0,0 +1,781 @@
use std::path::PathBuf;
use affine_store::directory::DocMode;
use ui::{
AppContext, Application, ApplicationHandle, Bounds, FrameSnapshot, HeadlessPlatform,
HeadlessWindow, WindowBounds, WindowHandle, WindowOptions, point, size,
};
use ui_tokens::ThemeMode;
use super::*;
use crate::{register_desktop_fonts, sqlite_loader::SqliteLazyBacking};
const TODAY: &str = "2026-12-02";
const YESTERDAY: &str = "2026-12-01";
struct TestShell {
app: ApplicationHandle,
platform: std::rc::Rc<HeadlessPlatform>,
window: HeadlessWindow,
handle: WindowHandle<DesktopShellView>,
}
impl TestShell {
fn open(mut state: DesktopAppState, width: u32) -> Self {
state.web_chrome = true;
let platform = HeadlessPlatform::new(width, 800, 1.0);
let app = Application::with_platform(platform.clone()).run_embedded(|_| {});
let handle = app.update(|cx| {
register_desktop_fonts(cx).unwrap();
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::new(
point(px(0.0), px(0.0)),
size(px(width as f32), px(800.0)),
))),
..WindowOptions::default()
},
|_, cx| cx.new(|cx| DesktopShellView::new(state, cx)),
)
.unwrap()
});
let window = platform.windows().pop().unwrap();
Self {
app,
platform,
window,
handle,
}
}
fn resize(&self, width: u32, height: u32) {
let mut window = self.window.clone();
ui::PlatformWindow::resize(&mut window, size(px(width as f32), px(height as f32)));
}
fn split_journal(&self) {
self.click("desktop.topbar.more");
self.click("desktop.header.menu.split");
self.state(|state| assert_eq!(state.split.panes.len(), 2));
}
fn frame(&self) -> FrameSnapshot {
self.platform.run_until_parked();
self.app.update(|cx| {
self.handle
.update(cx, |_, window, _| window.refresh())
.unwrap()
});
self.window.request_frame();
self.app.update(|cx| {
self.handle
.update(cx, |_, window, _| window.frame_snapshot().clone())
.unwrap()
})
}
#[track_caller]
fn click(&self, id: &str) {
let snapshot = self.frame();
let button = snapshot.elements.get(id).unwrap_or_else(|| {
panic!(
"missing {id}, available elements: {:?}",
snapshot.elements.keys()
)
});
assert!(button.interactive, "{id} must accept clicks");
let bounds = button.bounds;
self.window.simulate_click(point(
px(bounds.x + bounds.width * 0.5),
px(bounds.y + bounds.height * 0.5),
));
self.frame();
}
fn state<R>(&self, action: impl FnOnce(&mut DesktopAppState) -> R) -> R {
self.app.update(|cx| {
self.handle
.update(cx, |shell, _, cx| {
let result = action(&mut shell.state);
cx.notify();
result
})
.unwrap()
})
}
}
fn seeded(readonly: bool) -> DesktopAppState {
let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, TODAY);
if readonly {
mark_readonly(&mut state);
}
state
}
fn mark_readonly(state: &mut DesktopAppState) {
state.store.sqlite_backing = Some(SqliteLazyBacking::new(
PathBuf::from("readonly.affine"),
"ws-ro",
0,
));
}
fn assert_doc(shell: &TestShell, id: &str) {
shell.state(|state| assert_eq!(state.split.active().active_route().doc_id(), Some(id)));
}
#[test]
fn calendar_crosses_leap_days_and_years() {
for (date, week, next) in [
("2024-02-29", "2024-02-25", "2024-03-01"),
("2027-01-01", "2026-12-27", "2027-02-01"),
] {
let day = parse_day(date).unwrap();
assert_eq!(iso_date(week_start(day)), week);
assert_eq!(iso_date(next_month(day)), next);
}
assert!(parse_day("2026-02-29").is_none());
}
#[test]
fn journal_entry_points_open_the_same_existing_document_in_writable_and_readonly_workspaces() {
for readonly in [false, true] {
let mut state = seeded(false);
let yesterday =
state
.store
.create_doc("Yesterday", DocMode::Page, Some(YESTERDAY.into()), 1_000);
let first = state
.store
.create_doc("Today", DocMode::Page, Some(TODAY.into()), 1_001);
assert!(first.as_str() < "doc-journal-today");
if readonly {
mark_readonly(&mut state);
}
state.navigate_active_pane(DesktopRoute::AllDocs);
let shell = TestShell::open(state, 1280);
shell.click("desktop.sidebar.journals");
assert_doc(&shell, &first);
shell.state(|state| {
assert!(state.split.active_mut().go_back());
assert_eq!(state.split.active().active_route(), &DesktopRoute::AllDocs);
state.navigate_active_pane(DesktopRoute::Doc(yesterday.clone()));
});
shell.click("desktop.topbar.day.2026-12-02");
assert_doc(&shell, &first);
shell.state(|state| state.navigate_active_pane(DesktopRoute::Doc(yesterday.clone())));
shell.click("desktop.topbar.today");
assert_doc(&shell, &first);
shell.state(|state| state.navigate_active_pane(DesktopRoute::AllDocs));
shell.click("desktop.topbar.inspector_toggle");
shell.click("desktop.inspector.tab.journal");
shell.click("desktop.inspector.journal.day.2026-12-02");
assert_doc(&shell, &first);
}
}
#[test]
fn empty_journal_waits_for_create_and_never_writes_on_readonly() {
for readonly in [false, true] {
let mut state = seeded(readonly);
state.store.docs.remove("doc-journal-today");
state.navigate_active_pane(DesktopRoute::AllDocs);
let count = state.store.docs.len();
let clock = state.logical_clock_ms;
let shell = TestShell::open(state, 1280);
shell.click("desktop.sidebar.journals");
assert!(
shell
.frame()
.elements
.contains_key("desktop.topbar.journal_week")
);
shell.state(|state| {
assert_eq!(state.split.active().active_route(), &DesktopRoute::Journals);
assert_eq!(state.store.docs.len(), count);
assert_eq!(state.logical_clock_ms, clock);
});
shell.click("desktop.topbar.inspector_toggle");
shell.click("desktop.inspector.tab.journal");
shell.click("desktop.inspector.journal.next");
assert!(
shell
.frame()
.elements
.contains_key("desktop.inspector.journal.day.2027-01-01")
);
shell.click("desktop.inspector.journal.previous");
shell.click("desktop.inspector.journal.day.2026-12-03");
shell.state(|state| {
assert_eq!(state.journal_date(state.split.active()), "2026-12-03");
assert!(state.split.active_mut().go_back());
assert_eq!(state.journal_date(state.split.active()), TODAY);
});
shell.click("desktop.topbar.journal_previous");
assert!(
shell
.frame()
.elements
.contains_key("desktop.topbar.day.2026-11-25")
);
shell.click("desktop.topbar.journal_next");
shell.click("desktop.topbar.day.2026-12-01");
assert_eq!(
shell.state(|state| state.journal_date(state.split.active()).to_owned()),
YESTERDAY
);
assert!(shell.frame().elements["desktop.topbar.today"].interactive);
shell.click("desktop.topbar.today");
shell.state(|state| {
let pane = state.split.active();
assert_eq!(pane.active_route(), &DesktopRoute::Journals);
assert_eq!(state.journal_date(pane), TODAY);
assert_eq!(state.store.docs.len(), count);
});
assert_eq!(
shell.frame().elements["desktop.journals.create"].interactive,
!readonly
);
if readonly {
shell.state(|state| {
assert!(state.open_today_journal().is_empty());
assert_eq!(state.store.docs.len(), count);
});
} else {
shell.click("desktop.journals.create");
shell.state(|state| {
assert_eq!(state.store.docs.len(), count + 1);
assert_eq!(
state.split.active().active_route().doc_id(),
state.journal_doc_id(TODAY),
);
assert!(state.journal_doc_id(TODAY).is_some());
assert!(state.split.active_mut().go_back());
assert_eq!(state.journal_date(state.split.active()), YESTERDAY);
});
}
}
}
#[test]
fn document_header_today_replaces_history_and_respects_readonly() {
for (readonly, today_exists) in [(false, false), (true, false), (true, true)] {
let mut state = seeded(false);
if !today_exists {
state.store.docs.remove("doc-journal-today");
}
let yesterday =
state
.store
.create_doc("Yesterday", DocMode::Page, Some(YESTERDAY.into()), 1_000);
if readonly {
mark_readonly(&mut state);
}
state.navigate_active_pane(DesktopRoute::AllDocs);
state.navigate_active_pane(DesktopRoute::Doc(yesterday.clone()));
let count = state.store.docs.len();
let shell = TestShell::open(state, 1280);
let enabled = !readonly || today_exists;
assert_eq!(
shell.frame().elements["desktop.topbar.today"].interactive,
enabled
);
if enabled {
shell.click("desktop.topbar.today");
shell.state(|state| {
let today = state.journal_doc_id(TODAY).unwrap();
assert_eq!(state.split.active().active_route().doc_id(), Some(today));
assert_eq!(state.store.docs.len(), count + usize::from(!today_exists));
assert!(state.split.active_mut().go_back());
assert_eq!(state.split.active().active_route(), &DesktopRoute::AllDocs);
});
} else {
assert_doc(&shell, &yesterday);
}
}
}
#[test]
fn readonly_journal_split_indicator_focuses_the_right_pane_without_navigation() {
let mut state = seeded(false);
let yesterday =
state
.store
.create_doc("Yesterday", DocMode::Page, Some(YESTERDAY.into()), 1_000);
mark_readonly(&mut state);
state.navigate_active_pane(DesktopRoute::Doc(yesterday.clone()));
let shell = TestShell::open(state, 1280);
shell.state(|state| state.web_chrome = false);
shell.split_journal();
shell.resize(768, 800);
let frame = shell.frame();
let pane = frame.elements["desktop.pane.1"].bounds;
let dot = frame.elements["desktop.pane.1.topbar.split_indicator"].bounds;
assert_eq!((pane.x, pane.width), (508.0, 260.0));
let x = dot.x + dot.width / 2.0;
assert_eq!((x, dot.y), (638.0, 40.0));
for start in [0, 1] {
for y in [dot.y + dot.height / 2.0, 46.0] {
let history = shell.state(|state| {
state.split.focus_pane(start);
state.split.panes[1].history.clone()
});
shell.frame();
shell.window.simulate_click(point(px(x), px(y)));
shell.frame();
shell.state(|state| {
assert_eq!(state.split.active_pane, 1, "start={start}, y={y}");
assert_eq!(
state.split.active().active_route().doc_id(),
Some(yesterday.as_str())
);
assert_eq!(state.split.panes[1].history, history);
});
}
}
}
#[test]
fn journal_header_controls_fit_the_pane_and_keep_actions_available() {
for readonly in [false, true] {
for split_open in [false, true] {
for (width, sidebar_width) in [
(299, 0),
(300, 0),
(310, 0),
(320, 0),
(340, 0),
(359, 0),
(360, 0),
(390, 0),
(399, 0),
(400, 0),
(459, 0),
(460, 0),
(499, 0),
(500, 0),
(504, 0),
(524, 0),
(639, 0),
(640, 0),
(768, 0),
(768, 240),
(768, 248),
(1280, 0),
(1280, 248),
] {
let case = format!(
"window {width}px, sidebar {sidebar_width}px, readonly {readonly}, split {split_open}"
);
let mut state = seeded(false);
state.sidebar.open = sidebar_width > 0;
if sidebar_width > 0 {
state.sidebar.width = sidebar_width as f32;
}
let yesterday = state.store.create_doc(
"Yesterday",
DocMode::Page,
Some(YESTERDAY.into()),
1_000,
);
if readonly {
mark_readonly(&mut state);
}
state.navigate_active_pane(DesktopRoute::Doc(yesterday.clone()));
let shell = TestShell::open(state, 1280);
if split_open {
shell.split_journal();
}
shell.resize(width, 800);
assert_doc(&shell, &yesterday);
let active = shell.state(|state| state.split.active_pane);
let frame = shell.frame();
assert_eq!(
frame.elements.contains_key("desktop.topbar.sidebar_toggle"),
sidebar_width == 0,
"{case}"
);
let visible: Vec<_> = (0..=usize::from(split_open))
.filter(|index| {
frame
.elements
.contains_key(&format!("desktop.pane.{index}"))
})
.collect();
let folded = width < 640;
assert_eq!(
visible.len(),
1 + usize::from(split_open && !folded),
"{case}"
);
for (position, &index) in visible.iter().enumerate() {
let prefix = if index == 0 {
"desktop.topbar".into()
} else {
format!("desktop.pane.{index}.topbar")
};
let pane = frame.elements[&format!("desktop.pane.{index}")].bounds;
let pane_width = (width - sidebar_width) as f32 / visible.len() as f32;
assert_eq!(
pane.x,
sidebar_width as f32 + position as f32 * pane_width,
"{case}"
);
assert_eq!(pane.width, pane_width, "{case}");
assert_journal_header(
&frame,
&prefix,
pane,
[
("today", pane.width >= 300.0),
("more", true),
("inspector_toggle", position + 1 == visible.len()),
("close_split", split_open),
("share", !split_open && pane.width >= 500.0),
],
position == 0 && sidebar_width == 0,
readonly,
&case,
);
if split_open {
let indicator = frame.elements[&format!("{prefix}.split_indicator")].bounds;
assert_eq!(indicator.height, 6.0, "{case}");
let scope = format!("{prefix}.");
for (id, element) in &frame.elements {
let Some(name) = id.strip_prefix(scope.as_str()) else {
continue;
};
if name.starts_with("day.")
|| matches!(
name,
"journal_week" | "journal_previous" | "journal_next" | "today"
)
{
let bounds = element.bounds;
assert!(
indicator.right() <= bounds.x
|| bounds.right() <= indicator.x
|| indicator.bottom() <= bounds.y
|| bounds.bottom() <= indicator.y,
"{id} overlaps the split indicator: {case}"
);
}
}
}
}
let prefix = if active == 0 {
"desktop.topbar".into()
} else {
format!("desktop.pane.{active}.topbar")
};
if frame.elements.contains_key(&format!("{prefix}.today")) {
shell.click(&format!("{prefix}.today"));
assert!(
!shell.frame().elements.contains_key("desktop.header.menu"),
"Today opened More: {case}"
);
shell.state(|state| {
assert_eq!(state.split.active_pane, active, "{case}");
assert_eq!(
state.split.active().active_route().doc_id(),
Some("doc-journal-today"),
"{case}"
);
});
}
shell.click(&format!("{prefix}.more"));
let menu = shell.frame();
assert!(
menu.elements.contains_key("desktop.header.menu.favorite"),
"{case}"
);
assert!(
menu.elements.contains_key("desktop.header.menu.doc_info"),
"{case}"
);
}
}
}
}
fn assert_journal_header(
frame: &FrameSnapshot,
prefix: &str,
pane: ui::SnapshotRect,
actions: [(&str, bool); 5],
sidebar_toggle: bool,
readonly: bool,
case: &str,
) {
let elements = &frame.elements;
for (name, visible) in actions.into_iter().chain([
("journal_previous", true),
("journal_next", true),
("mode.page", true),
("mode.edgeless", true),
]) {
let id = format!("{prefix}.{name}");
assert_eq!(
elements.get(&id).map(|el| el.interactive),
visible.then_some(true),
"{id}: {case}"
);
}
let sidebar = "desktop.topbar.sidebar_toggle";
if sidebar_toggle {
assert!(elements[sidebar].interactive, "{case}");
}
assert_eq!(
elements.contains_key(&format!("{prefix}.readonly_sqlite_badge")),
readonly,
"{case}"
);
for name in ["favorite", "doc_info"] {
assert!(
!elements.contains_key(&format!("{prefix}.{name}")),
"{name}: {case}"
);
}
let fits = |outer: ui::SnapshotRect, inner: ui::SnapshotRect| {
inner.x >= outer.x - 0.5
&& inner.right() <= outer.right() + 0.5
&& inner.y >= outer.y - 0.5
&& inner.bottom() <= outer.bottom() + 0.5
};
let week = elements[&format!("{prefix}.journal_week")].bounds;
let mode = elements[&format!("{prefix}.mode_switch")].bounds;
let mut controls = Vec::new();
let mut days = 0;
for el in elements.values() {
let name = if el.id == sidebar {
if !sidebar_toggle {
continue;
}
"sidebar_toggle"
} else if let Some(name) = el
.id
.strip_prefix(prefix)
.and_then(|id| id.strip_prefix('.'))
{
name
} else {
continue;
};
assert!(
fits(pane, el.bounds),
"{} {:?} outside {pane:?}: {case}",
el.id,
el.bounds
);
assert!(
fits(el.content_mask, el.bounds),
"{} {:?} clipped by {:?}: {case}",
el.id,
el.bounds,
el.content_mask
);
if name.starts_with("day.") {
days += 1;
assert!(el.interactive && fits(week, el.bounds), "{}: {case}", el.id);
}
if name.starts_with("mode.") {
assert!(fits(mode, el.bounds), "{}: {case}", el.id);
}
if !matches!(name, "mode_switch" | "journal_week" | "split_indicator") {
controls.push(el);
}
}
assert!((1..=7).contains(&days), "{case}");
controls.sort_by(|a, b| a.bounds.x.total_cmp(&b.bounds.x));
for pair in controls.windows(2) {
assert!(
pair[0].bounds.right() <= pair[1].bounds.x + 0.5,
"{} overlaps {}: {case}",
pair[0].id,
pair[1].id,
);
}
}
#[test]
fn today_opens_the_first_journal_from_another_document_on_the_same_date() {
for readonly in [false, true] {
let mut state = seeded(false);
let other =
state
.store
.create_doc("Another journal", DocMode::Page, Some(TODAY.into()), 1_000);
let mut ids = ["doc-journal-today", &other];
ids.sort_unstable();
assert_eq!(state.journal_doc_id(TODAY), Some(ids[0]));
if readonly {
mark_readonly(&mut state);
}
state.navigate_active_pane(DesktopRoute::AllDocs);
state.navigate_active_pane(DesktopRoute::Doc(ids[1].into()));
let shell = TestShell::open(state, 500);
shell.click("desktop.topbar.today");
assert_doc(&shell, ids[0]);
shell.click("desktop.topbar.today");
assert_doc(&shell, ids[0]);
shell.state(|state| {
assert!(state.split.active_mut().go_back());
assert_eq!(state.split.active().active_route(), &DesktopRoute::AllDocs);
});
}
}
#[test]
fn picking_an_existing_journal_preserves_the_empty_date_in_single_and_split_history() {
for split in [false, true] {
let mut state = seeded(false);
state.store.docs.remove("doc-journal-today");
let yesterday =
state
.store
.create_doc("Yesterday", DocMode::Page, Some(YESTERDAY.into()), 1_000);
if split {
state.open_split_edgeless_for_active_doc();
assert_eq!(state.split.active_pane, 1);
}
state.navigate_active_pane(DesktopRoute::AllDocs);
state.select_journal_date(TODAY);
let shell = TestShell::open(state, 1280);
let topbar = if split {
"desktop.pane.1.topbar"
} else {
"desktop.topbar"
};
shell.click(&format!("{topbar}.inspector_toggle"));
shell.click("desktop.inspector.tab.journal");
shell.click("desktop.inspector.journal.day.2026-12-01");
assert_doc(&shell, &yesterday);
shell.state(|state| {
assert_eq!(state.split.active_pane, usize::from(split));
assert!(state.split.active_mut().go_back());
let pane = state.split.active();
assert_eq!(pane.active_route(), &DesktopRoute::Journals);
assert_eq!(state.journal_date(pane), TODAY);
});
}
}
#[test]
fn a_new_journal_replaces_the_placeholder_for_the_same_date() {
for reconcile in [false, true] {
let mut state = seeded(false);
state.store.docs.remove("doc-journal-today");
state.navigate_active_pane(DesktopRoute::AllDocs);
state.select_journal_date(TODAY);
let id = state
.store
.create_doc("Synced journal", DocMode::Page, Some(TODAY.into()), 1_000);
if reconcile {
state.reconcile_doc_routes();
} else {
state.select_journal_date(TODAY);
}
assert_eq!(
state.split.active().active_route().doc_id(),
Some(id.as_str())
);
assert!(state.split.active_mut().go_back());
assert_eq!(state.split.active().active_route(), &DesktopRoute::AllDocs);
}
}
#[test]
fn sqlite_readonly_badge_covers_document_and_non_document_topbars() {
for readonly in [false, true] {
let shell = TestShell::open(seeded(readonly), 1280);
for route in [
DesktopRoute::Doc("doc-arch".into()),
DesktopRoute::Doc("doc-journal-today".into()),
DesktopRoute::AllDocs,
DesktopRoute::Trash,
DesktopRoute::Journals,
DesktopRoute::Collection("col-rust-core".into()),
DesktopRoute::Tag("rust".into()),
DesktopRoute::Favorites,
] {
shell.state(|state| {
if route == DesktopRoute::Journals {
state.select_journal_date(YESTERDAY);
} else {
state.navigate_active_pane(route.clone());
}
assert_eq!(state.split.active().active_route(), &route);
});
let frame = shell.frame();
let badge = frame.elements.get("desktop.topbar.readonly_sqlite_badge");
assert_eq!(badge.is_some(), readonly, "{route:?}");
if let Some(badge) = badge {
assert!(!badge.interactive, "{route:?}");
}
}
}
}
#[test]
fn topbar_document_actions_follow_pane_width_and_remain_available_in_more() {
for (width, split, show_share, show_doc_actions) in [
(299, false, false, false),
(300, false, false, true),
(499, false, false, true),
(500, false, true, true),
(1280, true, false, true),
] {
let mut state = seeded(false);
state.navigate_active_pane(DesktopRoute::Doc("doc-arch".into()));
if split {
state.open_split_edgeless_for_active_doc();
state
.split
.active_mut()
.set_mode(crate::split_view::DocViewMode::Page);
}
let shell = TestShell::open(state, width);
let frame = shell.frame();
for (id, expected) in [
("desktop.topbar.share", show_share),
("desktop.topbar.favorite", show_doc_actions),
("desktop.topbar.doc_info", show_doc_actions),
] {
assert_eq!(
frame.elements.contains_key(id),
expected,
"{id} at {width}px"
);
}
shell.click("desktop.topbar.more");
let menu = shell.frame();
assert_eq!(
menu.elements.contains_key("desktop.header.menu.share"),
!show_share
);
assert!(menu.elements.contains_key("desktop.header.menu.favorite"));
if !show_doc_actions {
shell.click("desktop.header.menu.doc_info");
assert!(shell.frame().elements.contains_key("desktop.header.dialog"));
} else if split {
shell.click("desktop.header.menu.share");
assert!(
shell
.frame()
.elements
.contains_key("desktop.header.share.copy")
);
}
}
}
@@ -0,0 +1,414 @@
//! The local time zone that splits journal activity into calendar days, as `dayjs` does in the
//! web panel.
/// The local time zone of the browser.
#[cfg(target_arch = "wasm32")]
pub(super) struct LocalZone;
#[cfg(target_arch = "wasm32")]
impl LocalZone {
pub(super) fn system() -> Self {
Self
}
/// Minutes that the local calendar runs ahead of UTC at `ms`.
pub(super) fn offset_minutes(&self, ms: i64) -> i32 {
let date = js_sys::Date::new(&wasm_bindgen::JsValue::from_f64(ms as f64));
let offset = date.get_timezone_offset();
if offset.is_finite() {
-(offset.round() as i32)
} else {
0
}
}
}
/// A time zone read once from a zone file or a POSIX `TZ` rule.
#[cfg(not(target_arch = "wasm32"))]
pub(super) enum LocalZone {
/// A constant UTC offset in seconds.
Fixed(i32),
Tzif(Tzif),
Posix(PosixRule),
}
#[cfg(not(target_arch = "wasm32"))]
impl LocalZone {
/// The zone of `TZ`, or of `/etc/localtime` without it.
pub(super) fn system() -> Self {
Self::from_tz(std::env::var("TZ").ok().as_deref())
}
/// The zone of a `TZ` value: a zone file name, an absolute zone file path, or a POSIX rule.
/// Without a value, the zone in `/etc/localtime`. A zone that does not read is UTC.
pub(super) fn from_tz(tz: Option<&str>) -> Self {
let zone = match tz.map(|raw| raw.strip_prefix(':').unwrap_or(raw)) {
None => std::fs::read("/etc/localtime")
.ok()
.and_then(|data| Tzif::parse(&data))
.map(Self::Tzif),
Some("" | "UTC" | "GMT" | "Z") => None,
Some(name) => {
let files = if name.starts_with('/') {
vec![name.to_owned()]
} else {
["/usr/share/zoneinfo", "/var/db/timezone/zoneinfo"]
.map(|dir| format!("{dir}/{name}"))
.to_vec()
};
files
.iter()
.find_map(|file| std::fs::read(file).ok())
.and_then(|data| Tzif::parse(&data))
.map(Self::Tzif)
.or_else(|| PosixRule::parse(name).map(Self::Posix))
}
};
zone.unwrap_or(Self::Fixed(0))
}
/// Minutes that the zone runs ahead of UTC at `ms`.
pub(super) fn offset_minutes(&self, ms: i64) -> i32 {
let secs = ms.div_euclid(1000);
let seconds = match self {
Self::Fixed(offset) => *offset,
Self::Tzif(tzif) => tzif.offset(secs),
Self::Posix(rule) => rule.offset(secs),
};
seconds / 60
}
}
/// The transitions of a TZif zone file (RFC 8536).
#[cfg(not(target_arch = "wasm32"))]
pub(super) struct Tzif {
transitions: Vec<i64>,
/// The local time type that starts at each transition.
indices: Vec<u8>,
/// UTC offset in seconds and daylight saving flag of each local time type.
types: Vec<(i32, bool)>,
/// The rule after the last transition.
footer: Option<PosixRule>,
}
#[cfg(not(target_arch = "wasm32"))]
impl Tzif {
fn parse(data: &[u8]) -> Option<Self> {
let be32 = |at: usize| -> Option<[u8; 4]> { data.get(at..at + 4)?.try_into().ok() };
let header = |at: usize| -> Option<[usize; 6]> {
if data.get(at..at + 4)? != b"TZif" {
return None;
}
let mut counts = [0; 6];
for (index, count) in counts.iter_mut().enumerate() {
*count = u32::from_be_bytes(be32(at + 20 + index * 4)?) as usize;
}
Some(counts)
};
let mut counts = header(0)?;
let (mut start, mut time_size) = (44, 4);
if data.get(4).is_some_and(|version| *version >= b'2') {
// Skip the 32-bit block. The 64-bit block after it has the same layout.
let [isut, isstd, leap, times, types, chars] = counts;
let second = 44 + times * 5 + types * 6 + chars + leap * 8 + isstd + isut;
counts = header(second)?;
(start, time_size) = (second + 44, 8);
}
let [isut, isstd, leap, times, types, chars] = counts;
let transitions = (0..times)
.map(|index| {
let at = start + index * time_size;
Some(if time_size == 8 {
i64::from_be_bytes(data.get(at..at + 8)?.try_into().ok()?)
} else {
i64::from(i32::from_be_bytes(be32(at)?))
})
})
.collect::<Option<Vec<_>>>()?;
let indices_at = start + times * time_size;
let indices = data.get(indices_at..indices_at + times)?.to_vec();
let types_at = indices_at + times;
let types = (0..types)
.map(|index| {
let at = types_at + index * 6;
Some((i32::from_be_bytes(be32(at)?), *data.get(at + 4)? != 0))
})
.collect::<Option<Vec<_>>>()?;
if types.is_empty()
|| indices
.iter()
.any(|&index| usize::from(index) >= types.len())
{
return None;
}
let footer_at = types_at + types.len() * 6 + chars + leap * 12 + isstd + isut;
let footer = (time_size == 8)
.then(|| data.get(footer_at..))
.flatten()
.and_then(|bytes| std::str::from_utf8(bytes).ok())
.and_then(|text| text.split('\n').find(|line| !line.is_empty()))
.and_then(PosixRule::parse);
Some(Self {
transitions,
indices,
types,
footer,
})
}
fn offset(&self, secs: i64) -> i32 {
let passed = self.transitions.partition_point(|&time| time <= secs);
if passed == 0 {
// Before the first transition the zone keeps its first standard time.
return self
.types
.iter()
.find(|(_, dst)| !dst)
.unwrap_or(&self.types[0])
.0;
}
if passed == self.transitions.len()
&& let Some(footer) = &self.footer
{
return footer.offset(secs);
}
self.types[usize::from(self.indices[passed - 1])].0
}
}
/// A POSIX `TZ` rule such as `JST-9` or `EST5EDT,M3.2.0,M11.1.0` (IEEE Std 1003.1).
#[cfg(not(target_arch = "wasm32"))]
pub(super) struct PosixRule {
/// Standard time offset in seconds east of UTC.
standard: i32,
daylight: Option<Daylight>,
}
#[cfg(not(target_arch = "wasm32"))]
struct Daylight {
/// Daylight saving time offset in seconds east of UTC.
offset: i32,
/// The date and local time in seconds at which daylight saving time starts and ends.
start: (DateRule, i32),
end: (DateRule, i32),
}
#[cfg(not(target_arch = "wasm32"))]
enum DateRule {
/// `Mm.w.d`: weekday `d` of week `w` (5 is the last) of month `m`.
Weekday { month: i64, week: i64, weekday: i64 },
/// `Jn`: day `n` of the year from 1 to 365, where February 29 never counts.
Julian(i64),
/// `n`: day `n` of the year from 0 to 365, where February 29 counts.
Ordinal(i64),
}
#[cfg(not(target_arch = "wasm32"))]
impl PosixRule {
fn parse(rule: &str) -> Option<Self> {
let mut rest = rule;
let name = |rest: &mut &str| -> Option<()> {
let len = if let Some(quoted) = rest.strip_prefix('<') {
quoted.find('>')? + 2
} else {
rest.find(|c: char| !c.is_ascii_alphabetic())
.unwrap_or(rest.len())
};
(len >= 3).then(|| *rest = &rest[len..])
};
name(&mut rest)?;
// POSIX offsets count hours west of UTC.
let standard = -duration(&mut rest)?;
if rest.is_empty() || name(&mut rest).is_none() {
return Some(Self {
standard,
daylight: None,
});
}
let offset = if rest.starts_with(',') || rest.is_empty() {
standard + 3600
} else {
-duration(&mut rest)?
};
let mut rules = rest.strip_prefix(',').unwrap_or_default().split(',');
let daylight = match (rules.next(), rules.next()) {
(Some(start), Some(end)) => Some(Daylight {
offset,
start: DateRule::parse(start)?,
end: DateRule::parse(end)?,
}),
_ => None,
};
Some(Self { standard, daylight })
}
fn offset(&self, secs: i64) -> i32 {
let Some(daylight) = &self.daylight else {
return self.standard;
};
let year = blocksuite_editor::block_flow::civil_from_days(
(secs + i64::from(self.standard)).div_euclid(86_400),
)
.0;
// A rule time is local: standard time for the start, daylight saving time for the end.
let at = |(date, time): &(DateRule, i32), offset: i32| {
date.day(year) * 86_400 + i64::from(*time) - i64::from(offset)
};
let (on, off) = (
at(&daylight.start, self.standard),
at(&daylight.end, daylight.offset),
);
let in_daylight = if on < off {
(on..off).contains(&secs)
} else {
!(off..on).contains(&secs)
};
if in_daylight {
daylight.offset
} else {
self.standard
}
}
}
#[cfg(not(target_arch = "wasm32"))]
impl DateRule {
/// A `date[/time]` part of a rule, with its local time in seconds (02:00 by default).
fn parse(part: &str) -> Option<(Self, i32)> {
let (date, mut time) = part.split_once('/').unwrap_or((part, "2"));
let rule = if let Some(fields) = date.strip_prefix('M') {
let mut fields = fields.split('.').map(|field| field.parse::<i64>().ok());
let (month, week, weekday) = (fields.next()??, fields.next()??, fields.next()??);
((1..=12).contains(&month) && (1..=5).contains(&week) && (0..=6).contains(&weekday))
.then_some(Self::Weekday {
month,
week,
weekday,
})?
} else if let Some(day) = date.strip_prefix('J') {
Some(day.parse::<i64>().ok()?)
.filter(|day| (1..=365).contains(day))
.map(Self::Julian)?
} else {
Some(date.parse::<i64>().ok()?)
.filter(|day| (0..=365).contains(day))
.map(Self::Ordinal)?
};
Some((rule, duration(&mut time)?))
}
/// Days from 1970-01-01 to the rule date in `year`.
fn day(&self, year: i64) -> i64 {
let january = days_from_civil(year, 1, 1);
match *self {
Self::Weekday {
month,
week,
weekday,
} => {
let first = days_from_civil(year, month, 1);
let length = days_from_civil(year + month / 12, month % 12 + 1, 1) - first;
// 1970-01-01 was a Thursday (weekday 4).
let mut day = (weekday - (first + 4)).rem_euclid(7) + (week - 1) * 7;
while day >= length {
day -= 7;
}
first + day
}
Self::Julian(day) => {
let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
january + day - 1 + i64::from(leap && day >= 60)
}
Self::Ordinal(day) => january + day,
}
}
}
/// A signed `hh[:mm[:ss]]` duration in seconds, taken from the start of `rest`.
#[cfg(not(target_arch = "wasm32"))]
fn duration(rest: &mut &str) -> Option<i32> {
let end = rest
.find(|c: char| !(c.is_ascii_digit() || matches!(c, ':' | '+' | '-')))
.unwrap_or(rest.len());
let (text, tail) = rest.split_at(end);
*rest = tail;
let (sign, text) = match text.as_bytes().first()? {
b'-' => (-1, &text[1..]),
b'+' => (1, &text[1..]),
_ => (1, text),
};
let mut seconds = 0;
for (part, unit) in text.split(':').zip([3600, 60, 1]) {
seconds += part.parse::<i32>().ok()? * unit;
}
Some(sign * seconds)
}
/// Days from 1970-01-01 to the given proleptic Gregorian date.
#[cfg(not(target_arch = "wasm32"))]
fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
let year = if month <= 2 { year - 1 } else { year };
let era = year.div_euclid(400);
let year_of_era = year - era * 400;
let day_of_year = (153 * ((month + 9) % 12) + 2) / 5 + day - 1;
let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
era * 146_097 + day_of_era - 719_468
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::LocalZone;
#[test]
fn local_zone_follows_zone_files_and_every_posix_date_form_across_daylight_saving() {
const TOKYO_DEC_5_0030: i64 = 1_796_398_200_000;
const NEW_YORK: &str = "America/New_York";
const US_RULE: &str = "EST5EDT,M3.2.0,M11.1.0";
const SYDNEY: &str = "AEST-10AEDT,M10.1.0,M4.1.0/3";
// (TZ value, UTC time in ms, minutes ahead of UTC)
let cases = [
(Some("Asia/Tokyo"), TOKYO_DEC_5_0030, 540),
(Some(":Asia/Tokyo"), TOKYO_DEC_5_0030, 540),
(Some("JST-9"), TOKYO_DEC_5_0030, 540),
(Some("<+0530>-5:30"), TOKYO_DEC_5_0030, 330),
(Some("UTC"), TOKYO_DEC_5_0030, 0),
(Some(""), TOKYO_DEC_5_0030, 0),
// 2026-01-15 12:00 and 2026-07-15 12:00 UTC.
(Some(NEW_YORK), 1_768_478_400_000, -300),
(Some(NEW_YORK), 1_784_116_800_000, -240),
// One second before and at 2026-03-08 07:00 and 2026-11-01 06:00 UTC.
(Some(NEW_YORK), 1_772_953_199_000, -300),
(Some(NEW_YORK), 1_772_953_200_000, -240),
(Some(NEW_YORK), 1_793_512_799_000, -240),
(Some(NEW_YORK), 1_793_512_800_000, -300),
(Some(US_RULE), 1_772_953_199_000, -300),
(Some(US_RULE), 1_772_953_200_000, -240),
(Some(US_RULE), 1_793_512_799_000, -240),
(Some(US_RULE), 1_793_512_800_000, -300),
(Some(SYDNEY), 1_768_478_400_000, 660),
(Some(SYDNEY), 1_784_116_800_000, 600),
// `Jn` and `n` dates: 2026-07-15 04:30 and 2026-07-01 04:30 UTC.
(Some("EST5EDT,J60/2,J300/2"), 1_784_089_800_000, -240),
(Some("EST5EDT,J60/2,J305/2"), 1_782_880_200_000, -240),
(Some("EST5EDT,59/2,300/2"), 1_784_089_800_000, -240),
(Some("AEST-10AEDT,J278,J95/3"), 1_768_478_400_000, 660),
(Some("AEST-10AEDT,J278,J95/3"), 1_784_116_800_000, 600),
// Leap year 2028: J59 is February 28, J60 is March 1, and 0-based 59 is February 29.
// One second before and at 07:00 UTC on February 28, February 29, and March 1.
(Some("EST5EDT,J59/2,J300/2"), 1_835_333_999_000, -300),
(Some("EST5EDT,J59/2,J300/2"), 1_835_334_000_000, -240),
(Some("EST5EDT,59/2,300/2"), 1_835_420_399_000, -300),
(Some("EST5EDT,59/2,300/2"), 1_835_420_400_000, -240),
(Some("EST5EDT,J60/2,J300/2"), 1_835_438_400_000, -300),
(Some("EST5EDT,J60/2,J300/2"), 1_835_506_799_000, -300),
(Some("EST5EDT,J60/2,J300/2"), 1_835_506_800_000, -240),
// Out-of-range days make no daylight saving rule, so the zone is UTC.
(Some("EST5EDT,J0/2,J300/2"), 1_784_089_800_000, 0),
(Some("EST5EDT,366/2,300/2"), 1_784_089_800_000, 0),
];
for (tz, ms, minutes) in cases {
let zone = LocalZone::from_tz(tz);
assert_eq!(zone.offset_minutes(ms), minutes, "{tz:?} at {ms}");
}
}
}
@@ -0,0 +1,363 @@
use std::path::PathBuf;
use affine_store::directory::DocMode;
use ui::{Modifiers, MouseButton};
use ui_tokens::ThemeMode;
use super::{DesktopAppState, DesktopRoute, Shell};
use crate::sqlite_loader::SqliteLazyBacking;
const ROW_TIME: i64 = 1_900_000_000_000;
fn explorer(readonly: bool, route: DesktopRoute) -> (Shell, Vec<String>) {
let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02");
state.web_chrome = true;
let docs = (0..5)
.map(|i| {
state
.store
.create_doc(format!("Row {i}"), DocMode::Page, None, ROW_TIME + i)
})
.collect();
if readonly {
state.store.sqlite_backing = Some(SqliteLazyBacking::new(
PathBuf::from("readonly.affine"),
"ws-ro",
0,
));
}
state.navigate_active_pane(route);
(Shell::with_state(1280, state), docs)
}
impl Shell {
fn tabs(&self) -> usize {
self.update(|shell, _, _| shell.state.split.panes[0].tabs.len())
}
fn text(&self, id: &str) -> Option<String> {
self.update(|_, window, _| window.frame_snapshot().elements.get(id)?.text.clone())
}
fn interactive(&self, id: &str) -> bool {
self.update(|_, window, _| window.frame_snapshot().elements[id].interactive)
}
fn doc<R>(&self, id: &str, read: impl FnOnce(&crate::doc_store::DesktopDocMeta) -> R) -> R {
self.update(|shell, _, _| read(&shell.state.store.get_doc(id).unwrap().meta))
}
fn doc_count(&self) -> usize {
self.update(|shell, _, _| shell.state.store.docs.len())
}
}
#[test]
fn explorer_row_buttons_open_the_document_a_new_tab_or_the_row_menu() {
let platform = Modifiers {
platform: true,
..Modifiers::default()
};
let control = Modifiers {
control: true,
..Modifiers::default()
};
// (button, modifiers, opens a new tab, opens the row menu)
let cases = [
(MouseButton::Left, Modifiers::default(), false, false),
(MouseButton::Left, platform, true, false),
(MouseButton::Left, control, true, false),
(MouseButton::Middle, Modifiers::default(), true, false),
(MouseButton::Right, Modifiers::default(), false, true),
];
for (button, modifiers, new_tab, menu) in cases {
let case = format!("{button:?} {modifiers:?}");
let (app, docs) = explorer(false, DesktopRoute::AllDocs);
let tabs = app.tabs();
app.press(&format!("desktop.list.doc.{}", docs[0]), button, modifiers);
assert_eq!(app.tabs(), tabs + usize::from(new_tab), "{case}");
assert_eq!(app.contains("desktop.explorer.menu"), menu, "{case}");
if menu {
assert_eq!(app.route(), DesktopRoute::AllDocs, "{case}");
for item in ["favorite", "new_tab", "split", "peek", "duplicate", "trash"] {
let id = format!("desktop.explorer.menu.{item}");
assert!(app.interactive(&id), "{case}: {id}");
}
} else {
assert_eq!(app.route(), DesktopRoute::Doc(docs[0].clone()), "{case}");
}
}
}
#[test]
fn explorer_favorite_star_and_row_menu_toggle_the_favorite() {
let (app, docs) = explorer(false, DesktopRoute::AllDocs);
let row = format!("desktop.list.doc.{}", docs[0]);
let star = format!("desktop.explorer.favorite.{}", docs[0]);
app.hover(&row);
app.click(&star);
assert!(app.doc(&docs[0], |doc| doc.is_favorite));
assert_eq!(app.route(), DesktopRoute::AllDocs);
app.right_click(&row);
assert_eq!(
app.text("desktop.explorer.menu.favorite").as_deref(),
Some("Remove from favourites")
);
app.click("desktop.explorer.menu.favorite");
assert!(!app.doc(&docs[0], |doc| doc.is_favorite));
assert!(!app.contains("desktop.explorer.menu"));
app.right_click(&row);
assert_eq!(
app.text("desktop.explorer.menu.favorite").as_deref(),
Some("Add to favourites")
);
}
#[test]
fn explorer_duplicate_and_move_to_trash_wait_for_the_row_menu_and_confirmation() {
let (app, docs) = explorer(false, DesktopRoute::AllDocs);
let row = format!("desktop.list.doc.{}", docs[0]);
let count = app.doc_count();
app.right_click(&row);
app.click("desktop.explorer.menu.duplicate");
assert_eq!(app.doc_count(), count + 1);
assert_eq!(app.route(), DesktopRoute::AllDocs);
app.update(|shell, _, _| {
assert!(
shell
.state
.store
.docs
.values()
.any(|entry| entry.meta.title == "Copy of Row 0")
);
});
let before = app.root_update();
app.right_click(&row);
app.click("desktop.explorer.menu.trash");
assert!(!app.contains("desktop.explorer.menu"));
assert_eq!(
app.text("desktop.trash_prompt.body").as_deref(),
Some("Row 0 will be moved to trash")
);
app.key("escape");
assert!(!app.contains("desktop.trash_prompt"));
assert_eq!(app.root_update(), before);
assert!(!app.doc(&docs[0], |doc| doc.trashed));
app.right_click(&row);
app.click("desktop.explorer.menu.trash");
app.click("desktop.trash_prompt.cancel");
assert!(!app.doc(&docs[0], |doc| doc.trashed));
app.right_click(&row);
app.click("desktop.explorer.menu.trash");
app.click("desktop.trash_prompt.confirm");
assert!(app.doc(&docs[0], |doc| doc.trashed));
assert!(!app.contains("desktop.trash_prompt"));
app.click("desktop.explorer.select");
app.click(&format!("desktop.list.doc.{}", docs[1]));
app.click(&format!("desktop.list.doc.{}", docs[2]));
app.click("desktop.explorer.trash");
assert_eq!(
app.text("desktop.trash_prompt.body").as_deref(),
Some("2 docs will be moved to Trash")
);
app.key("escape");
assert!(!app.doc(&docs[1], |doc| doc.trashed));
app.click("desktop.explorer.trash");
app.click("desktop.trash_prompt.confirm");
assert!(app.doc(&docs[1], |doc| doc.trashed) && app.doc(&docs[2], |doc| doc.trashed));
assert_eq!(
app.text("desktop.explorer.selected").as_deref(),
Some("0 selected")
);
}
#[test]
fn explorer_shift_click_selects_ranges_and_escape_leaves_selection() {
// Newest first: rows show docs[4], docs[3], docs[2], docs[1], docs[0].
let (app, docs) = explorer(false, DesktopRoute::AllDocs);
let shift = Modifiers {
shift: true,
..Modifiers::default()
};
let row = |index: usize| format!("desktop.list.doc.{}", docs[index]);
let selected = |app: &Shell| -> Vec<usize> {
(0..docs.len())
.filter(|&index| app.contains(&format!("desktop.explorer.selected.{}", docs[index])))
.collect()
};
// (row, shift, selected rows after the click)
let steps: [(usize, bool, &[usize]); 4] = [
(3, true, &[3]),
(1, true, &[1, 2, 3]),
(2, false, &[1, 3]),
(4, true, &[1, 4]),
];
for (index, with_shift, expected) in steps {
let modifiers = if with_shift {
shift
} else {
Modifiers::default()
};
app.press(&row(index), MouseButton::Left, modifiers);
assert_eq!(selected(&app), expected, "row {index}");
assert_eq!(app.route(), DesktopRoute::AllDocs);
}
assert_eq!(
app.text("desktop.explorer.selected").as_deref(),
Some("2 selected")
);
app.key("escape");
assert!(!app.contains("desktop.explorer.selected"));
assert!(selected(&app).is_empty());
let (readonly, docs) = explorer(true, DesktopRoute::AllDocs);
readonly.press(
&format!("desktop.list.doc.{}", docs[0]),
MouseButton::Left,
shift,
);
assert!(!readonly.contains("desktop.explorer.selected"));
assert_eq!(readonly.route(), DesktopRoute::Doc(docs[0].clone()));
}
#[test]
fn tag_breadcrumb_switches_tags_and_returns_to_the_tag_overview() {
let (app, _) = explorer(false, DesktopRoute::Tag("architecture".into()));
assert!(!app.contains("desktop.explorer.new_doc"));
let label = app.update(|shell, _, _| shell.state.store.tag_label("architecture"));
assert_eq!(app.text("desktop.explorer.breadcrumb.tag"), Some(label));
app.click("desktop.explorer.breadcrumb.tag");
assert!(app.contains("desktop.explorer.tag_switch.architecture"));
app.click("desktop.explorer.tag_switch.design");
assert_eq!(app.route(), DesktopRoute::Tag("design".into()));
assert!(app.contains("desktop.list.doc.doc-board"));
app.click("desktop.explorer.breadcrumb.tags");
assert_eq!(app.route(), DesktopRoute::AllDocs);
assert!(app.contains("desktop.explorer.group.0"));
assert!(!app.contains("desktop.explorer.breadcrumb.tag"));
}
#[test]
fn all_docs_new_doc_button_creates_the_default_or_chosen_mode_only_when_writable() {
for readonly in [false, true] {
let (app, _) = explorer(readonly, DesktopRoute::AllDocs);
let count = app.doc_count();
assert_eq!(app.interactive("desktop.explorer.new_doc"), !readonly);
assert_eq!(app.interactive("desktop.explorer.new_doc.menu"), !readonly);
if readonly {
continue;
}
app.click("desktop.explorer.new_doc");
let DesktopRoute::Doc(page) = app.route() else {
panic!("New doc must open the new document");
};
assert_eq!(app.doc_count(), count + 1);
app.doc(&page, |doc| assert_eq!(doc.default_mode, DocMode::Page));
app.update(|shell, _, cx| {
shell.state.navigate_active_pane(DesktopRoute::AllDocs);
cx.notify();
});
app.window.request_frame();
app.click("desktop.explorer.new_doc.menu");
app.click("desktop.explorer.menu.new_edgeless");
let DesktopRoute::Doc(board) = app.route() else {
panic!("Edgeless must open the new document");
};
assert_eq!(app.doc_count(), count + 2);
app.doc(&board, |doc| {
assert_eq!(doc.default_mode, DocMode::Edgeless)
});
}
}
#[test]
fn explorer_escape_closes_the_menu_or_prompt_before_it_ends_the_selection() {
let (app, docs) = explorer(false, DesktopRoute::AllDocs);
app.click("desktop.explorer.select");
app.click(&format!("desktop.list.doc.{}", docs[0]));
app.click(&format!("desktop.list.doc.{}", docs[1]));
let open_row_menu = |app: &Shell| app.right_click(&format!("desktop.list.doc.{}", docs[2]));
let open_prompt = |app: &Shell| app.click("desktop.explorer.trash");
// (what opens over the selection, the element that the first Escape closes)
let layers: [(&dyn Fn(&Shell), &str); 2] = [
(&open_row_menu, "desktop.explorer.menu"),
(&open_prompt, "desktop.trash_prompt"),
];
for (open, closes) in layers {
open(&app);
assert!(app.contains(closes), "{closes}");
app.key("escape");
assert!(!app.contains(closes), "{closes}");
assert_eq!(
app.text("desktop.explorer.selected").as_deref(),
Some("2 selected"),
"{closes}"
);
}
app.key("escape");
assert!(!app.contains("desktop.explorer.selected"));
assert!(!app.doc(&docs[0], |doc| doc.trashed));
}
#[test]
fn explorer_row_ignores_the_back_and_forward_mouse_buttons() {
for direction in [
ui::NavigationDirection::Back,
ui::NavigationDirection::Forward,
] {
let (app, docs) = explorer(false, DesktopRoute::AllDocs);
let tabs = app.tabs();
let row = format!("desktop.list.doc.{}", docs[0]);
app.press(&row, MouseButton::Navigate(direction), Modifiers::default());
assert!(!app.contains("desktop.explorer.menu"), "{direction:?}");
assert_eq!(app.tabs(), tabs, "{direction:?}");
assert_ne!(
app.route(),
DesktopRoute::Doc(docs[0].clone()),
"{direction:?}"
);
}
}
#[test]
fn tag_switcher_search_filters_tags_and_reports_no_match() {
let (app, _) = explorer(false, DesktopRoute::Tag("architecture".into()));
app.click("desktop.explorer.breadcrumb.tag");
assert!(app.contains("desktop.explorer.tag_search"));
// (query, tags shown, tags hidden)
let cases: [(&str, &[&str], &[&str]); 3] = [
("", &["architecture", "design", "rust"], &[]),
("DES", &["design"], &["architecture", "rust"]),
("zzz", &[], &["architecture", "design", "rust"]),
];
let mut previous = String::new();
for (query, shown, hidden) in cases {
let len = previous.encode_utf16().count();
app.input(|input| input.replace_text_in_range(Some(0..len), query));
previous = query.to_owned();
for tag in shown {
assert!(
app.contains(&format!("desktop.explorer.tag_switch.{tag}")),
"{query}: {tag}"
);
}
for tag in hidden {
assert!(
!app.contains(&format!("desktop.explorer.tag_switch.{tag}")),
"{query}: {tag}"
);
}
assert_eq!(
app.text("desktop.explorer.tag_switch.empty").as_deref(),
shown.is_empty().then_some("Found 0 results"),
"{query}"
);
}
}
@@ -0,0 +1,173 @@
use std::path::PathBuf;
use affine_store::directory::DocMode;
use ui::{Modifiers, MouseButton};
use ui_tokens::ThemeMode;
use super::{DesktopAppState, DesktopRoute, Shell};
use crate::sqlite_loader::SqliteLazyBacking;
const DAY_MS: i64 = 86_400_000;
/// Midnight UTC of 2026-12-01.
const DEC_1: i64 = 1_796_083_200_000;
fn at(day: i64) -> i64 {
DEC_1 + (day - 1) * DAY_MS + 12 * 3_600_000
}
fn journal_shell(state: DesktopAppState) -> Shell {
let app = Shell::with_state(1280, state);
app.click("desktop.topbar.inspector_toggle");
app.click("desktop.inspector.tab.journal");
app
}
fn seeded() -> DesktopAppState {
let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02");
state.web_chrome = true;
state.navigate_active_pane(DesktopRoute::AllDocs);
state
}
#[test]
fn journal_calendar_dots_mark_journal_and_activity_dates_except_the_selected_one() {
let mut state = seeded();
state
.store
.create_doc("Third", DocMode::Page, Some("2026-12-03".into()), at(3));
state.store.create_doc("Fifth", DocMode::Page, None, at(5));
state
.store
.create_doc("Sixth", DocMode::Page, Some("2026-12-06".into()), 1_000);
let app = journal_shell(state);
// (date, journal dot, activity dot)
for (date, journal, activity) in [
("2026-12-02", false, false),
("2026-12-03", true, true),
("2026-12-05", false, true),
("2026-12-06", true, false),
("2026-12-07", false, false),
] {
for (kind, expected) in [("journal", journal), ("activity", activity)] {
assert_eq!(
app.contains(&format!("desktop.inspector.journal.dot.{kind}.{date}")),
expected,
"{kind} {date}"
);
}
}
}
#[test]
fn journal_activity_tabs_list_created_and_updated_documents_and_open_them() {
let mut state = seeded();
let created = state.store.create_doc("Made", DocMode::Page, None, at(5));
let edited = state
.store
.create_doc("Edited", DocMode::Edgeless, None, at(1));
state
.store
.docs
.get_mut(&edited)
.unwrap()
.meta
.updated_at_ms = at(5) + 1;
state.store.touch_meta();
let app = journal_shell(state);
app.click("desktop.inspector.journal.day.2026-12-05");
let item = |id: &str| format!("desktop.inspector.journal.activity.{id}");
// (tab, listed documents, documents left out)
let tabs = [
("created", vec![&created], vec![&edited]),
("updated", vec![&edited, &created], vec![]),
];
for (tab, listed, absent) in tabs {
app.click(&format!("desktop.inspector.journal.tab.{tab}"));
let rows: Vec<f32> = listed.iter().map(|id| app.bounds(&item(id)).y).collect();
assert!(
rows.windows(2).all(|pair| pair[0] < pair[1]),
"{tab}: {rows:?}"
);
for id in absent {
assert!(!app.contains(&item(id)), "{tab}");
}
assert!(!app.contains("desktop.inspector.journal.activity.empty"));
}
app.click("desktop.inspector.journal.day.2026-12-20");
assert!(app.contains("desktop.inspector.journal.activity.empty"));
app.click("desktop.inspector.journal.day.2026-12-05");
app.click("desktop.inspector.journal.tab.created");
let tabs_before = app.update(|shell, _, _| shell.state.split.panes[0].tabs.len());
let new_tab = Modifiers {
platform: true,
..Modifiers::default()
};
app.press(&item(&created), MouseButton::Left, new_tab);
app.update(|shell, _, _| assert_eq!(shell.state.split.panes[0].tabs.len(), tabs_before + 1));
assert_eq!(app.route(), DesktopRoute::Doc(created.clone()));
app.update(|shell, _, cx| {
shell.state.navigate_active_pane(DesktopRoute::AllDocs);
cx.notify();
});
app.window.request_frame();
app.click("desktop.inspector.journal.day.2026-12-05");
app.click(&item(&created));
assert_eq!(app.route(), DesktopRoute::Doc(created));
}
#[test]
fn journal_conflict_block_lists_same_day_journals_and_trashes_only_after_confirmation() {
for readonly in [false, true] {
let mut state = seeded();
let other = state.store.create_doc(
"Second journal",
DocMode::Page,
Some("2026-12-02".into()),
at(2),
);
if readonly {
state.store.sqlite_backing = Some(SqliteLazyBacking::new(
PathBuf::from("readonly.affine"),
"ws-ro",
0,
));
}
let app = journal_shell(state);
assert!(app.contains("desktop.inspector.journal.conflict"));
for id in ["doc-journal-today", other.as_str()] {
assert!(app.contains(&format!("desktop.inspector.journal.conflict.item.{id}")));
}
let trash = format!("desktop.inspector.journal.conflict.trash.{other}");
let interactive =
app.update(|_, window, _| window.frame_snapshot().elements[&trash].interactive);
assert_eq!(interactive, !readonly);
app.click(&format!("desktop.inspector.journal.conflict.item.{other}"));
assert_eq!(app.route(), DesktopRoute::Doc(other.clone()));
if readonly {
continue;
}
let before = app.root_update();
app.click(&trash);
assert!(app.contains("desktop.trash_prompt"));
app.key("escape");
assert!(!app.contains("desktop.trash_prompt"));
assert_eq!(app.root_update(), before);
app.click(&trash);
app.click("desktop.trash_prompt.confirm");
app.update(|shell, _, _| {
assert!(shell.state.store.get_doc(&other).unwrap().meta.trashed);
assert!(
!shell
.state
.store
.get_doc("doc-journal-today")
.unwrap()
.meta
.trashed
);
});
assert!(!app.contains("desktop.inspector.journal.conflict"));
}
}
@@ -1,4 +1,6 @@
mod explorer_menus;
mod inspector_outline;
mod journal_panel;
mod outline_rail;
mod trash_and_tags;
mod virtual_rows;
@@ -1,6 +1,6 @@
use affine_store::directory::DocMode;
use image::GenericImageView;
use ui::{MouseButton, MouseDownEvent, MouseUpEvent, PlatformInput, px};
use ui::px;
use ui_tokens::ThemeMode;
use super::{
@@ -107,34 +107,16 @@ fn virtual_rows_keep_spacers_and_anchor_after_height_order_and_document_changes(
}
#[test]
fn explorer_shift_click_and_row_menu_keep_the_document_identity() {
fn explorer_row_menu_keeps_the_document_identity_after_scrolling() {
let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02");
let docs = append_rows(&mut state, 60, ROW_TIME, false);
state.navigate_active_pane(DesktopRoute::AllDocs);
let app = Shell::with_state(1280, state);
let target = docs.last().unwrap();
let row = format!("desktop.list.doc.{target}");
let position = app.position(&row);
let modifiers = ui::Modifiers {
shift: true,
..Default::default()
};
app.window
.dispatch_input(PlatformInput::MouseDown(MouseDownEvent {
button: MouseButton::Left,
position,
modifiers,
click_count: 1,
..Default::default()
}));
app.window
.dispatch_input(PlatformInput::MouseUp(MouseUpEvent {
button: MouseButton::Left,
position,
modifiers,
click_count: 1,
}));
app.window.request_frame();
app.right_click(&row);
app.click("desktop.explorer.menu.peek");
assert!(app.contains("desktop.peek.modal"));
app.click("desktop.peek.close");
@@ -144,6 +126,7 @@ fn explorer_shift_click_and_row_menu_keep_the_document_identity() {
assert!(!app.contains(&row));
assert!(app.contains("desktop.list.doc.doc-sync"));
app.click("desktop.explorer.menu.trash");
app.click("desktop.trash_prompt.confirm");
app.update(|shell, _, _| {
assert!(shell.state.store.get_doc(target).unwrap().meta.trashed);
assert!(!shell.state.store.get_doc(&docs[0]).unwrap().meta.trashed);
@@ -171,6 +154,7 @@ fn explorer_select_all_includes_every_document_in_the_collection() {
app.click("desktop.explorer.select");
app.click("desktop.explorer.select_all");
app.click("desktop.explorer.trash");
app.click("desktop.trash_prompt.confirm");
app.update(|shell, _, _| {
for (index, id) in docs.iter().enumerate() {
assert_eq!(