feat(collection): match custom property filters

Saved collections and the rule preview now match workspace custom
properties of the text, number, checkbox, and date types. The rules are the
same as the property filters of the web client.

- An unknown or deleted property, a type without filters, or a method that
  does not apply to the type is an error, as in the web client.

- Compare numbers as JavaScript Number does. A document without a value is
  NaN, so no number comparison matches it.

- All filter scopes share one source of custom properties. A filter reads
  the property type and the value from it when it matches a document.

- The document views, the sidebar rows, the saved collections, and the
  preview read the property tables again when their revisions change. A
  change that no store command made also shows at once. Only a filter by a
  custom property causes a read of the property tables.

- Add YjsTableDoc::for_each_row. It reads only the fields that the caller
  asks for, so other fields of a row cause no copies.
This commit is contained in:
DarkSky committed 2026-12-04 23:17:18 +09:00
1 parent c453968923
commit 84fa64fd2d
8 files changed
+967 -21

No files matched your search

@@ -550,6 +550,24 @@ impl YjsTableDoc {
Ok(rows)
}
/// Visit each row that is not deleted with its primary key and a reader of its text fields.
/// The reader copies only the fields that the caller asks for, so other fields cause no
/// work.
pub fn for_each_row(&self, mut visit: impl FnMut(&str, &dyn Fn(&str) -> Option<String>)) {
for key in self.doc.keys() {
let Ok(map) = self.doc.get_map(&key) else {
continue;
};
if is_map_deleted(&map) {
continue;
}
visit(&key, &|field| match map.get(field) {
Some(Value::Any(Any::String(text))) => Some(text),
_ => None,
});
}
}
/// Return `true` if `primary_key` exists in the underlying YDoc with `$$DELETED = true`.
pub fn is_soft_deleted(&self, primary_key: &str) -> StoreResult<bool> {
let Ok(map) = self.doc.get_map(primary_key) else {
+344 -13
View File
@@ -6,7 +6,7 @@ use std::{
use serde::{Deserialize, Serialize};
use super::{CivilDate, FilterScope};
use super::{CivilDate, FilterScope, PropertyColumns, PropertyKind};
/// Smart collection filter rule.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
@@ -79,6 +79,11 @@ impl FilterRule {
&self.params
}
/// The workspace facts that the filter reads.
pub fn scope(&self) -> &Arc<FilterScope> {
&self.scope
}
/// Whether the document matches the filter, or `None` for an unsupported filter.
pub fn matches(&self, doc: &DocFacts<'_>) -> Option<bool> {
self.matches_with_scratch(doc, &mut String::new())
@@ -98,8 +103,12 @@ impl FilterRule {
#[inline]
fn matches_with_scratch(&self, doc: &DocFacts<'_>, scratch: &mut String) -> Option<bool> {
self.prepared()
.matches(self.params.value.as_deref(), &self.scope, doc, scratch)
let (prepared, value) = (self.prepared(), self.params.value.as_deref());
if let PreparedFilter::Property { .. } = prepared {
let columns = self.scope.properties.as_ref()?.read();
return prepared.matches(value, &self.scope, doc, scratch, Some(&**columns));
}
prepared.matches(value, &self.scope, doc, scratch, None)
}
}
@@ -125,6 +134,30 @@ pub struct PreparedRule<'a> {
filter: Cow<'a, PreparedFilter>,
value: Option<&'a str>,
scope: &'a FilterScope,
/// The custom properties at compile time, for a custom property filter.
properties: Option<Arc<PropertyColumns>>,
}
impl<'a> PreparedRule<'a> {
fn new(
filter: Cow<'a, PreparedFilter>,
value: Option<&'a str>,
scope: &'a FilterScope,
) -> Self {
let properties = match *filter {
PreparedFilter::Property { .. } => scope
.properties
.as_ref()
.map(|source| Arc::clone(&*source.read())),
_ => None,
};
Self {
filter,
value,
scope,
properties,
}
}
}
impl<'a> CompiledFilter<'a> {
@@ -135,11 +168,11 @@ impl<'a> CompiledFilter<'a> {
value: Option<&'a str>,
scope: &'a FilterScope,
) -> Self {
Self::System(PreparedRule {
filter: Cow::Owned(PreparedFilter::new(kind, key, method, value, scope)),
Self::System(PreparedRule::new(
Cow::Owned(PreparedFilter::new(kind, key, method, value, scope)),
value,
scope,
})
))
}
/// Match a tag ID directly, as legacy collection rules do.
@@ -155,7 +188,15 @@ impl<'a> CompiledFilter<'a> {
Self::ModeIs(mode) => doc.mode == *mode,
Self::IncludeDocIds(ids) => ids.iter().any(|id| id == doc.id),
Self::Title(title) => title.matches(doc.title, scratch),
Self::System(rule) => return rule.filter.matches(rule.value, rule.scope, doc, scratch),
Self::System(rule) => {
return rule.filter.matches(
rule.value,
rule.scope,
doc,
scratch,
rule.properties.as_deref(),
);
}
})
}
}
@@ -190,6 +231,131 @@ enum PreparedFilter {
Favorite(bool),
Trash(bool),
Journal(bool),
/// A workspace custom property, by property ID.
Property {
key: String,
test: PropertyTest,
},
}
/// A test of the `custom:<id>` text value of a document, as the property filters of the web
/// client do. A document without the value reads as `undefined`. The type of the property
/// selects the methods that apply when the filter reads the value.
#[derive(Clone, Debug)]
enum PropertyTest {
/// `is` or `is-not` the filter value, for text and checkbox properties. A checkbox reads
/// `false` unless its value is `true`.
Equal(bool),
/// `is-empty` or `is-not-empty`, for text, number, and date properties: no value or an
/// empty text.
Empty(bool),
/// A number comparison with `Number(value)`, where `Number(undefined)` is `NaN`.
Number { op: NumberOp, target: f64 },
/// A `YYYY-MM-DD` value in the range, for date properties.
Date(RangeInclusive<CivilDate>),
}
#[derive(Clone, Copy, Debug)]
enum NumberOp {
Equal,
NotEqual,
Greater,
Less,
GreaterOrEqual,
LessOrEqual,
}
impl PropertyTest {
fn new(method: &str, value: Option<&str>, today: Option<CivilDate>) -> Option<Self> {
let op = match method {
"is" | "is-not" => return Some(Self::Equal(method == "is")),
"is-empty" | "is-not-empty" => return Some(Self::Empty(method == "is-empty")),
"=" => NumberOp::Equal,
"≠" => NumberOp::NotEqual,
">" => NumberOp::Greater,
"<" => NumberOp::Less,
"≥" => NumberOp::GreaterOrEqual,
"≤" => NumberOp::LessOrEqual,
_ => return date_range(method, value, today).map(Self::Date),
};
Some(Self::Number {
op,
target: value.map_or(f64::NAN, js_number),
})
}
/// Whether the stored value matches, or `None` when the method does not apply to the type.
#[inline]
fn matches(
&self,
kind: PropertyKind,
stored: Option<&str>,
value: Option<&str>,
) -> Option<bool> {
use PropertyKind::{Checkbox, Date, Number, Text};
Some(match (self, kind) {
(Self::Equal(equal), Text) => (stored == value) == *equal,
(Self::Equal(equal), Checkbox) => {
let checked = if stored == Some("true") {
"true"
} else {
"false"
};
(Some(checked) == value) == *equal
}
(Self::Empty(empty), Text | Number | Date) => {
stored.is_none_or(str::is_empty) == *empty
}
(Self::Number { op, target }, Number) => {
let (number, target) = (stored.map_or(f64::NAN, js_number), *target);
match op {
NumberOp::Equal => (number - target).abs() < f64::EPSILON,
NumberOp::NotEqual => (number - target).abs() >= f64::EPSILON,
NumberOp::Greater => number > target,
NumberOp::Less => number < target,
NumberOp::GreaterOrEqual => number >= target,
NumberOp::LessOrEqual => number <= target,
}
}
(Self::Date(range), Date) => stored
.and_then(CivilDate::parse)
.is_some_and(|date| range.contains(&date)),
_ => return None,
})
}
}
/// JavaScript `Number(text)`: blank text is `0`, and text that is not a number is `NaN`.
fn js_number(text: &str) -> f64 {
let text = text.trim_matches(|c: char| (c.is_whitespace() && c != '\u{85}') || c == '\u{feff}');
let radix = match text.get(..2) {
Some("0x" | "0X") => 16,
Some("0o" | "0O") => 8,
Some("0b" | "0B") => 2,
_ => 10,
};
match text {
"" => 0.0,
"Infinity" | "+Infinity" => f64::INFINITY,
"-Infinity" => f64::NEG_INFINITY,
_ if radix != 10 => {
let digits = &text[2..];
digits
.chars()
.try_fold(0.0, |number, ch| {
Some(number * f64::from(radix) + f64::from(ch.to_digit(radix)?))
})
.filter(|_| !digits.is_empty())
.unwrap_or(f64::NAN)
}
_ if text
.bytes()
.all(|b| b.is_ascii_digit() || matches!(b, b'.' | b'e' | b'E' | b'+' | b'-')) =>
{
text.parse().unwrap_or(f64::NAN)
}
_ => f64::NAN,
}
}
#[derive(Clone, Debug)]
@@ -200,6 +366,17 @@ enum DateTest {
impl PreparedFilter {
fn new(kind: &str, key: &str, method: &str, value: Option<&str>, scope: &FilterScope) -> Self {
if kind == "property" {
// The filter reads the property and its type with each value, so it stays valid when
// the properties change. An unknown method is an error for every type.
return PropertyTest::new(method, value, scope.today).map_or(
Self::Unsupported,
|test| Self::Property {
key: key.to_owned(),
test,
},
);
}
if kind != "system" {
return Self::Unsupported;
}
@@ -276,6 +453,7 @@ impl PreparedFilter {
scope: &FilterScope,
doc: &DocFacts<'_>,
scratch: &mut String,
properties: Option<&PropertyColumns>,
) -> Option<bool> {
Some(match self {
Self::Unsupported => return None,
@@ -319,6 +497,12 @@ impl PreparedFilter {
Self::Favorite(expected) => doc.favorite == *expected,
Self::Trash(expected) => doc.trashed == *expected,
Self::Journal(expected) => doc.journal == *expected,
// An unknown or deleted property is an error.
Self::Property { key, test } => {
let column = properties?.get(key)?;
let stored = column.values.get(doc.id).map(String::as_str);
return test.matches(column.kind, stored, value);
}
})
}
}
@@ -439,11 +623,11 @@ impl CollectionRule {
Self::ModeIs(mode) => CompiledFilter::ModeIs(mode),
Self::TitleContains(needle) => CompiledFilter::Title(TitleFilter::new(needle)),
Self::IncludeDocIds(ids) => CompiledFilter::IncludeDocIds(ids),
Self::Filter(rule) => CompiledFilter::System(PreparedRule {
filter: Cow::Borrowed(rule.prepared()),
value: rule.params.value.as_deref(),
scope: &rule.scope,
}),
Self::Filter(rule) => CompiledFilter::System(PreparedRule::new(
Cow::Borrowed(rule.prepared()),
rule.params.value.as_deref(),
&rule.scope,
)),
}
}
}
@@ -484,7 +668,7 @@ mod tests {
use std::collections::{BTreeMap, BTreeSet};
use super::*;
use crate::domain::LocalCalendar;
use crate::domain::{LocalCalendar, PropertyColumn, PropertySource};
#[test]
fn civil_dates_round_trip_and_start_relative_ranges() {
@@ -524,6 +708,7 @@ mod tests {
calendar: LocalCalendar::default(),
tags: Some(BTreeSet::from(["a".into(), "b".into(), "c".into()])),
created: BTreeMap::from([("doc".into(), noon("2026-11-01").unwrap())]),
properties: None,
});
let tags = vec!["a".to_owned(), "b".to_owned(), "deleted".to_owned()];
let doc = DocFacts {
@@ -642,6 +827,152 @@ mod tests {
assert!(!collection_holds(&[listed()], &trashed));
}
#[test]
fn custom_property_filters_match_like_the_web_client() {
let column = |kind: &str, values: [(&str, &str); 2]| PropertyColumn {
kind: PropertyKind::parse(kind),
values: values
.into_iter()
.map(|(doc, value)| (doc.into(), value.into()))
.collect(),
};
let columns = PropertyColumns::from([
("state".into(), column("text", [("a", "ready"), ("b", "")])),
("score".into(), column("number", [("a", "5"), ("b", "")])),
(
"done".into(),
column("checkbox", [("a", "true"), ("b", "false")]),
),
(
"due".into(),
column("date", [("a", "2026-12-01"), ("b", "")]),
),
("rating".into(), column("rating", [("a", "3"), ("b", "")])),
]);
let scope = Arc::new(FilterScope {
today: CivilDate::parse("2026-12-03"),
properties: Some(Arc::new(PropertySource::new(columns))),
..FilterScope::default()
});
let rule = |key: &str, method: &str, value: Option<&str>, scope: &Arc<FilterScope>| {
FilterRule::new(
FilterParams {
kind: "property".into(),
key: key.into(),
method: method.into(),
value: value.map(Into::into),
},
Arc::clone(scope),
)
};
let doc = |id| DocFacts {
id,
title: "",
tags: &[],
mode: "page",
page_width: None,
favorite: false,
journal: false,
trashed: false,
created: None,
updated: None,
};
// Document `c` has no value for any property.
const T: Option<bool> = Some(true);
const F: Option<bool> = Some(false);
for (key, method, value, expected) in [
("state", "is", Some("ready"), [T, F, F]),
("state", "is", Some(""), [F, T, F]),
("state", "is", None, [F, F, T]),
("state", "is-not", Some("ready"), [F, T, T]),
("state", "is-not-empty", None, [T, F, F]),
("state", "is-empty", None, [F, T, T]),
("state", "contains", Some("r"), [None; 3]),
("score", "=", Some("5"), [T, F, F]),
("score", "=", Some("0"), [F, T, F]),
("score", "=", None, [F, F, F]),
("score", "≠", Some("5"), [F, T, F]),
("score", ">", Some("1"), [T, F, F]),
("score", "<", Some("1"), [F, T, F]),
("score", "≥", Some(" 5 "), [T, F, F]),
("score", "≤", Some("5"), [T, T, F]),
("score", "is-empty", None, [F, T, T]),
("score", "is-not-empty", None, [T, F, F]),
("score", "is", Some("5"), [None; 3]),
("done", "is", Some("true"), [T, F, F]),
("done", "is", Some("false"), [F, T, T]),
("done", "is-not", Some("true"), [F, T, T]),
("done", "is-empty", None, [None; 3]),
("due", "after", Some("2026-11-30"), [T, F, F]),
("due", "before", Some("2026-11-30"), [F, F, F]),
("due", "between", Some("2026-12-01,2026-12-01"), [T, F, F]),
("due", "this-month", None, [T, F, F]),
("due", "is-empty", None, [F, T, T]),
("due", "between", Some("2026-12-01"), [None; 3]),
("due", "after", None, [None; 3]),
("rating", "is", Some("3"), [None; 3]),
("deleted", "is", Some("ready"), [None; 3]),
] {
let rule = rule(key, method, value, &scope);
let actual = ["a", "b", "c"].map(|id| rule.matches(&doc(id)));
assert_eq!(actual, expected, "{key} {method} {value:?}");
}
// A prepared filter reads the current properties: new values, a new type, and a
// deleted property.
let ready = rule("state", "is", Some("ready"), &scope);
let source = scope.properties.as_ref().unwrap();
for (columns, expected) in [
(
PropertyColumns::from([(
"state".into(),
column("text", [("a", "draft"), ("b", "ready")]),
)]),
[F, T, F],
),
(
PropertyColumns::from([(
"state".into(),
column("number", [("a", "1"), ("b", "")]),
)]),
[None; 3],
),
(PropertyColumns::new(), [None; 3]),
] {
source.replace(columns);
assert_eq!(["a", "b", "c"].map(|id| ready.matches(&doc(id))), expected);
}
// Without the custom properties of the workspace, a property filter is an error.
let unread = Arc::new(FilterScope::default());
assert_eq!(
rule("state", "is", Some("ready"), &unread).matches(&doc("a")),
None
);
}
#[test]
fn js_number_reads_text_like_javascript() {
for (text, expected) in [
("", 0.0),
(" \n", 0.0),
(" 12 ", 12.0),
("-1.5", -1.5),
("1.", 1.0),
(".5", 0.5),
("1e3", 1000.0),
("0x10", 16.0),
("0b11", 3.0),
("Infinity", f64::INFINITY),
("-Infinity", f64::NEG_INFINITY),
] {
assert_eq!(js_number(text), expected, "{text:?}");
}
for text in [
"abc", ".", "1e", "1_0", "inf", "NaN", "0x", "-0x10", "\u{85}1",
] {
assert!(js_number(text).is_nan(), "{text:?}");
}
}
#[test]
fn saved_filter_preparation_does_not_change_its_serialized_form_or_equality() {
let params = FilterParams {
+154 -2
View File
@@ -3,13 +3,14 @@
use std::{
collections::{BTreeMap, BTreeSet},
sync::{Arc, Mutex, MutexGuard},
sync::{Arc, Mutex, MutexGuard, PoisonError, RwLock, RwLockReadGuard},
};
use affine_store::{
directory::{DocId, WorkspaceDirectory},
workspace_db::{
DocPropertiesRow, FavoriteRow, FolderRow, UserdataTableName, WorkspaceDbTableName,
DocCustomPropertyInfoRow, DocPropertiesRow, FavoriteRow, FolderRow, UserdataTableName,
WorkspaceDb, WorkspaceDbTableName,
},
};
use serde::{Deserialize, Serialize};
@@ -209,6 +210,115 @@ pub struct FilterScope {
/// Creation times in Unix milliseconds by document ID. Documents not in this map were
/// created today.
pub created: BTreeMap<String, i64>,
/// The custom properties of the workspace. A store reads them only when a collection
/// filters by a custom property. Custom property filters are errors without them.
pub properties: Option<Arc<PropertySource>>,
}
/// Workspace custom properties that remain, by property ID.
pub type PropertyColumns = BTreeMap<String, PropertyColumn>;
/// The type of a workspace custom property.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PropertyKind {
Text,
Number,
Checkbox,
Date,
/// A type that collection filters do not read.
Other,
}
impl PropertyKind {
pub fn parse(kind: &str) -> Self {
match kind {
"text" => Self::Text,
"number" => Self::Number,
"checkbox" => Self::Checkbox,
"date" => Self::Date,
_ => Self::Other,
}
}
}
/// One workspace custom property and its text values.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PropertyColumn {
pub kind: PropertyKind,
/// The `custom:<id>` text value of each document that has one, by document ID.
pub values: BTreeMap<String, String>,
}
/// The current custom properties of a workspace. A store replaces them when the property
/// tables change, and each filter reads the current properties.
#[derive(Debug, Default)]
pub struct PropertySource(RwLock<Arc<PropertyColumns>>);
impl PropertySource {
pub fn new(columns: PropertyColumns) -> Self {
Self(RwLock::new(Arc::new(columns)))
}
pub fn read(&self) -> RwLockReadGuard<'_, Arc<PropertyColumns>> {
self.0.read().unwrap_or_else(PoisonError::into_inner)
}
pub fn replace(&self, columns: PropertyColumns) {
*self.0.write().unwrap_or_else(PoisonError::into_inner) = Arc::new(columns);
}
}
impl PartialEq for PropertySource {
fn eq(&self, other: &Self) -> bool {
std::ptr::eq(self, other)
}
}
impl Eq for PropertySource {}
/// The revisions of the property definition and document property tables of a workspace.
pub fn property_table_revisions(db: &WorkspaceDb) -> (Option<u64>, Option<u64>) {
let revision = |table| db.db_table(table).map(|table| table.revision());
(
revision(WorkspaceDbTableName::DocCustomPropertyInfo),
revision(WorkspaceDbTableName::DocProperties),
)
}
/// Read the custom properties of a workspace and the text value of each document, in one
/// pass over each table.
pub fn read_property_columns(db: &WorkspaceDb) -> PropertyColumns {
let mut columns: PropertyColumns = db
.db_table(WorkspaceDbTableName::DocCustomPropertyInfo)
.and_then(|table| table.list_rows::<DocCustomPropertyInfoRow>().ok())
.into_iter()
.flatten()
.filter(|row| row.is_deleted != Some(true))
.map(|row| {
let column = PropertyColumn {
kind: PropertyKind::parse(&row.property_type),
values: BTreeMap::new(),
};
(row.id, column)
})
.collect();
let Some(table) = db
.db_table(WorkspaceDbTableName::DocProperties)
.filter(|_| !columns.is_empty())
else {
return columns;
};
let mut field = String::from("custom:");
table.for_each_row(|doc, read| {
for (id, column) in &mut columns {
field.truncate("custom:".len());
field.push_str(id);
if let Some(value) = read(&field) {
column.values.insert(doc.to_owned(), value);
}
}
});
columns
}
/// User-defined collection grouping documents by explicit IDs and filter rules.
@@ -666,6 +776,48 @@ mod tests {
assert_eq!(svc.evaluate_collection("col-1").unwrap().len(), 1);
}
#[test]
fn property_columns_read_text_values_of_remaining_properties_and_rows() {
let mut db = WorkspaceDb::new("ws", "u1", 1);
let info = WorkspaceDbTableName::DocCustomPropertyInfo;
let values = WorkspaceDbTableName::DocProperties;
for row in [
serde_json::json!({"id": "state", "type": "text"}),
serde_json::json!({"id": "gone", "type": "text", "isDeleted": true}),
serde_json::json!({"id": "rank", "type": "rating"}),
] {
db.upsert_db_row(info, &row).unwrap();
}
for row in [
serde_json::json!({"id": "a", "custom:state": "ready", "custom:gone": "old"}),
serde_json::json!({"id": "b", "custom:state": 5, "custom:rank": "3"}),
serde_json::json!({"id": "c", "custom:state": "trashed row"}),
] {
db.upsert_db_row(values, &row).unwrap();
}
db.soft_delete_db_row(values, "c").unwrap();
let columns = read_property_columns(&db);
let read: Vec<_> = columns
.iter()
.map(|(id, column)| (id.as_str(), column.kind, column.values.clone()))
.collect();
assert_eq!(
read,
[
(
"rank",
PropertyKind::Other,
BTreeMap::from([("b".to_owned(), "3".to_owned())])
),
(
"state",
PropertyKind::Text,
BTreeMap::from([("a".to_owned(), "ready".to_owned())])
),
]
);
}
#[test]
fn shared_single_root_writer_exposes_linked_doc_immediately_in_domain_service() {
let mut db = WorkspaceDb::new("ws-shared", "u1", 1);
+1 -1
View File
@@ -7,7 +7,7 @@
- `affine-desktop` owns the multi-pane `Workbench`, collapsible and resizable `AppSidebar` (workspace switcher, Quick Search, New Page/Edgeless, All Docs, Favorites, Journals, Folders/Collections/Tags tree, Trash, and Settings), multi-tab Split View with per-pane `Entity<playground::PlaygroundView>` synchronized incrementally via Yjs V1 state-vector diffs (`encode_diff_v1`) through `DesktopDocStore` and per-pane `NavHistory`, `Cmd/Ctrl+K` `QuickSearch`, centered `PeekView`, physically isolated `ComposerDraftStore` with SHA-256 content-addressed attachments and one-way idempotent importers, `wasm32` Web Desktop mount entry (`wasm_desktop_main`), and the `desktop-harness` offscreen verification CLI.
- Native read-only `.affine` / `<spaceId>.db` inspection opens via `SqliteDocStorage::open_read_only` (`sqlite_loader.rs`) with lazy per-document hydration and zero CRDT writeback. The read worker reuses one read-only connection of the current backing and reopens it when the backing changes, the file is replaced, or the last backing handle is dropped. It holds no read transaction between requests.
- Interactive mutations operate on in-memory `DesktopDocStore` sessions until the host binds a `WorkspaceSession` to the active workspace: the native host with its SQLite store and transport (`DesktopShellView::connect_workspace`), Web Desktop with its IndexedDB store (`DesktopShellView::bind_local_workspaces`, `workbench/local_workspace.rs`). From then on that `WorkspaceSession` is the single writer of the workspace (`doc_store/writer.rs`): shell commands (create, journal, rename, favorite, trash, restore, delete, folder placement) write to it first and the store projects the result. Editor and store document edits join one ordered queue, and every session write merges that queue first.
- `doc_store/views.rs` builds the ordered document lists, sidebar counts, sidebar folder tree, and Quick Search index at most once per metadata revision. The sidebar tree flattens into rows by expansion state and mounts only the rows that `ui_kit::VirtualList` places in the viewport and overscan.
- `doc_store/views.rs` builds the document lists, sidebar counts, folder tree, and Quick Search index once per metadata revision. Custom property filters also key the views on the revisions of the property tables. A table change that no store command made also builds the views again. The sidebar tree flattens into rows by expansion state and mounts only the rows that `ui_kit::VirtualList` places in the viewport and overscan.
Web Desktop (`wasm_desktop_main`) opens each showcase workspace from the documents that `hosts/web/desktop/start.js` reads from its nbstore IndexedDB store `local:workspace:<workspaceId>` (the workspace root, the `db$*` tables, and one document per page), or seeds a workspace that the store does not hold. Each workspace has a session of its own, and the shell binds the session of the active workspace as its writer. Every 250 ms on the UI scheduler clock, and at once when the active workspace, its document list, or the open document changes, the shell writes the session updates and deletions of every workspace to the store and the route to the `?workspace=&doc=` query. An explicit `mode=page` or `mode=edgeless` sets the initial view mode for that document and stays in the URL until the route changes. `flush_web_desktop` writes them at once; the page calls it when it is hidden or unloaded. The shell also writes the app tabs of the active workspace (route, view mode, pin state, and split views of each tab) to the store with `LocalDocStore::set_tabs`, and Web Desktop keeps them in `localStorage`. At startup, before the first write, each workspace opens the tabs that the store kept for it, and then the route and the split view of the URL open in the active workspace. Without IndexedDB, or when the stored documents do not decode, the showcase runs in memory only.
@@ -2,12 +2,12 @@
use std::{
collections::{BTreeMap, BTreeSet},
sync::Arc,
sync::{Arc, TryLockError},
};
use affine_client::domain::{
CivilDate, CollectionRule, CompiledFilter, DocFacts, FilterParams, FilterRule, FilterScope,
LocalCalendar, filters_match,
LocalCalendar, filters_match, property_table_revisions, read_property_columns,
};
use affine_store::{
StoreResult,
@@ -20,6 +20,14 @@ use ui_tokens::{LIGHT_THEME, ThemeTokens};
use super::{DesktopCollection, DesktopDocMeta, DesktopDocStore, PageWidth, stored_ms};
/// The workspace, writer, and table revisions of the last read of the custom properties.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct PropertiesKey {
workspace: usize,
connected: bool,
revisions: (Option<u64>, Option<u64>),
}
#[derive(Default)]
pub(super) struct NavigationProjection {
pub(super) tags: Option<BTreeMap<String, WorkspaceTag>>,
@@ -64,11 +72,16 @@ pub(super) fn created_dates(root: &WorkspaceRootDoc) -> BTreeMap<String, i64> {
impl DesktopDocStore {
pub(crate) fn load_navigation(&mut self) {
self.derived.properties_key.set(None);
self.project_navigation(NavigationSnapshot::read(self.directory.db().root()));
}
pub(super) fn load_connected_navigation(&mut self) {
self.derived.properties_key.set(None);
let now = self.writer_now();
self.derived.session_directory = self
.with_session(now, |session| Ok(session.directory().shared_directory()))
.and_then(Result::ok);
if let Some(Ok(snapshot)) = self.with_session(now, |session| {
let dir = session.directory().lock_directory();
Ok(NavigationSnapshot::read(dir.db().root()))
@@ -78,6 +91,56 @@ impl DesktopDocStore {
}
}
/// Whether a saved collection of the active workspace filters by a custom property.
pub(super) fn saved_property_filters(&self) -> bool {
self.collections.iter().flat_map(|c| &c.rules).any(
|rule| matches!(rule, CollectionRule::Filter(rule) if rule.params().kind == "property"),
)
}
/// The workspace, writer, and table revisions of the last read of the custom properties.
/// A cache of collection members keys on it together with the metadata revision.
pub(crate) fn properties_cache_key(&self) -> Option<(usize, bool, Option<u64>, Option<u64>)> {
self.derived.properties_key.get().map(|key| {
let (info, values) = key.revisions;
(key.workspace, key.connected, info, values)
})
}
/// Read the custom properties of the active workspace again when their tables changed.
/// Without `force`, only a saved collection that filters by a custom property reads them,
/// so other workspaces read no property table. While another thread holds the directory of
/// the connected session, the current properties stay until the next read.
pub(super) fn sync_custom_properties(&self, force: bool) {
if !force && !self.saved_property_filters() {
return;
}
let connected = self.saves_active_workspace();
let session = self
.derived
.session_directory
.as_ref()
.filter(|_| connected);
let guard = match session.map(|directory| directory.try_lock()) {
None => None,
Some(Ok(guard)) => Some(guard),
Some(Err(TryLockError::Poisoned(error))) => Some(error.into_inner()),
Some(Err(TryLockError::WouldBlock)) => return,
};
let db = guard
.as_ref()
.map_or(self.directory.db(), |guard| guard.db());
let key = PropertiesKey {
workspace: self.active_workspace_idx,
connected,
revisions: property_table_revisions(db),
};
if self.derived.properties_key.get() != Some(key) {
self.derived.properties.replace(read_property_columns(db));
self.derived.properties_key.set(Some(key));
}
}
fn project_navigation(&mut self, snapshot: NavigationSnapshot) -> bool {
let workspace = self.active_workspace().id.clone();
let projection = self.derived.navigation.entry(workspace).or_default();
@@ -134,6 +197,7 @@ impl DesktopDocStore {
calendar: self.derived.calendar.clone(),
tags: tags.map(|tags| tags.keys().cloned().collect()),
created,
properties: Some(Arc::clone(&self.derived.properties)),
})
}
@@ -143,6 +207,13 @@ impl DesktopDocStore {
if record.filters.is_empty() {
return Vec::new();
}
if record
.filters
.iter()
.any(|filter| filter.kind == "property")
{
self.sync_custom_properties(true);
}
let views = self.views();
let scope = views.filter_scope(
self,
@@ -505,6 +576,8 @@ pub(super) mod tests {
TypeTarget, YTypeKind,
};
use affine_client::WorkspaceSession;
use super::*;
use crate::{DesktopAppState, DesktopShellView, LocalDocStore, StoredWorkspaces};
@@ -660,6 +733,138 @@ pub(super) mod tests {
assert!(store.filtered_doc_ids(&record).contains(&next));
}
#[test]
fn custom_property_collections_match_in_every_entry_point_and_rule_order() {
let storage = Rc::new(LocalUpdates::default());
for connected in [false, true] {
let check = |store: &mut DesktopDocStore| {
// A workspace without custom property filters reads no property table.
store.touch_meta();
store.views();
assert!(store.derived.properties_key.get().is_none());
let now = 1_900_000_000_000;
let a = store.create_doc("Cross memo A", DocMode::Page, None, now);
let b = store.create_doc("Cross memo B", DocMode::Page, None, now + 1);
let state = store
.create_custom_property(&a, "Review state", "text")
.unwrap();
assert!(store.set_custom_property_value(&a, &state, "ready"));
assert!(store.set_custom_property_value(&b, &state, "draft"));
store.views();
assert!(store.derived.properties_key.get().is_none());
let filter = |kind: &str, key: &str, method: &str, value: &str| CollectionFilter {
kind: kind.into(),
key: key.into(),
method: method.into(),
value: Some(value.into()),
};
let property = filter("property", &state, "is", "ready");
let title = filter("system", "title", "match", "Cross memo");
let records = [
("only", vec![property.clone()]),
("property-first", vec![property.clone(), title.clone()]),
("title-first", vec![title, property]),
]
.map(|(id, filters)| WorkspaceCollection {
id: id.into(),
name: id.into(),
allow_list: Vec::new(),
filters,
});
// The preview of a collection that is not saved reads the properties too.
for record in &records {
assert_eq!(
store.filtered_doc_ids(record),
std::slice::from_ref(&a),
"draft {}",
record.id
);
}
for record in &records {
assert!(
store.edit_navigation(NavigationEdit::CreateCollection(record.clone()))
);
}
let assert_members =
|store: &DesktopDocStore, expected: [&[&String]; 3], step: &str| {
let views = store.views();
for (record, expected) in records.iter().zip(expected) {
let mut expected: Vec<_> =
expected.iter().map(|id| (*id).clone()).collect();
expected.sort();
let mut preview = store.filtered_doc_ids(record);
preview.sort();
let mut saved: Vec<_> = store
.docs_for_collection(&record.id)
.into_iter()
.map(|doc| doc.id.clone())
.collect();
saved.sort();
let index = store
.collections
.iter()
.position(|collection| collection.id == record.id)
.unwrap();
let context = format!("connected={connected} {step} {}", record.id);
assert_eq!(preview, expected, "preview {context}");
assert_eq!(saved, expected, "saved {context}");
assert_eq!(views.collection_counts[index], expected.len(), "{context}");
}
};
assert_members(store, [&[&a], &[&a], &[&a]], "initial");
assert!(store.set_custom_property_value(&b, &state, "ready"));
assert_members(store, [&[&a, &b], &[&a, &b], &[&a, &b]], "edit");
assert!(store.set_custom_property_value(&a, &state, ""));
assert_members(store, [&[&b], &[&b], &[&b]], "clear");
// The expanded collection in the sidebar lists its members.
let mut sidebar = crate::sidebar::SidebarState::default();
sidebar
.expanded_groups
.insert(crate::sidebar_tree::TreeGroup::Collection("only".into()));
let mut index = crate::sidebar_tree::SidebarRowIndex::default();
let mut sidebar_rows = |store: &DesktopDocStore| {
index.sync(&sidebar, store, &store.views());
index.row_count()
};
let rows = sidebar_rows(store);
// A table change that the store did not make shows in every entry point at once.
let written = match store.with_session(now, |session| {
session.set_custom_property_value(&a, &state, "ready", now)
}) {
Some(result) => result.unwrap(),
None => WorkspaceSession::set_custom_property_value_in(
store.directory.db_mut(),
&a,
&state,
"ready",
)
.unwrap()
.is_some(),
};
assert!(written);
assert_members(store, [&[&a, &b], &[&a, &b], &[&a, &b]], "unseen write");
assert_eq!(sidebar_rows(store), rows + 1, "connected={connected}");
assert!(store.trash_doc(&b, now + 2));
assert_members(store, [&[&a], &[&a], &[&a]], "trash");
store.switch_workspace(1);
store.switch_workspace(0);
assert_members(store, [&[&a], &[&a], &[&a]], "workspace switch");
// A deleted property is an error: as the first filter it matches nothing, and
// after another filter the collection skips it.
assert!(store.edit_custom_property(&a, &state, None, None, true));
assert_members(store, [&[], &[], &[&a]], "deleted property");
};
if connected {
open_with_local_writes(&storage, 0, check);
} else {
check(&mut DesktopDocStore::seed_showcase("2026-12-04"));
}
}
}
#[test]
fn tag_colors_use_current_theme_and_preserve_custom_rgb() {
for (color, light, dark) in [
@@ -149,6 +149,8 @@ pub(crate) struct DocViews {
pub(crate) tags: Vec<VisibleTag>,
/// Matching visible document count of each collection, in `DesktopDocStore::collections` order.
pub(crate) collection_counts: Vec<usize>,
/// Whether a saved collection filters by a custom property.
uses_property_filters: bool,
pub(crate) folders: SidebarFolderTree,
filter_scope: OnceLock<Arc<FilterScope>>,
dated_filter_scope: Mutex<Option<(u64, Arc<FilterScope>)>>,
@@ -273,6 +275,7 @@ impl DocViews {
journals: ids(journals),
tags,
collection_counts,
uses_property_filters: store.saved_property_filters(),
filter_scope: OnceLock::new(),
dated_filter_scope: Mutex::new(None),
}
@@ -333,6 +336,8 @@ pub(crate) struct TagSearchHit {
pub(crate) matched_tags: Vec<String>,
}
type ViewsKey = (u64, Option<super::navigation::PropertiesKey>);
/// Revision counter and lazily built caches of the derived views.
#[derive(Default)]
pub(crate) struct DerivedCache {
@@ -341,11 +346,17 @@ pub(crate) struct DerivedCache {
pub(super) today: Option<affine_client::domain::CivilDate>,
/// The zone that turns document times into local dates for collection date filters.
pub(super) calendar: affine_client::domain::LocalCalendar,
/// The custom properties of the active workspace, shared by every collection filter.
pub(super) properties: Arc<affine_client::domain::PropertySource>,
/// The workspace, writer, and table revisions of the last read of `properties`.
pub(super) properties_key: Cell<Option<super::navigation::PropertiesKey>>,
/// The directory of the connected session, which holds its property tables.
pub(super) session_directory: Option<Arc<Mutex<affine_store::directory::WorkspaceDirectory>>>,
/// Advances on every change to document metadata, membership, or folder placement.
pub(crate) meta_rev: u64,
/// Advances on every change to folder rows; keys the sanitized folder forest.
folder_rev: u64,
views: RefCell<Option<(u64, Arc<DocViews>)>>,
views: RefCell<Option<(ViewsKey, Arc<DocViews>)>>,
search: RefCell<SearchCache>,
work: Cell<DerivedWork>,
}
@@ -392,8 +403,17 @@ impl DesktopDocStore {
}
}
/// The derived views of the current metadata and custom property revisions. A change to
/// the custom property tables builds the views again even when no store command made it.
pub(crate) fn views(&self) -> Arc<DocViews> {
let rev = self.derived.meta_rev;
if let Some(((meta_rev, _), views)) = self.derived.views.borrow().as_ref()
&& *meta_rev == self.derived.meta_rev
&& !views.uses_property_filters
{
return Arc::clone(views);
}
self.sync_custom_properties(false);
let rev = (self.derived.meta_rev, self.derived.properties_key.get());
if let Some((cached_rev, views)) = self.derived.views.borrow().as_ref()
&& *cached_rev == rev
{
@@ -261,6 +261,8 @@ impl RowRef {
#[derive(Clone, Debug, PartialEq, Eq)]
struct RowKey {
meta_rev: u64,
/// Collection members also change with the custom property tables.
properties_key: Option<(usize, bool, Option<u64>, Option<u64>)>,
sections: BTreeSet<SidebarSection>,
folders: BTreeSet<String>,
groups: BTreeSet<TreeGroup>,
@@ -307,10 +309,19 @@ impl SidebarRowIndex {
(content + TREE_BOTTOM - self.viewport_height).max(0.0)
}
fn sync(&mut self, sidebar: &SidebarState, store: &DesktopDocStore, views: &DocViews) {
/// Build the rows again when the metadata, the custom properties, or the expansion state
/// changed. Call it after `DesktopDocStore::views`, which reads the custom properties.
pub(crate) fn sync(
&mut self,
sidebar: &SidebarState,
store: &DesktopDocStore,
views: &DocViews,
) {
let meta_rev = store.derived.meta_rev;
let properties_key = store.properties_cache_key();
if self.key.as_ref().is_some_and(|k| {
k.meta_rev == meta_rev
&& k.properties_key == properties_key
&& k.sections == sidebar.expanded_sections
&& k.folders == sidebar.expanded_folders
&& k.groups == sidebar.expanded_groups
@@ -326,6 +337,7 @@ impl SidebarRowIndex {
match &mut self.key {
Some(key) => {
key.meta_rev = meta_rev;
key.properties_key = properties_key;
key.sections.clone_from(&sidebar.expanded_sections);
key.folders.clone_from(&sidebar.expanded_folders);
key.groups.clone_from(&sidebar.expanded_groups);
@@ -334,6 +346,7 @@ impl SidebarRowIndex {
None => {
self.key = Some(RowKey {
meta_rev,
properties_key,
sections: sidebar.expanded_sections.clone(),
folders: sidebar.expanded_folders.clone(),
groups: sidebar.expanded_groups.clone(),
@@ -0,0 +1,207 @@
//! Saved collections with custom property filters: matches, per-document allocations, and
//! allocations of the custom property reads.
use std::{
alloc::{GlobalAlloc, Layout, System},
cell::Cell,
sync::Arc,
};
use affine_client::domain::{
CivilDate, CollectionRule, CompiledCollection, DocFacts, FilterParams, FilterRule, FilterScope,
PropertyColumn, PropertyColumns, PropertyKind, PropertySource, read_property_columns,
};
use affine_desktop::{DesktopCollection, DesktopDocMeta};
use affine_store::{
directory::DocMode,
workspace_db::{WorkspaceDb, WorkspaceDbTableName},
};
use serde_json::json;
thread_local! {
static COUNTING: Cell<bool> = const { Cell::new(false) };
static BYTES: Cell<u64> = const { Cell::new(0) };
}
struct CountingAllocator;
fn record(bytes: usize) {
if COUNTING.try_with(Cell::get).unwrap_or(false) {
let _ = BYTES.try_with(|total| total.set(total.get() + bytes as u64));
}
}
// SAFETY: Delegates directly to `System` while counting allocated bytes per thread in TLS.
unsafe impl GlobalAlloc for CountingAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
record(layout.size());
unsafe { System.alloc(layout) }
}
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
record(layout.size());
unsafe { System.alloc_zeroed(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
record(new_size);
unsafe { System.realloc(ptr, layout, new_size) }
}
}
#[global_allocator]
static ALLOCATOR: CountingAllocator = CountingAllocator;
const DOCS: usize = 1_024;
const BASE_TIME: i64 = 1_796_342_400_000;
fn allocated_bytes<T>(run: impl FnOnce() -> T) -> (T, u64) {
BYTES.with(|total| total.set(0));
COUNTING.with(|counting| counting.set(true));
let output = run();
COUNTING.with(|counting| counting.set(false));
(output, BYTES.with(Cell::get))
}
#[test]
fn saved_collection_scans_allocate_nothing_per_document_with_and_without_custom_properties() {
let docs: Vec<_> = (0..DOCS)
.map(|index| DesktopDocMeta {
id: format!("doc-{index:04}"),
title: format!("Cross memo {index}"),
summary: String::new(),
default_mode: DocMode::Page,
page_width: None,
tags: Vec::new(),
is_favorite: index % 2 == 0,
trashed: false,
journal_date: None,
updated_at_ms: BASE_TIME,
outgoing_refs: Vec::new(),
})
.collect();
// Every fourth document has each value. The other documents have no value.
let column = |kind: &str, value: &dyn Fn(usize) -> String| PropertyColumn {
kind: PropertyKind::parse(kind),
values: (0..DOCS)
.step_by(4)
.map(|index| (docs[index].id.clone(), value(index)))
.collect(),
};
let columns = PropertyColumns::from([
("state".into(), column("text", &|_| "ready".into())),
("score".into(), column("number", &|index| index.to_string())),
("done".into(), column("checkbox", &|_| "true".into())),
("due".into(), column("date", &|_| "2026-12-01".into())),
]);
let scope = Arc::new(FilterScope {
today: CivilDate::parse("2026-12-04"),
properties: Some(Arc::new(PropertySource::new(columns))),
..FilterScope::default()
});
let rule = |kind: &str, key: &str, method: &str, value: &str| {
CollectionRule::Filter(FilterRule::new(
FilterParams {
kind: kind.into(),
key: key.into(),
method: method.into(),
value: Some(value.into()),
},
Arc::clone(&scope),
))
};
for (rules, expected) in [
(
vec![
rule("system", "favorite", "is", "true"),
rule("system", "title", "match", "cross memo"),
rule("system", "updatedAt", "this-month", ""),
],
DOCS / 2,
),
(vec![rule("property", "state", "is", "ready")], DOCS / 4),
(
vec![
rule("system", "title", "match", "cross memo"),
rule("property", "score", "≥", "512"),
rule("property", "done", "is", "true"),
rule("property", "due", "after", "2026-11-30"),
],
DOCS / 8,
),
(vec![rule("property", "score", "≠", "0")], DOCS / 4 - 1),
] {
let collection = DesktopCollection {
id: "collection".into(),
name: "Collection".into(),
rules,
};
let (saved, bytes) =
allocated_bytes(|| docs.iter().filter(|doc| collection.matches(doc)).count());
assert_eq!((saved, bytes), (expected, 0), "{:?}", collection.rules);
let compiled = CompiledCollection::new(&collection.rules);
let mut scratch = String::new();
let facts: Vec<_> = docs
.iter()
.map(|doc| DocFacts {
id: &doc.id,
title: &doc.title,
tags: &doc.tags,
mode: "page",
page_width: None,
favorite: doc.is_favorite,
journal: false,
trashed: false,
created: None,
updated: Some(doc.updated_at_ms),
})
.collect();
let (counted, bytes) = allocated_bytes(|| {
facts
.iter()
.filter(|doc| compiled.matches(doc, &mut scratch))
.count()
});
assert_eq!((counted, bytes), (expected, 0), "{:?}", collection.rules);
}
}
#[test]
fn custom_property_reads_copy_no_other_row_fields() {
// The size of the other text in each row, or `None` for rows without other fields.
let read = |other_text: Option<usize>| {
let mut db = WorkspaceDb::new("workspace", "user", 1);
db.upsert_db_row(
WorkspaceDbTableName::DocCustomPropertyInfo,
&json!({"id": "state", "type": "text"}),
)
.unwrap();
for index in 0..64 {
let mut row = json!({
"id": format!("doc-{index:02}"),
"custom:state": "ready",
"custom:deleted": "old",
});
if let Some(len) = other_text {
row["notes"] = json!("x".repeat(len));
row["labels"] = json!(vec!["x".repeat(len / 256); 256]);
}
db.upsert_db_row(WorkspaceDbTableName::DocProperties, &row)
.unwrap();
}
let (columns, bytes) = allocated_bytes(|| read_property_columns(&db));
assert_eq!(columns["state"].values.len(), 64);
bytes
};
// The rows hold 2 MiB of other text in all. The bytes that the read allocates do not
// depend on it.
let large = read(Some(16 * 1024));
for other in [read(Some(256)), read(None)] {
assert!(large.abs_diff(other) < 4096, "{large} B and {other} B");
}
}