mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
feat(desktop): add interactive workspace settings, properties tab, backup export, and template badge
This commit is contained in:
1 parent
39248d82a6
commit
350fec7b01
37 files changed
+8719
-274
No files matched your search
@@ -0,0 +1,510 @@
|
||||
//! Recursive body-block subtree cloning from a template `PageDocSession`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use y_octo::{Any, SessionCommit, SessionReadValue, SessionValue, TypePath, TypeTarget};
|
||||
|
||||
use crate::{
|
||||
DocError, DocResult,
|
||||
read::{BlockContent, BlockNode},
|
||||
};
|
||||
|
||||
use super::{PageDocSession, SelectionSnapshot, block_target, descendants};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ClonedBlock {
|
||||
id: String,
|
||||
entries: Vec<(String, SessionValue)>,
|
||||
children: Vec<ClonedBlock>,
|
||||
}
|
||||
|
||||
fn remap_id(id_map: &HashMap<String, String>, id: &str) -> String {
|
||||
id_map.get(id).cloned().unwrap_or_else(|| id.to_owned())
|
||||
}
|
||||
|
||||
fn remap_any(any: &Any, id_map: &HashMap<String, String>) -> Any {
|
||||
match any {
|
||||
Any::Object(obj) => Any::Object(Box::new(
|
||||
obj.iter()
|
||||
.map(|(k, v)| (remap_id(id_map, k), v.clone()))
|
||||
.collect(),
|
||||
)),
|
||||
other => other.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn clone_read_value(
|
||||
page: &PageDocSession,
|
||||
val: &SessionReadValue,
|
||||
remap_keys: Option<&HashMap<String, String>>,
|
||||
) -> DocResult<SessionValue> {
|
||||
match val {
|
||||
SessionReadValue::Any(any) => Ok(SessionValue::Any(match remap_keys {
|
||||
Some(id_map) => remap_any(any, id_map),
|
||||
None => any.clone(),
|
||||
})),
|
||||
SessionReadValue::Text(id) => Ok(SessionValue::Text(
|
||||
page.inner()
|
||||
.read_text_delta(&TypeTarget::Identity(id.clone()))?,
|
||||
)),
|
||||
SessionReadValue::Array(id) => {
|
||||
let items = page.inner().read_array(&TypeTarget::Identity(id.clone()))?;
|
||||
let mut out = Vec::with_capacity(items.len());
|
||||
for item in &items {
|
||||
out.push(clone_read_value(page, item, None)?);
|
||||
}
|
||||
Ok(SessionValue::Array(out))
|
||||
}
|
||||
SessionReadValue::Map(id) => {
|
||||
let entries = page.inner().read_map(&TypeTarget::Identity(id.clone()))?;
|
||||
let mut out = Vec::with_capacity(entries.len());
|
||||
for (k, v) in &entries {
|
||||
let next_k = remap_keys
|
||||
.and_then(|map| map.get(k))
|
||||
.cloned()
|
||||
.unwrap_or_else(|| k.clone());
|
||||
out.push((next_k, clone_read_value(page, v, None)?));
|
||||
}
|
||||
Ok(SessionValue::Map(out))
|
||||
}
|
||||
_ => Ok(SessionValue::Any(Any::Null)),
|
||||
}
|
||||
}
|
||||
|
||||
fn clone_surface_reference(
|
||||
page: &PageDocSession,
|
||||
val: &SessionReadValue,
|
||||
field: &str,
|
||||
id_map: &HashMap<String, String>,
|
||||
) -> DocResult<SessionValue> {
|
||||
match val {
|
||||
SessionReadValue::Any(Any::Object(obj)) => Ok(SessionValue::Any(Any::Object(Box::new(
|
||||
obj.iter()
|
||||
.map(|(k, v)| {
|
||||
let next_v = match (k.as_str(), v) {
|
||||
(key, Any::String(old)) if key == field => {
|
||||
Any::String(remap_id(id_map, old))
|
||||
}
|
||||
_ => v.clone(),
|
||||
};
|
||||
(k.clone(), next_v)
|
||||
})
|
||||
.collect(),
|
||||
)))),
|
||||
SessionReadValue::Map(id) => {
|
||||
let entries = page.inner().read_map(&TypeTarget::Identity(id.clone()))?;
|
||||
let mut out = Vec::with_capacity(entries.len());
|
||||
for (k, v) in &entries {
|
||||
let next_v = match (k.as_str(), v) {
|
||||
(key, SessionReadValue::Any(Any::String(old))) if key == field => {
|
||||
SessionValue::Any(Any::String(remap_id(id_map, old)))
|
||||
}
|
||||
_ => clone_read_value(page, v, None)?,
|
||||
};
|
||||
out.push((k.clone(), next_v));
|
||||
}
|
||||
Ok(SessionValue::Map(out))
|
||||
}
|
||||
other => clone_read_value(page, other, None),
|
||||
}
|
||||
}
|
||||
|
||||
fn clone_mindmap_children(
|
||||
page: &PageDocSession,
|
||||
val: &SessionReadValue,
|
||||
id_map: &HashMap<String, String>,
|
||||
) -> DocResult<SessionValue> {
|
||||
match val {
|
||||
SessionReadValue::Map(id) => {
|
||||
let entries = page.inner().read_map(&TypeTarget::Identity(id.clone()))?;
|
||||
let mut out = Vec::with_capacity(entries.len());
|
||||
for (id, detail) in &entries {
|
||||
out.push((
|
||||
remap_id(id_map, id),
|
||||
clone_surface_reference(page, detail, "parent", id_map)?,
|
||||
));
|
||||
}
|
||||
Ok(SessionValue::Map(out))
|
||||
}
|
||||
SessionReadValue::Any(Any::Object(children)) => {
|
||||
Ok(SessionValue::Any(Any::Object(Box::new(
|
||||
children
|
||||
.iter()
|
||||
.map(|(id, detail)| {
|
||||
let mut detail = detail.clone();
|
||||
if let Any::Object(fields) = &mut detail
|
||||
&& let Some(Any::String(parent)) = fields.get_mut("parent")
|
||||
&& let Some(mapped) = id_map.get(parent)
|
||||
{
|
||||
parent.clone_from(mapped);
|
||||
}
|
||||
(remap_id(id_map, id), detail)
|
||||
})
|
||||
.collect(),
|
||||
))))
|
||||
}
|
||||
other => clone_read_value(page, other, Some(id_map)),
|
||||
}
|
||||
}
|
||||
|
||||
fn clone_surface_element(
|
||||
page: &PageDocSession,
|
||||
val: &SessionReadValue,
|
||||
id_map: &HashMap<String, String>,
|
||||
) -> DocResult<SessionValue> {
|
||||
let SessionReadValue::Map(id) = val else {
|
||||
return clone_read_value(page, val, Some(id_map));
|
||||
};
|
||||
let entries = page.inner().read_map(&TypeTarget::Identity(id.clone()))?;
|
||||
let is_mindmap = entries.iter().any(|(key, value)| {
|
||||
key == "type"
|
||||
&& matches!(value, SessionReadValue::Any(Any::String(kind)) if kind == "mindmap")
|
||||
});
|
||||
let mut out = Vec::with_capacity(entries.len());
|
||||
for (k, v) in &entries {
|
||||
let next = match (k.as_str(), v) {
|
||||
("id", SessionReadValue::Any(Any::String(old))) => {
|
||||
SessionValue::Any(Any::String(remap_id(id_map, old)))
|
||||
}
|
||||
("children", _) if is_mindmap => clone_mindmap_children(page, v, id_map)?,
|
||||
("children", _) => clone_read_value(page, v, Some(id_map))?,
|
||||
("source" | "target", _) => clone_surface_reference(page, v, "id", id_map)?,
|
||||
_ => clone_read_value(page, v, None)?,
|
||||
};
|
||||
out.push((k.clone(), next));
|
||||
}
|
||||
Ok(SessionValue::Map(out))
|
||||
}
|
||||
|
||||
fn clone_surface_elements_prop(
|
||||
page: &PageDocSession,
|
||||
val: &SessionReadValue,
|
||||
id_map: &HashMap<String, String>,
|
||||
) -> DocResult<SessionValue> {
|
||||
let SessionReadValue::Map(id) = val else {
|
||||
return clone_read_value(page, val, None);
|
||||
};
|
||||
let entries = page.inner().read_map(&TypeTarget::Identity(id.clone()))?;
|
||||
let mut out = Vec::with_capacity(entries.len());
|
||||
for (k, v) in &entries {
|
||||
let next = if k == "value" {
|
||||
if let SessionReadValue::Map(values_id) = v {
|
||||
let items = page
|
||||
.inner()
|
||||
.read_map(&TypeTarget::Identity(values_id.clone()))?;
|
||||
let mut cloned = Vec::with_capacity(items.len());
|
||||
for (elem_id, elem_val) in &items {
|
||||
cloned.push((
|
||||
remap_id(id_map, elem_id),
|
||||
clone_surface_element(page, elem_val, id_map)?,
|
||||
));
|
||||
}
|
||||
SessionValue::Map(cloned)
|
||||
} else {
|
||||
clone_read_value(page, v, Some(id_map))?
|
||||
}
|
||||
} else {
|
||||
clone_read_value(page, v, None)?
|
||||
};
|
||||
out.push((k.clone(), next));
|
||||
}
|
||||
Ok(SessionValue::Map(out))
|
||||
}
|
||||
|
||||
fn read_cloned_subtree(
|
||||
source: &PageDocSession,
|
||||
node: &BlockNode,
|
||||
id_map: &HashMap<String, String>,
|
||||
) -> DocResult<ClonedBlock> {
|
||||
let new_id = id_map
|
||||
.get(&node.id)
|
||||
.cloned()
|
||||
.ok_or_else(|| DocError::InvalidState(format!("missing mapped id for {}", node.id)))?;
|
||||
let raw_entries = source.inner().read_map(&block_target(&node.id))?;
|
||||
let mut entries = Vec::with_capacity(raw_entries.len());
|
||||
for (k, v) in raw_entries {
|
||||
if k == "sys:id" {
|
||||
entries.push((k, SessionValue::Any(Any::String(new_id.clone()))));
|
||||
} else if k == "sys:children" {
|
||||
continue;
|
||||
} else if k == "prop:reference" {
|
||||
let next = match &v {
|
||||
SessionReadValue::Any(Any::String(old)) => {
|
||||
SessionValue::Any(Any::String(remap_id(id_map, old)))
|
||||
}
|
||||
other => clone_read_value(source, other, None)?,
|
||||
};
|
||||
entries.push((k, next));
|
||||
} else if k == "prop:elements" {
|
||||
entries.push((k, clone_surface_elements_prop(source, &v, id_map)?));
|
||||
} else if k == "prop:cells" || k == "prop:childElementIds" {
|
||||
entries.push((k, clone_read_value(source, &v, Some(id_map))?));
|
||||
} else {
|
||||
entries.push((k, clone_read_value(source, &v, None)?));
|
||||
}
|
||||
}
|
||||
let mut children = Vec::with_capacity(node.children.len());
|
||||
for child in &node.children {
|
||||
children.push(read_cloned_subtree(source, child, id_map)?);
|
||||
}
|
||||
Ok(ClonedBlock {
|
||||
id: new_id,
|
||||
entries,
|
||||
children,
|
||||
})
|
||||
}
|
||||
|
||||
fn write_cloned_subtree(
|
||||
page: &mut PageDocSession,
|
||||
blocks_target: &TypeTarget,
|
||||
node: ClonedBlock,
|
||||
) -> DocResult<String> {
|
||||
let mut child_ids = Vec::with_capacity(node.children.len());
|
||||
for child in node.children {
|
||||
let cid = write_cloned_subtree(page, blocks_target, child)?;
|
||||
child_ids.push(SessionValue::Any(Any::String(cid)));
|
||||
}
|
||||
let mut entries = node.entries;
|
||||
entries.push(("sys:children".to_string(), SessionValue::Array(child_ids)));
|
||||
page.session
|
||||
.map_set(blocks_target, node.id.clone(), SessionValue::Map(entries))?;
|
||||
Ok(node.id)
|
||||
}
|
||||
|
||||
impl PageDocSession {
|
||||
/// Replace all child block subtrees under this page's `affine:page` root with deep copies of
|
||||
/// `source`'s body subtrees, allocating fresh block/surface IDs while preserving this page's root title.
|
||||
pub fn clone_body_blocks_from(
|
||||
&mut self,
|
||||
source: &PageDocSession,
|
||||
fresh_id: &mut impl FnMut() -> String,
|
||||
now_ms: u64,
|
||||
) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
|
||||
let source_snap = source.read_page_snapshot()?;
|
||||
let Some(source_root) = source_snap.root.as_ref() else {
|
||||
return Ok(None);
|
||||
};
|
||||
if source_root.children.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let target_snap = self.read_page_snapshot()?;
|
||||
let Some(target_root) = target_snap.root.as_ref() else {
|
||||
return Err(DocError::InvalidState(
|
||||
"target page has no root block".into(),
|
||||
));
|
||||
};
|
||||
let target_root_id = target_root.id.clone();
|
||||
let existing_children: Vec<String> =
|
||||
target_root.children.iter().map(|c| c.id.clone()).collect();
|
||||
|
||||
let mut id_map = HashMap::new();
|
||||
for child in &source_root.children {
|
||||
for node in child.walk() {
|
||||
id_map.insert(node.id.clone(), fresh_id());
|
||||
if let BlockContent::Surface { elements, .. } = &node.content {
|
||||
for el in elements {
|
||||
id_map.entry(el.id.clone()).or_insert_with(&mut *fresh_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut cloned_roots = Vec::with_capacity(source_root.children.len());
|
||||
for child in &source_root.children {
|
||||
cloned_roots.push(read_cloned_subtree(source, child, &id_map)?);
|
||||
}
|
||||
|
||||
let (mut graph, dup_parents) = self.child_graph_with_dups()?;
|
||||
let root_had_dups = dup_parents.contains(&target_root_id);
|
||||
graph.insert(target_root_id.clone(), Vec::new());
|
||||
let candidates = descendants(&graph, existing_children);
|
||||
let external = graph
|
||||
.iter()
|
||||
.filter(|(id, _)| !candidates.contains(*id))
|
||||
.flat_map(|(_, children)| {
|
||||
children
|
||||
.iter()
|
||||
.filter(|id| candidates.contains(*id))
|
||||
.cloned()
|
||||
});
|
||||
let retained = descendants(&graph, external);
|
||||
let delete_ids: Vec<String> = candidates.difference(&retained).cloned().collect();
|
||||
|
||||
self.structural_edit(now_ms, move |page| {
|
||||
let blocks_target = TypeTarget::Path(TypePath::root("blocks"));
|
||||
let root_children_target = TypeTarget::Path(
|
||||
TypePath::root("blocks")
|
||||
.key(&target_root_id)
|
||||
.key("sys:children"),
|
||||
);
|
||||
if root_had_dups {
|
||||
page.dedup_children_in_tx(&target_root_id)?;
|
||||
}
|
||||
let existing_len = page.session.read_array(&root_children_target)?.len() as u64;
|
||||
if existing_len > 0 {
|
||||
page.session
|
||||
.array_remove(&root_children_target, 0, existing_len)?;
|
||||
}
|
||||
for id in &delete_ids {
|
||||
page.session.map_remove(&blocks_target, id)?;
|
||||
}
|
||||
let mut root_ids = Vec::with_capacity(cloned_roots.len());
|
||||
for node in cloned_roots {
|
||||
let id = write_cloned_subtree(page, &blocks_target, node)?;
|
||||
root_ids.push(SessionValue::Any(Any::String(id)));
|
||||
}
|
||||
page.session
|
||||
.array_insert(&root_children_target, 0, root_ids)?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::schema::BlockSpec;
|
||||
|
||||
#[test]
|
||||
fn cloning_frame_and_surface_ref_remaps_reference_and_undoes_in_one_step() {
|
||||
let mut tpl = PageDocSession::new("tpl", 1).expect("tpl");
|
||||
tpl.add_block(
|
||||
"root".to_string(),
|
||||
BlockSpec::Page {
|
||||
title: "Tpl".to_string(),
|
||||
},
|
||||
None,
|
||||
None,
|
||||
10,
|
||||
)
|
||||
.expect("page");
|
||||
tpl.add_block(
|
||||
"surface-1".to_string(),
|
||||
BlockSpec::Surface,
|
||||
Some("root"),
|
||||
None,
|
||||
11,
|
||||
)
|
||||
.expect("surface");
|
||||
tpl.add_block(
|
||||
"frame-1".to_string(),
|
||||
BlockSpec::Frame {
|
||||
title: "Hero Frame".to_string(),
|
||||
xywh: Some("[0,0,400,300]".to_string()),
|
||||
presentation_index: Some("a0".to_string()),
|
||||
},
|
||||
Some("surface-1"),
|
||||
None,
|
||||
12,
|
||||
)
|
||||
.expect("frame");
|
||||
tpl.add_block(
|
||||
"note-1".to_string(),
|
||||
BlockSpec::Note { xywh: None },
|
||||
Some("root"),
|
||||
None,
|
||||
13,
|
||||
)
|
||||
.expect("note");
|
||||
tpl.add_block(
|
||||
"sref-1".to_string(),
|
||||
BlockSpec::SurfaceRef {
|
||||
reference: "frame-1".to_string(),
|
||||
ref_flavour: "affine:frame".to_string(),
|
||||
caption: "Hero".to_string(),
|
||||
},
|
||||
Some("note-1"),
|
||||
None,
|
||||
14,
|
||||
)
|
||||
.expect("surface-ref");
|
||||
|
||||
let mut target = PageDocSession::new("target", 2).expect("target");
|
||||
target
|
||||
.add_block(
|
||||
"target-root".to_string(),
|
||||
BlockSpec::Page {
|
||||
title: "Daily".to_string(),
|
||||
},
|
||||
None,
|
||||
None,
|
||||
20,
|
||||
)
|
||||
.expect("target page");
|
||||
target
|
||||
.add_block(
|
||||
"initial-note".to_string(),
|
||||
BlockSpec::Note { xywh: None },
|
||||
Some("target-root"),
|
||||
None,
|
||||
21,
|
||||
)
|
||||
.expect("initial note");
|
||||
|
||||
let mut seq = 100usize;
|
||||
let commit = target
|
||||
.clone_body_blocks_from(
|
||||
&tpl,
|
||||
&mut || {
|
||||
seq += 1;
|
||||
format!("cloned-{seq}")
|
||||
},
|
||||
30,
|
||||
)
|
||||
.expect("clone")
|
||||
.expect("commit");
|
||||
assert!(!commit.update.is_empty());
|
||||
|
||||
let snap = target.read_page_snapshot().expect("snap");
|
||||
let root = snap.root.as_ref().expect("root");
|
||||
let cloned_frame = root
|
||||
.children
|
||||
.iter()
|
||||
.flat_map(|c| c.walk())
|
||||
.find(|n| matches!(n.content, BlockContent::Frame { .. }))
|
||||
.expect("cloned frame");
|
||||
assert_ne!(cloned_frame.id, "frame-1");
|
||||
let cloned_ref = root
|
||||
.children
|
||||
.iter()
|
||||
.flat_map(|c| c.walk())
|
||||
.find_map(|n| match &n.content {
|
||||
BlockContent::SurfaceRef { reference, .. } => {
|
||||
Some((n.id.clone(), reference.clone()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.expect("cloned surface-ref");
|
||||
assert_ne!(cloned_ref.0, "sref-1");
|
||||
assert_eq!(cloned_ref.1, cloned_frame.id);
|
||||
|
||||
// Cold reopen still resolves SurfaceRef -> Frame.
|
||||
let bytes = target.encode_update_v1().expect("encode");
|
||||
let mut reopened = PageDocSession::new("target", 3).expect("reopen");
|
||||
reopened.apply_remote_update_v1(&bytes).expect("apply");
|
||||
let reopened_snap = reopened.read_page_snapshot().expect("reopen snap");
|
||||
let reopened_root = reopened_snap.root.as_ref().expect("reopen root");
|
||||
let reopened_frame = reopened_root
|
||||
.children
|
||||
.iter()
|
||||
.flat_map(|c| c.walk())
|
||||
.find(|n| matches!(n.content, BlockContent::Frame { .. }))
|
||||
.expect("reopened frame");
|
||||
let reopened_ref = reopened_root
|
||||
.children
|
||||
.iter()
|
||||
.flat_map(|c| c.walk())
|
||||
.find_map(|n| match &n.content {
|
||||
BlockContent::SurfaceRef { reference, .. } => Some(reference.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("reopened ref");
|
||||
assert_eq!(reopened_ref, reopened_frame.id);
|
||||
|
||||
// Single undo restores the pre-clone subtree in one step.
|
||||
assert!(target.undo().expect("undo").is_some());
|
||||
let after_undo = target.read_page_snapshot().expect("undo snap");
|
||||
let undo_root = after_undo.root.as_ref().expect("undo root");
|
||||
let undo_child_ids: Vec<&str> = undo_root.children.iter().map(|c| c.id.as_str()).collect();
|
||||
assert_eq!(undo_child_ids, vec!["initial-note"]);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
mod clone;
|
||||
mod database;
|
||||
mod export;
|
||||
mod structure;
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
use blocksuite_playground_doc::{
|
||||
read::{BlockContent, SurfaceElementKind},
|
||||
schema::{BlockSpec, MindmapNodeSpec, SurfaceElementSpec},
|
||||
session::PageDocSession,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn cloning_a_mindmap_remaps_its_parent_and_one_undo_restores_the_body() {
|
||||
let mut source = PageDocSession::new("template", 1).expect("source");
|
||||
source
|
||||
.add_block(
|
||||
"source-root",
|
||||
BlockSpec::Page {
|
||||
title: "Template".into(),
|
||||
},
|
||||
None,
|
||||
None,
|
||||
1,
|
||||
)
|
||||
.expect("source root");
|
||||
source
|
||||
.add_block(
|
||||
"source-surface",
|
||||
BlockSpec::Surface,
|
||||
Some("source-root"),
|
||||
None,
|
||||
2,
|
||||
)
|
||||
.expect("source surface");
|
||||
for (id, index) in [("root-shape", "a1"), ("branch-shape", "a2")] {
|
||||
source
|
||||
.add_surface_element(
|
||||
"source-surface",
|
||||
id,
|
||||
index,
|
||||
SurfaceElementSpec::Shape {
|
||||
shape_type: "rect".into(),
|
||||
xywh: "[0,0,100,50]".into(),
|
||||
seed: 1,
|
||||
filled: true,
|
||||
text: Some(id.into()),
|
||||
},
|
||||
3,
|
||||
)
|
||||
.expect("node shape");
|
||||
}
|
||||
source
|
||||
.add_surface_element(
|
||||
"source-surface",
|
||||
"map",
|
||||
"a0",
|
||||
SurfaceElementSpec::Mindmap {
|
||||
seed: 1,
|
||||
style: 1,
|
||||
layout_type: 0,
|
||||
children: vec![
|
||||
(
|
||||
"root-shape".into(),
|
||||
MindmapNodeSpec {
|
||||
index: "a0".into(),
|
||||
parent: None,
|
||||
collapsed: false,
|
||||
},
|
||||
),
|
||||
(
|
||||
"branch-shape".into(),
|
||||
MindmapNodeSpec {
|
||||
index: "a1".into(),
|
||||
parent: Some("root-shape".into()),
|
||||
collapsed: true,
|
||||
},
|
||||
),
|
||||
],
|
||||
},
|
||||
4,
|
||||
)
|
||||
.expect("mindmap");
|
||||
let source_before = source.read_page_snapshot().expect("original template");
|
||||
|
||||
let mut target = PageDocSession::new("target", 2).expect("target");
|
||||
target
|
||||
.add_block(
|
||||
"target-root",
|
||||
BlockSpec::Page {
|
||||
title: "New Page".into(),
|
||||
},
|
||||
None,
|
||||
None,
|
||||
1,
|
||||
)
|
||||
.expect("target root");
|
||||
target
|
||||
.add_block(
|
||||
"initial-note",
|
||||
BlockSpec::Note { xywh: None },
|
||||
Some("target-root"),
|
||||
None,
|
||||
2,
|
||||
)
|
||||
.expect("initial note");
|
||||
let target_before = target.read_page_snapshot().expect("original target");
|
||||
let mut ids = 0;
|
||||
assert!(
|
||||
target
|
||||
.clone_body_blocks_from(
|
||||
&source,
|
||||
&mut || {
|
||||
ids += 1;
|
||||
format!("copy-{ids}")
|
||||
},
|
||||
3
|
||||
)
|
||||
.expect("clone")
|
||||
.is_some()
|
||||
);
|
||||
|
||||
let cloned = target.read_page_snapshot().expect("cloned target");
|
||||
let block = &cloned.root.as_ref().expect("target root").children[0];
|
||||
let BlockContent::Surface { elements, .. } = &block.content else {
|
||||
panic!("expected a cloned surface");
|
||||
};
|
||||
let mindmap = elements
|
||||
.iter()
|
||||
.find_map(|element| match &element.kind {
|
||||
SurfaceElementKind::Mindmap(mindmap) => Some(mindmap),
|
||||
_ => None,
|
||||
})
|
||||
.expect("cloned mindmap");
|
||||
assert_eq!(mindmap.nodes.len(), 2);
|
||||
let (root, _) = mindmap
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| node.index == "a0")
|
||||
.expect("root");
|
||||
let (branch, detail) = mindmap
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| node.index == "a1")
|
||||
.expect("branch");
|
||||
assert_ne!(root, "root-shape");
|
||||
assert_ne!(branch, "branch-shape");
|
||||
for id in [root, branch] {
|
||||
assert!(elements.iter().any(|element| &element.id == id));
|
||||
}
|
||||
assert_eq!(detail.parent.as_ref(), Some(root));
|
||||
assert!(detail.collapsed);
|
||||
assert_eq!(
|
||||
source.read_page_snapshot().expect("template after clone"),
|
||||
source_before
|
||||
);
|
||||
assert!(target.undo().expect("undo clone").is_some());
|
||||
assert_eq!(
|
||||
target.read_page_snapshot().expect("target after one undo"),
|
||||
target_before
|
||||
);
|
||||
}
|
||||
@@ -673,6 +673,16 @@ impl SqliteDocStorage {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// List every document ID present in `snapshots`, `updates`, or `clocks`.
|
||||
pub async fn list_doc_ids(&self) -> StoreResult<Vec<String>> {
|
||||
let rows = sqlx::query(
|
||||
"SELECT doc_id FROM snapshots UNION SELECT doc_id FROM updates UNION SELECT doc_id FROM clocks ORDER BY doc_id",
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
rows.iter().map(|r| Ok(r.try_get("doc_id")?)).collect()
|
||||
}
|
||||
|
||||
/// Fetch the clock row for a single document.
|
||||
pub async fn get_doc_clock(&self, doc_id: &str) -> StoreResult<Option<DocClock>> {
|
||||
let row = sqlx::query("SELECT doc_id, timestamp FROM clocks WHERE doc_id = ?")
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
//! Full local `.affine` SQLite workspace backup export for [`DesktopDocStore`].
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use affine_store::workspace_db::{USERDATA_TABLE_NAMES, WORKSPACE_DB_TABLE_NAMES, WorkspaceDb};
|
||||
|
||||
use super::DesktopDocStore;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct WorkspaceBackup {
|
||||
pub filename: String,
|
||||
pub bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
impl DesktopDocStore {
|
||||
pub fn export_workspace_updates(
|
||||
&mut self,
|
||||
) -> anyhow::Result<(String, String, Vec<(String, Vec<u8>)>)> {
|
||||
let ws = self.active_workspace();
|
||||
let space_id = ws.id.clone();
|
||||
let workspace_name = ws.name.clone();
|
||||
let mut doc_ids: BTreeSet<String> = self.docs.keys().cloned().collect();
|
||||
let now = self.writer_now();
|
||||
if let Some(res) = self.with_session(now, |session| {
|
||||
let mut updates = Vec::new();
|
||||
{
|
||||
let dir = session.directory().lock_directory();
|
||||
let db = dir.db();
|
||||
updates.push((
|
||||
space_id.clone(),
|
||||
db.root()
|
||||
.encode_update_v1()
|
||||
.map_err(|e| affine_client::ClientError::Store(e.to_string()))?,
|
||||
));
|
||||
collect_table_updates(db, &mut updates)
|
||||
.map_err(|e| affine_client::ClientError::Store(e.to_string()))?;
|
||||
}
|
||||
for (id, _) in session.open_doc_revisions() {
|
||||
doc_ids.insert(id.to_owned());
|
||||
}
|
||||
let mut extra = Vec::new();
|
||||
for id in &doc_ids {
|
||||
if let Some(bytes) = session.doc_update_v1(id) {
|
||||
updates.push((id.clone(), bytes));
|
||||
} else {
|
||||
extra.push(id.clone());
|
||||
}
|
||||
}
|
||||
Ok((updates, extra))
|
||||
}) {
|
||||
let (mut updates, extra) = res.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
for id in extra {
|
||||
if let Some(bytes) = self.export_local_doc_bytes(&id)? {
|
||||
updates.push((id, bytes));
|
||||
}
|
||||
}
|
||||
self.append_sqlite_backing_records(&mut updates)?;
|
||||
return Ok((space_id, workspace_name, updates));
|
||||
}
|
||||
|
||||
let db = self.directory.db();
|
||||
let mut updates = vec![(space_id.clone(), db.root().encode_update_v1()?)];
|
||||
collect_table_updates(db, &mut updates)?;
|
||||
for id in &doc_ids {
|
||||
if let Some(bytes) = self.export_local_doc_bytes(id)? {
|
||||
updates.push((id.clone(), bytes));
|
||||
}
|
||||
}
|
||||
self.append_sqlite_backing_records(&mut updates)?;
|
||||
Ok((space_id, workspace_name, updates))
|
||||
}
|
||||
|
||||
fn export_local_doc_bytes(&self, doc_id: &str) -> anyhow::Result<Option<Vec<u8>>> {
|
||||
let Some(entry) = self.docs.get(doc_id) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if entry.is_hydrated() {
|
||||
return Ok(Some(entry.session.encode_update_v1()?));
|
||||
}
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
if let Some(backing) = &self.sqlite_backing
|
||||
&& let Some(bytes) = backing.load_doc_update(doc_id)?
|
||||
{
|
||||
return Ok(Some(bytes));
|
||||
}
|
||||
Ok(Some(entry.session.encode_update_v1()?))
|
||||
}
|
||||
|
||||
fn append_sqlite_backing_records(
|
||||
&self,
|
||||
updates: &mut Vec<(String, Vec<u8>)>,
|
||||
) -> anyhow::Result<()> {
|
||||
#[cfg(target_family = "wasm")]
|
||||
{
|
||||
let _ = updates;
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
{
|
||||
let Some(backing) = &self.sqlite_backing else {
|
||||
return Ok(());
|
||||
};
|
||||
let existing: BTreeSet<String> = updates.iter().map(|(id, _)| id.clone()).collect();
|
||||
for doc_id in backing.list_doc_ids()? {
|
||||
if existing.contains(&doc_id) {
|
||||
continue;
|
||||
}
|
||||
if let Some(bytes) = backing.load_doc_update(&doc_id)? {
|
||||
updates.push((doc_id, bytes));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn export_workspace_backup(&mut self, now_ms: i64) -> anyhow::Result<WorkspaceBackup> {
|
||||
self.export_workspace_backup_with_blobs(&BTreeMap::new(), now_ms)
|
||||
}
|
||||
|
||||
pub fn export_workspace_backup_with_blobs(
|
||||
&mut self,
|
||||
extra_blobs: &BTreeMap<String, Vec<u8>>,
|
||||
now_ms: i64,
|
||||
) -> anyhow::Result<WorkspaceBackup> {
|
||||
#[cfg(target_family = "wasm")]
|
||||
{
|
||||
let _ = (extra_blobs, now_ms);
|
||||
anyhow::bail!("full SQLite workspace backup is only supported on native builds")
|
||||
}
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
{
|
||||
let (space_id, name, updates) = self.export_workspace_updates()?;
|
||||
let stem = sanitize_backup_stem(&name, &space_id);
|
||||
let mut blobs: BTreeMap<String, (String, Vec<u8>)> = BTreeMap::new();
|
||||
if let Some(backing) = &self.sqlite_backing {
|
||||
for (key, mime, data) in backing.load_all_blobs()? {
|
||||
blobs.insert(key, (mime, data));
|
||||
}
|
||||
}
|
||||
for (key, data) in extra_blobs {
|
||||
let mime = blobs
|
||||
.get(key)
|
||||
.map_or_else(|| "application/octet-stream".to_owned(), |(m, _)| m.clone());
|
||||
blobs.insert(key.clone(), (mime, data.clone()));
|
||||
}
|
||||
let blob_rows: Vec<(String, String, Vec<u8>)> = blobs
|
||||
.into_iter()
|
||||
.map(|(key, (mime, data))| (key, mime, data))
|
||||
.collect();
|
||||
let bytes = export_sqlite_backup_bytes(&space_id, &updates, &blob_rows, now_ms)?;
|
||||
Ok(WorkspaceBackup {
|
||||
filename: format!("{stem}.affine"),
|
||||
bytes,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_table_updates(
|
||||
db: &WorkspaceDb,
|
||||
updates: &mut Vec<(String, Vec<u8>)>,
|
||||
) -> anyhow::Result<()> {
|
||||
for &table in WORKSPACE_DB_TABLE_NAMES {
|
||||
if let Some(doc) = db.db_table(table) {
|
||||
updates.push((table.local_doc_id(), doc.encode_update_v1()?));
|
||||
}
|
||||
}
|
||||
for &table in USERDATA_TABLE_NAMES {
|
||||
if let Some(doc) = db.userdata_table(table) {
|
||||
updates.push((table.local_doc_id(db.user_id()), doc.encode_update_v1()?));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
fn sanitize_backup_stem(name: &str, fallback: &str) -> String {
|
||||
let mut stem: String = name
|
||||
.chars()
|
||||
.map(|ch| {
|
||||
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
|
||||
ch
|
||||
} else if ch.is_whitespace() {
|
||||
'-'
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
while stem.contains("--") {
|
||||
stem = stem.replace("--", "-");
|
||||
}
|
||||
let trimmed = stem.trim_matches(|ch| ch == '-' || ch == '_');
|
||||
if trimmed.is_empty() {
|
||||
fallback.to_owned()
|
||||
} else {
|
||||
trimmed.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
fn export_sqlite_backup_bytes(
|
||||
space_id: &str,
|
||||
updates: &[(String, Vec<u8>)],
|
||||
blobs: &[(String, String, Vec<u8>)],
|
||||
now_ms: i64,
|
||||
) -> anyhow::Result<Vec<u8>> {
|
||||
use affine_store::sqlite::{DocRecord, SetBlob, SqliteDocStorage, millis_to_naive_utc};
|
||||
|
||||
let nonce = blocksuite_playground_doc::try_random_client_id()?;
|
||||
let path = std::env::temp_dir().join(format!("affine-export-{nonce:x}.affine"));
|
||||
let path_str = path.to_string_lossy().into_owned();
|
||||
let space_id = space_id.to_owned();
|
||||
let timestamp = millis_to_naive_utc(now_ms);
|
||||
let result = std::thread::scope(|scope| {
|
||||
scope
|
||||
.spawn(|| -> anyhow::Result<Vec<u8>> {
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()?;
|
||||
rt.block_on(async {
|
||||
let storage = SqliteDocStorage::new(path_str.clone());
|
||||
storage.connect().await?;
|
||||
storage.set_space_id(&space_id).await?;
|
||||
for (id, bin) in updates {
|
||||
storage
|
||||
.set_doc_snapshot(&DocRecord {
|
||||
doc_id: id.clone(),
|
||||
bin: bin.clone(),
|
||||
timestamp,
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
for (key, mime, data) in blobs {
|
||||
storage
|
||||
.set_blob(SetBlob {
|
||||
key: key.clone(),
|
||||
data: data.clone(),
|
||||
mime: mime.clone(),
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
storage.checkpoint().await?;
|
||||
storage.close().await;
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})?;
|
||||
Ok(std::fs::read(&path)?)
|
||||
})
|
||||
.join()
|
||||
.map_err(|_| anyhow::anyhow!("backup export worker panicked"))?
|
||||
});
|
||||
for suffix in ["", "-wal", "-shm"] {
|
||||
let mut os = path.as_os_str().to_owned();
|
||||
os.push(suffix);
|
||||
let _ = std::fs::remove_file(std::path::Path::new(&os));
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -14,10 +14,11 @@ use affine_client::{
|
||||
|
||||
use affine_store::{
|
||||
directory::{DocMode, WorkspaceDirectory},
|
||||
workspace_db::{FolderRow, WorkspaceDb},
|
||||
workspace_db::{FolderRow, USERDATA_TABLE_NAMES, WORKSPACE_DB_TABLE_NAMES, WorkspaceDb},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub use backup::WorkspaceBackup;
|
||||
use blocksuite_playground_doc::{
|
||||
read::PageSnapshot, session::PageDocSession, try_random_client_id,
|
||||
};
|
||||
@@ -27,6 +28,7 @@ pub(crate) use explorer_prefs::{
|
||||
ExplorerPropertySnapshot, ExplorerRouteScope, ExplorerViewMode, RouteExplorerState,
|
||||
};
|
||||
pub(crate) use load::{LoadedWorkspace, load_workspace};
|
||||
pub use properties::TemplateDocSettings;
|
||||
pub(crate) use skeleton::{build_basic_doc_session, populate_note_and_surface_ids};
|
||||
pub use views::DerivedWork;
|
||||
pub(crate) use views::{
|
||||
@@ -190,7 +192,7 @@ pub struct WorkspaceBucket {
|
||||
}
|
||||
|
||||
impl WorkspaceBucket {
|
||||
fn empty_for_workspace(workspace_id: &str) -> Option<Self> {
|
||||
pub(crate) fn empty_for_workspace(workspace_id: &str) -> Option<Self> {
|
||||
let client_id = try_random_client_id().ok()?;
|
||||
let mut db = WorkspaceDb::new(workspace_id, "local-user", client_id);
|
||||
let _ = db.initialize_meta();
|
||||
@@ -257,6 +259,89 @@ impl DesktopDocStore {
|
||||
self.workspace_buckets.insert(old_idx, incoming);
|
||||
self.active_workspace_idx = index;
|
||||
self.folders_changed();
|
||||
self.sync_active_workspace_name_from_root();
|
||||
}
|
||||
|
||||
pub(crate) fn workspace_doc_ids(&self) -> Vec<String> {
|
||||
let ws = self.active_workspace();
|
||||
let user_id = self.directory.db().user_id();
|
||||
let mut ids = Vec::with_capacity(
|
||||
1 + WORKSPACE_DB_TABLE_NAMES.len() + USERDATA_TABLE_NAMES.len() + self.docs.len(),
|
||||
);
|
||||
ids.push(ws.id.clone());
|
||||
ids.extend(WORKSPACE_DB_TABLE_NAMES.iter().map(|t| t.local_doc_id()));
|
||||
ids.extend(USERDATA_TABLE_NAMES.iter().map(|t| t.local_doc_id(user_id)));
|
||||
ids.extend(self.docs.keys().cloned());
|
||||
ids
|
||||
}
|
||||
|
||||
/// Remove the active non-readonly workspace and switch to a remaining one, or rebuild a clean
|
||||
/// default local workspace when removing the last workspace.
|
||||
pub fn delete_active_workspace(&mut self) -> Option<String> {
|
||||
if self.is_readonly_sqlite() || self.workspaces.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let deleted_idx = self.active_workspace_idx;
|
||||
let deleted_id = self.workspaces[deleted_idx].id.clone();
|
||||
if self.workspaces.len() > 1 {
|
||||
let next_idx = if deleted_idx == 0 { 1 } else { 0 };
|
||||
self.switch_workspace(next_idx);
|
||||
self.workspace_buckets.remove(&deleted_idx);
|
||||
let old_buckets = std::mem::take(&mut self.workspace_buckets);
|
||||
for (idx, bucket) in old_buckets {
|
||||
let new_idx = if idx > deleted_idx { idx - 1 } else { idx };
|
||||
self.workspace_buckets.insert(new_idx, bucket);
|
||||
}
|
||||
self.workspaces.remove(deleted_idx);
|
||||
if self.active_workspace_idx > deleted_idx {
|
||||
self.active_workspace_idx -= 1;
|
||||
}
|
||||
self.touch_meta();
|
||||
} else {
|
||||
let new_id = loop {
|
||||
let candidate = if let Ok(nonce) = blocksuite_playground_doc::try_random_client_id()
|
||||
{
|
||||
format!("ws-local-{nonce:x}")
|
||||
} else {
|
||||
self.next_seq += 1;
|
||||
format!("ws-local-default-{}", self.next_seq)
|
||||
};
|
||||
if candidate != deleted_id {
|
||||
break candidate;
|
||||
}
|
||||
};
|
||||
let mut bucket = WorkspaceBucket::empty_for_workspace(&new_id)?;
|
||||
if let Some(diff) = mutations::write_root_workspace_name(
|
||||
bucket.directory.db().root(),
|
||||
"Local Workspace",
|
||||
) {
|
||||
let _ = bucket.directory.db_mut().apply_remote_root_update(&diff);
|
||||
}
|
||||
let _ = bucket.directory.db_mut().drain_pending_updates();
|
||||
self.unbind_writer();
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
{
|
||||
self.sqlite_backing = None;
|
||||
}
|
||||
self.workspace_buckets.clear();
|
||||
self.workspaces = vec![DesktopWorkspace {
|
||||
id: new_id,
|
||||
name: "Local Workspace".into(),
|
||||
kind: WorkspaceKind::Local,
|
||||
synced: true,
|
||||
}];
|
||||
self.active_workspace_idx = 0;
|
||||
self.directory = bucket.directory;
|
||||
self.docs = bucket.docs;
|
||||
self.folder_rows = bucket.folder_rows;
|
||||
*self.folder_cache.get_mut() = bucket.folder_cache;
|
||||
self.collections = bucket.collections;
|
||||
self.tag_colors = bucket.tag_colors;
|
||||
self.link_graph = bucket.link_graph;
|
||||
self.reindex_all();
|
||||
self.touch_meta();
|
||||
}
|
||||
Some(deleted_id)
|
||||
}
|
||||
|
||||
pub fn page_titles(&self) -> BTreeMap<String, String> {
|
||||
@@ -495,6 +580,7 @@ impl DesktopDocStore {
|
||||
}
|
||||
}
|
||||
|
||||
mod backup;
|
||||
mod database_backlinks;
|
||||
mod explorer_prefs;
|
||||
mod hydration;
|
||||
@@ -506,5 +592,6 @@ mod reorder;
|
||||
#[cfg(test)]
|
||||
pub(crate) use navigation::tests::LocalUpdates;
|
||||
mod skeleton;
|
||||
mod template;
|
||||
mod views;
|
||||
mod writer;
|
||||
@@ -9,16 +9,17 @@ use std::rc::Rc;
|
||||
use affine_client::{ClientError, EditorDocMode, LinkGraph};
|
||||
use affine_store::{
|
||||
directory::{CreateDocId, CreateDocRequest, DocId, DocMode},
|
||||
workspace_db::derive_page_id_for_op,
|
||||
workspace_db::{PendingDocUpdate, derive_page_id_for_op},
|
||||
};
|
||||
use blocksuite_playground_doc::{
|
||||
read::{BlockContent, BlockNode},
|
||||
refs::{DocRefEdge, OutboundRefKind, extract_outbound_doc_refs},
|
||||
schema::{BlockSpec, ParagraphType},
|
||||
session::PageDocSession,
|
||||
try_random_client_id,
|
||||
};
|
||||
|
||||
use super::template::clone_template_body;
|
||||
pub(super) use super::template::{read_root_workspace_name, write_root_workspace_name};
|
||||
use super::{
|
||||
DesktopDocMeta, DesktopDocStore, DocHydrationState, LiveDocEntry, OutlineHeading,
|
||||
build_basic_doc_session, populate_note_and_surface_ids,
|
||||
@@ -115,6 +116,22 @@ impl DesktopDocStore {
|
||||
{
|
||||
return id.clone();
|
||||
}
|
||||
let template_id = if intent_id.is_none() {
|
||||
let tpl_settings = self.template_settings();
|
||||
let candidate = if journal_date.is_some() {
|
||||
tpl_settings.journal_template_id
|
||||
} else if tpl_settings.enable_page_template {
|
||||
tpl_settings.page_template_id
|
||||
} else {
|
||||
None
|
||||
};
|
||||
candidate.filter(|tpl_id| self.docs.get(tpl_id).is_some_and(|e| !e.meta.trashed))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(ref tpl_id) = template_id {
|
||||
let _ = self.ensure_doc_hydrated(tpl_id);
|
||||
}
|
||||
let Ok(client_id) = try_random_client_id() else {
|
||||
return String::new();
|
||||
};
|
||||
@@ -149,7 +166,7 @@ impl DesktopDocStore {
|
||||
.ok_or_else(|| ClientError::DocNotFound(id.clone()))?;
|
||||
Ok((id, Some(bytes)))
|
||||
});
|
||||
let (id, session, note_id, surface_id) = match created {
|
||||
let (id, mut session, note_id, surface_id) = match created {
|
||||
Some(Ok((id, None))) => return id,
|
||||
Some(Ok((id, Some(bytes)))) => {
|
||||
let Ok(mut session) = PageDocSession::new(&id, client_id) else {
|
||||
@@ -175,6 +192,14 @@ impl DesktopDocStore {
|
||||
(id, session, note_id, surface_id)
|
||||
}
|
||||
};
|
||||
let (template_delta, cloned_summary) = if let Some(ref tpl_id) = template_id
|
||||
&& let Some(tpl_entry) = self.docs.get(tpl_id)
|
||||
{
|
||||
clone_template_body(tpl_entry, &mut session, &mut self.next_seq, now_ms as u64)
|
||||
.map_or((None, None), |(diff, summary)| (Some(diff), summary))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
let Ok(typed_id) = DocId::new(id.clone()) else {
|
||||
return String::new();
|
||||
};
|
||||
@@ -203,7 +228,7 @@ impl DesktopDocStore {
|
||||
meta: DesktopDocMeta {
|
||||
id: id.clone(),
|
||||
title,
|
||||
summary: NEW_DOC_SUMMARY.into(),
|
||||
summary: cloned_summary.unwrap_or_else(|| NEW_DOC_SUMMARY.into()),
|
||||
default_mode: mode,
|
||||
page_width: None,
|
||||
tags,
|
||||
@@ -223,6 +248,10 @@ impl DesktopDocStore {
|
||||
let snap = entry.snapshot.clone();
|
||||
populate_note_and_surface_ids(&mut entry, &snap);
|
||||
self.docs.insert(id.clone(), entry);
|
||||
if let Some(delta) = template_delta {
|
||||
self.enqueue_doc_update(&id, delta);
|
||||
let _ = self.with_session(now_ms, |_| Ok(()));
|
||||
}
|
||||
self.index_doc_links(&id);
|
||||
self.touch_meta();
|
||||
id
|
||||
@@ -572,6 +601,7 @@ impl DesktopDocStore {
|
||||
/// Index every document link and resolve the folder forest after a bulk load.
|
||||
pub(crate) fn reindex_all(&mut self) {
|
||||
self.load_navigation();
|
||||
self.sync_active_workspace_name_from_root();
|
||||
self.link_graph = LinkGraph::default();
|
||||
for entry in self.docs.values() {
|
||||
if entry.meta.trashed {
|
||||
@@ -584,6 +614,75 @@ impl DesktopDocStore {
|
||||
self.folders_changed();
|
||||
}
|
||||
|
||||
pub(crate) fn sync_active_workspace_name_from_root(&mut self) {
|
||||
if let Some(name) = read_root_workspace_name(self.directory.db().root()) {
|
||||
let trimmed = name.trim();
|
||||
if !trimmed.is_empty() {
|
||||
self.workspaces[self.active_workspace_idx].name = trimmed.to_owned();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rename the active workspace and write `meta.name` into `WorkspaceRootDoc`.
|
||||
pub fn rename_workspace(&mut self, new_name: &str) -> bool {
|
||||
if self.is_readonly_sqlite() {
|
||||
return false;
|
||||
}
|
||||
let trimmed = new_name.trim();
|
||||
if trimmed.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let root_name = read_root_workspace_name(self.directory.db().root());
|
||||
if self.workspaces[self.active_workspace_idx].name == trimmed
|
||||
&& root_name.as_deref() == Some(trimmed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let space_id = self.active_workspace().id.clone();
|
||||
let now = self.writer_now();
|
||||
let session_diff = self.with_session(now, |session| {
|
||||
let diff = {
|
||||
let mut dir = session.directory().lock_directory();
|
||||
let diff = write_root_workspace_name(dir.db().root(), trimmed);
|
||||
if let Some(bytes) = &diff {
|
||||
dir.db_mut()
|
||||
.apply_remote_root_update(bytes)
|
||||
.map_err(|err| ClientError::Store(err.to_string()))?;
|
||||
}
|
||||
diff
|
||||
};
|
||||
if let Some(bytes) = &diff {
|
||||
session.queue_doc_update(&space_id, bytes.clone(), now)?;
|
||||
session.enqueue_pending_persist_updates(vec![PendingDocUpdate {
|
||||
doc_id: space_id.clone(),
|
||||
update: bytes.clone(),
|
||||
}]);
|
||||
}
|
||||
Ok(diff)
|
||||
});
|
||||
match session_diff {
|
||||
Some(Ok(Some(bytes))) => {
|
||||
let _ = self.directory.db_mut().apply_remote_root_update(&bytes);
|
||||
}
|
||||
Some(Ok(None)) => {}
|
||||
Some(Err(_)) => return false,
|
||||
None => {
|
||||
if let Some(bytes) = write_root_workspace_name(self.directory.db().root(), trimmed)
|
||||
&& self
|
||||
.directory
|
||||
.db_mut()
|
||||
.apply_remote_root_update(&bytes)
|
||||
.is_err()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.workspaces[self.active_workspace_idx].name = trimmed.to_owned();
|
||||
self.touch_meta();
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn register_seeded(
|
||||
&mut self,
|
||||
meta: DesktopDocMeta,
|
||||
@@ -626,8 +725,11 @@ impl DesktopDocStore {
|
||||
}
|
||||
}
|
||||
|
||||
fn heading_from_node(node: &BlockNode) -> Option<(&str, u8, &str)> {
|
||||
let BlockContent::Paragraph { kind, text, .. } = &node.content else {
|
||||
fn heading_from_node(
|
||||
node: &blocksuite_playground_doc::read::BlockNode,
|
||||
) -> Option<(&str, u8, &str)> {
|
||||
let blocksuite_playground_doc::read::BlockContent::Paragraph { kind, text, .. } = &node.content
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let level = match kind {
|
||||
@@ -820,4 +922,299 @@ mod tests {
|
||||
);
|
||||
assert_eq!(store.link_graph.outbound_edges("doc-sync").len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_rename_writes_root_meta_and_delete_switches_or_rebuilds_clean_workspace() {
|
||||
let mut store = DesktopDocStore::seed_showcase("2026-12-02");
|
||||
let initial_id = store.active_workspace().id.clone();
|
||||
assert!(!store.rename_workspace(" "));
|
||||
assert!(store.rename_workspace("Design Handbook"));
|
||||
assert_eq!(store.active_workspace().name, "Design Handbook");
|
||||
assert_eq!(
|
||||
read_root_workspace_name(store.directory.db().root()).as_deref(),
|
||||
Some("Design Handbook")
|
||||
);
|
||||
|
||||
let second_bucket =
|
||||
crate::doc_store::WorkspaceBucket::empty_for_workspace("ws-second").expect("bucket");
|
||||
store.workspaces.push(crate::doc_store::DesktopWorkspace {
|
||||
id: "ws-second".into(),
|
||||
name: "Second Space".into(),
|
||||
kind: crate::doc_store::WorkspaceKind::Local,
|
||||
synced: true,
|
||||
});
|
||||
let second_idx = store.workspaces.len() - 1;
|
||||
store.workspace_buckets.insert(second_idx, second_bucket);
|
||||
store.switch_workspace(second_idx);
|
||||
assert_eq!(store.active_workspace().id, "ws-second");
|
||||
|
||||
assert_eq!(
|
||||
store.delete_active_workspace().as_deref(),
|
||||
Some("ws-second")
|
||||
);
|
||||
assert_eq!(store.workspaces.len(), 2);
|
||||
assert_eq!(store.active_workspace().id, initial_id);
|
||||
assert_eq!(store.active_workspace().name, "Design Handbook");
|
||||
|
||||
let next_rem = store.workspaces[1].id.clone();
|
||||
assert_eq!(
|
||||
store.delete_active_workspace().as_deref(),
|
||||
Some(initial_id.as_str())
|
||||
);
|
||||
assert_eq!(store.workspaces.len(), 1);
|
||||
assert_eq!(store.active_workspace().id, next_rem);
|
||||
|
||||
assert_eq!(
|
||||
store.delete_active_workspace().as_deref(),
|
||||
Some(next_rem.as_str())
|
||||
);
|
||||
assert_eq!(store.workspaces.len(), 1);
|
||||
assert_ne!(store.active_workspace().id, next_rem);
|
||||
assert_eq!(store.active_workspace().name, "Local Workspace");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_and_journal_templates_clone_body_and_survive_cold_reopen() {
|
||||
use blocksuite_playground_doc::read::BlockContent;
|
||||
use ui_tokens::ThemeMode;
|
||||
|
||||
const NOW: i64 = 1_764_400_000;
|
||||
let storage = std::rc::Rc::new(crate::doc_store::LocalUpdates::default());
|
||||
let (state, sessions) = crate::DesktopAppState::open_local(
|
||||
&storage.0.borrow(),
|
||||
ThemeMode::Light,
|
||||
"2026-12-02",
|
||||
NOW,
|
||||
)
|
||||
.expect("open showcase");
|
||||
let (platform, app, handle, _) =
|
||||
crate::editor_host::tests::open_test_shell(state, 1280, 800);
|
||||
|
||||
let body_texts_and_ids = |doc: &DesktopDocStore, id: &str| -> (Vec<String>, Vec<String>) {
|
||||
let entry = doc.get_doc(id).expect("doc exists");
|
||||
let root = entry.snapshot.root.as_ref().expect("root snapshot");
|
||||
let mut ids = Vec::new();
|
||||
let mut texts = Vec::new();
|
||||
for child in &root.children {
|
||||
if !child.is_page_visible_note() {
|
||||
continue;
|
||||
}
|
||||
for node in child.walk() {
|
||||
ids.push(node.id.clone());
|
||||
let text = match &node.content {
|
||||
BlockContent::Paragraph { text, .. } | BlockContent::List { text, .. } => {
|
||||
text.plain.clone()
|
||||
}
|
||||
_ => String::new(),
|
||||
};
|
||||
if !text.trim().is_empty() {
|
||||
texts.push(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
(ids, texts)
|
||||
};
|
||||
|
||||
let assert_cloned_frame_ref = |doc: &DesktopDocStore, id: &str| {
|
||||
let entry = doc.get_doc(id).expect("doc exists");
|
||||
let root = entry.snapshot.root.as_ref().expect("root snapshot");
|
||||
let frame_id = root
|
||||
.children
|
||||
.iter()
|
||||
.flat_map(|c| c.walk())
|
||||
.find_map(|n| matches!(n.content, BlockContent::Frame { .. }).then(|| n.id.clone()))
|
||||
.expect("cloned frame");
|
||||
assert_ne!(frame_id, "tpl-frame-1");
|
||||
let ref_target = root
|
||||
.children
|
||||
.iter()
|
||||
.flat_map(|c| c.walk())
|
||||
.find_map(|n| match &n.content {
|
||||
BlockContent::SurfaceRef { reference, .. } => Some(reference.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("cloned surface ref");
|
||||
assert_eq!(ref_target, frame_id);
|
||||
};
|
||||
|
||||
let (tpl_id, page_id, journal_id, linked_id, plain_id, tpl_body_ids) = app.update(|app| {
|
||||
handle
|
||||
.update(app, |shell, _, cx| {
|
||||
let local_ws = shell.bind_local_workspaces(sessions, storage.clone(), NOW, cx);
|
||||
let store = &mut shell.state.store;
|
||||
let tpl_id =
|
||||
store.create_doc("Meeting Template", DocMode::Page, None, NOW + 10);
|
||||
assert!(!tpl_id.is_empty());
|
||||
assert!(
|
||||
store
|
||||
.append_paragraph(&tpl_id, "Template Intro", NOW + 11)
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
store
|
||||
.append_paragraph(&tpl_id, "Verify exports", NOW + 12)
|
||||
.is_some()
|
||||
);
|
||||
let tpl_delta = {
|
||||
let tpl_entry = store.docs.get_mut(&tpl_id).expect("tpl entry");
|
||||
let before = tpl_entry.session.encode_state_vector_v1().expect("tpl sv");
|
||||
let root_id = tpl_entry
|
||||
.snapshot
|
||||
.root
|
||||
.as_ref()
|
||||
.expect("tpl root")
|
||||
.id
|
||||
.clone();
|
||||
let note_id = tpl_entry
|
||||
.snapshot
|
||||
.root
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.children
|
||||
.iter()
|
||||
.find(|c| c.is_page_visible_note())
|
||||
.expect("tpl note")
|
||||
.id
|
||||
.clone();
|
||||
tpl_entry
|
||||
.session
|
||||
.add_block(
|
||||
"tpl-surface-1",
|
||||
blocksuite_playground_doc::schema::BlockSpec::Surface,
|
||||
Some(&root_id),
|
||||
Some(0),
|
||||
(NOW + 13) as u64,
|
||||
)
|
||||
.expect("tpl surface");
|
||||
tpl_entry
|
||||
.session
|
||||
.add_block(
|
||||
"tpl-frame-1",
|
||||
blocksuite_playground_doc::schema::BlockSpec::Frame {
|
||||
title: "Tpl Frame".into(),
|
||||
xywh: Some("[0,0,320,200]".into()),
|
||||
presentation_index: Some("a0".into()),
|
||||
},
|
||||
Some("tpl-surface-1"),
|
||||
None,
|
||||
(NOW + 14) as u64,
|
||||
)
|
||||
.expect("tpl frame");
|
||||
tpl_entry
|
||||
.session
|
||||
.add_block(
|
||||
"tpl-sref-1",
|
||||
blocksuite_playground_doc::schema::BlockSpec::SurfaceRef {
|
||||
reference: "tpl-frame-1".into(),
|
||||
ref_flavour: "affine:frame".into(),
|
||||
caption: "Frame Ref".into(),
|
||||
},
|
||||
Some(¬e_id),
|
||||
None,
|
||||
(NOW + 15) as u64,
|
||||
)
|
||||
.expect("tpl surface ref");
|
||||
tpl_entry.snapshot =
|
||||
tpl_entry.session.read_page_snapshot().expect("tpl snap");
|
||||
tpl_entry.revision = tpl_entry.session.revision();
|
||||
tpl_entry
|
||||
.session
|
||||
.encode_diff_v1(&before)
|
||||
.expect("tpl delta")
|
||||
};
|
||||
store.enqueue_doc_update(&tpl_id, tpl_delta);
|
||||
assert!(store.set_doc_is_template(&tpl_id, true));
|
||||
assert!(
|
||||
store.set_template_settings(crate::doc_store::TemplateDocSettings {
|
||||
enable_page_template: true,
|
||||
page_template_id: Some(tpl_id.clone()),
|
||||
journal_template_id: Some(tpl_id.clone()),
|
||||
})
|
||||
);
|
||||
|
||||
let (tpl_ids, tpl_texts) = body_texts_and_ids(store, &tpl_id);
|
||||
assert_eq!(tpl_texts, vec!["Template Intro", "Verify exports"]);
|
||||
|
||||
let page_id = store.create_doc("Project Plan", DocMode::Page, None, NOW + 100);
|
||||
let (page_ids, page_texts) = body_texts_and_ids(store, &page_id);
|
||||
assert_eq!(page_texts, vec!["Template Intro", "Verify exports"]);
|
||||
assert!(page_ids.iter().all(|id| !tpl_ids.contains(id)));
|
||||
assert!(!store.doc_is_template(&page_id));
|
||||
assert_cloned_frame_ref(store, &page_id);
|
||||
|
||||
let journal_id = store.create_doc(
|
||||
"2026-12-03",
|
||||
DocMode::Page,
|
||||
Some("2026-12-03".into()),
|
||||
NOW + 200,
|
||||
);
|
||||
let (_, journal_texts) = body_texts_and_ids(store, &journal_id);
|
||||
assert_eq!(journal_texts, vec!["Template Intro", "Verify exports"]);
|
||||
assert!(!store.doc_is_template(&journal_id));
|
||||
assert_cloned_frame_ref(store, &journal_id);
|
||||
assert_eq!(
|
||||
store
|
||||
.get_doc(&journal_id)
|
||||
.unwrap()
|
||||
.meta
|
||||
.journal_date
|
||||
.as_deref(),
|
||||
Some("2026-12-03")
|
||||
);
|
||||
|
||||
let linked_id = store.create_linked_doc(
|
||||
"Inline Ref".into(),
|
||||
DocMode::Page,
|
||||
NOW + 300,
|
||||
"inline-intent-1",
|
||||
);
|
||||
let (_, linked_texts) = body_texts_and_ids(store, &linked_id);
|
||||
assert!(linked_texts.is_empty());
|
||||
|
||||
assert!(
|
||||
store.set_template_settings(crate::doc_store::TemplateDocSettings {
|
||||
enable_page_template: false,
|
||||
page_template_id: Some(tpl_id.clone()),
|
||||
journal_template_id: Some(tpl_id.clone()),
|
||||
})
|
||||
);
|
||||
let plain_id = store.create_doc("Plain Note", DocMode::Page, None, NOW + 400);
|
||||
let (_, plain_texts) = body_texts_and_ids(store, &plain_id);
|
||||
assert!(plain_texts.is_empty());
|
||||
|
||||
shell.flush_persistence();
|
||||
local_ws.save();
|
||||
(tpl_id, page_id, journal_id, linked_id, plain_id, tpl_ids)
|
||||
})
|
||||
.unwrap()
|
||||
});
|
||||
platform.run_until_parked();
|
||||
|
||||
let (mut reopened, _) = crate::DesktopAppState::open_local(
|
||||
&storage.0.borrow(),
|
||||
ThemeMode::Light,
|
||||
"2026-12-02",
|
||||
NOW + 500,
|
||||
)
|
||||
.expect("reopen local");
|
||||
reopened
|
||||
.store
|
||||
.ensure_doc_hydrated(&page_id)
|
||||
.expect("hydrate page");
|
||||
reopened
|
||||
.store
|
||||
.ensure_doc_hydrated(&journal_id)
|
||||
.expect("hydrate journal");
|
||||
let (re_page_ids, re_page_texts) = body_texts_and_ids(&reopened.store, &page_id);
|
||||
assert_eq!(re_page_texts, vec!["Template Intro", "Verify exports"]);
|
||||
assert!(re_page_ids.iter().all(|id| !tpl_body_ids.contains(id)));
|
||||
assert_cloned_frame_ref(&reopened.store, &page_id);
|
||||
let (_, re_journal_texts) = body_texts_and_ids(&reopened.store, &journal_id);
|
||||
assert_eq!(re_journal_texts, vec!["Template Intro", "Verify exports"]);
|
||||
assert_cloned_frame_ref(&reopened.store, &journal_id);
|
||||
assert!(reopened.store.doc_is_template(&tpl_id));
|
||||
assert!(!reopened.store.doc_is_template(&page_id));
|
||||
assert!(reopened.store.get_doc(&linked_id).is_some());
|
||||
assert!(reopened.store.get_doc(&plain_id).is_some());
|
||||
}
|
||||
}
|
||||
@@ -3,13 +3,29 @@
|
||||
use affine_client::{ClientResult, WorkspaceSession};
|
||||
use affine_store::{
|
||||
directory::DocMode,
|
||||
workspace_db::{DocCustomPropertyInfoRow, WorkspaceDb, WorkspaceDbTableName},
|
||||
workspace_db::{
|
||||
DocCustomPropertyInfoRow, PendingDocUpdate, SettingsRow, UserdataTableName, WorkspaceDb,
|
||||
WorkspaceDbTableName,
|
||||
},
|
||||
};
|
||||
use serde_json::json;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value as JsonValue, json};
|
||||
|
||||
use super::{DesktopDocMeta, DesktopDocStore, PageWidth};
|
||||
|
||||
const DOC_PROPERTIES: WorkspaceDbTableName = WorkspaceDbTableName::DocProperties;
|
||||
const TEMPLATE_DOC_SETTING_KEY: &str = "templateDoc";
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TemplateDocSettings {
|
||||
#[serde(default)]
|
||||
pub enable_page_template: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub page_template_id: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub journal_template_id: Option<String>,
|
||||
}
|
||||
|
||||
impl DesktopDocStore {
|
||||
pub(crate) fn custom_property_rows(
|
||||
@@ -71,6 +87,314 @@ impl DesktopDocStore {
|
||||
)
|
||||
}
|
||||
|
||||
pub fn workspace_custom_properties(&mut self) -> Vec<DocCustomPropertyInfoRow> {
|
||||
let now = self.writer_now();
|
||||
let rows = match self.with_session(now, |session| {
|
||||
let directory = session.directory().lock_directory();
|
||||
Ok(WorkspaceSession::custom_property_definitions(
|
||||
directory.db(),
|
||||
))
|
||||
}) {
|
||||
Some(result) => result.unwrap_or_default(),
|
||||
None => WorkspaceSession::custom_property_definitions(self.directory.db()),
|
||||
};
|
||||
rows.into_iter()
|
||||
.filter(|row| row.is_deleted != Some(true))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn workspace_property_doc_count(&mut self, id: &str) -> usize {
|
||||
let field = format!("custom:{id}");
|
||||
let doc_ids: Vec<String> = self
|
||||
.docs
|
||||
.values()
|
||||
.filter(|entry| !entry.meta.trashed)
|
||||
.map(|entry| entry.meta.id.clone())
|
||||
.collect();
|
||||
let count_in = |db: &WorkspaceDb| {
|
||||
let Some(table) = db.db_table(DOC_PROPERTIES) else {
|
||||
return 0;
|
||||
};
|
||||
doc_ids
|
||||
.iter()
|
||||
.filter(|doc_id| {
|
||||
table
|
||||
.get_raw_row(doc_id)
|
||||
.and_then(|row| row.get(&field).cloned())
|
||||
.is_some_and(|val| match val {
|
||||
JsonValue::Bool(flag) => flag,
|
||||
JsonValue::String(text) => !text.is_empty(),
|
||||
JsonValue::Null => false,
|
||||
_ => true,
|
||||
})
|
||||
})
|
||||
.count()
|
||||
};
|
||||
let now = self.writer_now();
|
||||
match self.with_session(now, |session| {
|
||||
Ok(count_in(session.directory().lock_directory().db()))
|
||||
}) {
|
||||
Some(Ok(count)) => count,
|
||||
_ => count_in(self.directory.db()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_workspace_custom_property(&mut self, name: &str, kind: &str) -> Option<String> {
|
||||
if self.is_readonly_sqlite() {
|
||||
return None;
|
||||
}
|
||||
let now = self.writer_now();
|
||||
let (id, table_sync) = match self.with_session(now, |session| {
|
||||
let id = session.create_custom_property(name, kind, now)?;
|
||||
let sync = session
|
||||
.directory()
|
||||
.lock_directory()
|
||||
.db()
|
||||
.db_table(WorkspaceDbTableName::DocCustomPropertyInfo)
|
||||
.and_then(|t| t.encode_update_v1().ok());
|
||||
Ok((id, sync))
|
||||
}) {
|
||||
Some(Ok((id, sync))) => (id, sync),
|
||||
Some(Err(_)) => return None,
|
||||
None => {
|
||||
let id = WorkspaceSession::create_custom_property_in(
|
||||
self.directory.db_mut(),
|
||||
name,
|
||||
kind,
|
||||
)
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|(id, _)| id);
|
||||
(id, None)
|
||||
}
|
||||
};
|
||||
if let Some(bytes) = table_sync {
|
||||
let _ = self
|
||||
.directory
|
||||
.db_mut()
|
||||
.load_db_table(WorkspaceDbTableName::DocCustomPropertyInfo, &bytes);
|
||||
}
|
||||
if id.is_some() {
|
||||
self.touch_meta();
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
pub fn edit_workspace_custom_property(
|
||||
&mut self,
|
||||
id: &str,
|
||||
name: Option<&str>,
|
||||
show: Option<&str>,
|
||||
delete: bool,
|
||||
) -> bool {
|
||||
if self.is_readonly_sqlite() {
|
||||
return false;
|
||||
}
|
||||
let now = self.writer_now();
|
||||
let (changed, table_sync) = match self.with_session(now, |session| {
|
||||
let changed = session.edit_custom_property(id, name, show, delete, now)?;
|
||||
let sync = session
|
||||
.directory()
|
||||
.lock_directory()
|
||||
.db()
|
||||
.db_table(WorkspaceDbTableName::DocCustomPropertyInfo)
|
||||
.and_then(|t| t.encode_update_v1().ok());
|
||||
Ok((changed, sync))
|
||||
}) {
|
||||
Some(Ok((changed, sync))) => (changed, sync),
|
||||
Some(Err(_)) => return false,
|
||||
None => (
|
||||
WorkspaceSession::edit_custom_property_in(
|
||||
self.directory.db_mut(),
|
||||
id,
|
||||
name,
|
||||
show,
|
||||
delete,
|
||||
)
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some(),
|
||||
None,
|
||||
),
|
||||
};
|
||||
if let Some(bytes) = table_sync {
|
||||
let _ = self
|
||||
.directory
|
||||
.db_mut()
|
||||
.load_db_table(WorkspaceDbTableName::DocCustomPropertyInfo, &bytes);
|
||||
}
|
||||
if changed {
|
||||
self.touch_meta();
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
pub fn doc_is_template(&self, doc_id: &str) -> bool {
|
||||
self.directory
|
||||
.db()
|
||||
.db_table(DOC_PROPERTIES)
|
||||
.and_then(|table| table.get_raw_row(doc_id))
|
||||
.and_then(|row| row.get("isTemplate").and_then(JsonValue::as_bool))
|
||||
== Some(true)
|
||||
}
|
||||
|
||||
pub fn set_doc_is_template(&mut self, doc_id: &str, is_template: bool) -> bool {
|
||||
let Some(entry) = self.get_doc(doc_id) else {
|
||||
return false;
|
||||
};
|
||||
if self.is_readonly_sqlite() || entry.meta.trashed {
|
||||
return false;
|
||||
}
|
||||
if self.doc_is_template(doc_id) == is_template {
|
||||
return false;
|
||||
}
|
||||
let default_mode = entry.meta.default_mode;
|
||||
let now = self.writer_now();
|
||||
let session_sync = self.with_session(now, |session| {
|
||||
let diff = {
|
||||
let mut dir = session.directory().lock_directory();
|
||||
patch_local_property(
|
||||
dir.db_mut(),
|
||||
doc_id,
|
||||
"isTemplate",
|
||||
json!(is_template),
|
||||
default_mode,
|
||||
)?
|
||||
};
|
||||
if let Some(bytes) = diff {
|
||||
let doc_id = DOC_PROPERTIES.local_doc_id();
|
||||
let _ = session.queue_doc_update(&doc_id, bytes.clone(), now);
|
||||
session.enqueue_pending_persist_updates(vec![PendingDocUpdate {
|
||||
doc_id,
|
||||
update: bytes,
|
||||
}]);
|
||||
}
|
||||
Ok(session
|
||||
.directory()
|
||||
.lock_directory()
|
||||
.db()
|
||||
.db_table(DOC_PROPERTIES)
|
||||
.and_then(|t| t.encode_update_v1().ok()))
|
||||
});
|
||||
match session_sync {
|
||||
Some(Ok(Some(bytes))) => {
|
||||
let _ = self
|
||||
.directory
|
||||
.db_mut()
|
||||
.load_db_table(DOC_PROPERTIES, &bytes);
|
||||
}
|
||||
Some(Ok(None)) => {}
|
||||
Some(Err(_)) => return false,
|
||||
None => {
|
||||
if patch_local_property(
|
||||
self.directory.db_mut(),
|
||||
doc_id,
|
||||
"isTemplate",
|
||||
json!(is_template),
|
||||
default_mode,
|
||||
)
|
||||
.is_err()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.touch_meta();
|
||||
true
|
||||
}
|
||||
|
||||
pub fn template_docs(&self) -> Vec<&DesktopDocMeta> {
|
||||
let mut docs: Vec<_> = self
|
||||
.docs
|
||||
.values()
|
||||
.filter(|entry| !entry.meta.trashed && self.doc_is_template(&entry.meta.id))
|
||||
.map(|entry| &entry.meta)
|
||||
.collect();
|
||||
docs.sort_by(|a, b| {
|
||||
a.title
|
||||
.to_lowercase()
|
||||
.cmp(&b.title.to_lowercase())
|
||||
.then_with(|| a.id.cmp(&b.id))
|
||||
});
|
||||
docs
|
||||
}
|
||||
|
||||
pub fn template_settings(&self) -> TemplateDocSettings {
|
||||
self.directory
|
||||
.db()
|
||||
.userdata_table(UserdataTableName::Settings)
|
||||
.and_then(|table| {
|
||||
table
|
||||
.get_row::<SettingsRow>(TEMPLATE_DOC_SETTING_KEY)
|
||||
.ok()
|
||||
.flatten()
|
||||
})
|
||||
.and_then(|row| serde_json::from_value::<TemplateDocSettings>(row.value).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn set_template_settings(&mut self, settings: TemplateDocSettings) -> bool {
|
||||
if self.is_readonly_sqlite() {
|
||||
return false;
|
||||
}
|
||||
if self.template_settings() == settings {
|
||||
return false;
|
||||
}
|
||||
let Ok(value) = serde_json::to_value(&settings) else {
|
||||
return false;
|
||||
};
|
||||
let row = SettingsRow {
|
||||
key: TEMPLATE_DOC_SETTING_KEY.to_owned(),
|
||||
value,
|
||||
};
|
||||
let now = self.writer_now();
|
||||
let session_sync = self.with_session(now, |session| {
|
||||
let (doc_id, diff, full) = {
|
||||
let mut dir = session.directory().lock_directory();
|
||||
let db = dir.db_mut();
|
||||
let doc_id = UserdataTableName::Settings.local_doc_id(db.user_id());
|
||||
let diff = db
|
||||
.upsert_userdata_row(UserdataTableName::Settings, &row)
|
||||
.map_err(|err| affine_client::ClientError::Store(err.to_string()))?;
|
||||
let _ = db.drain_pending_updates();
|
||||
let full = db
|
||||
.userdata_table(UserdataTableName::Settings)
|
||||
.and_then(|t| t.encode_update_v1().ok());
|
||||
(doc_id, diff, full)
|
||||
};
|
||||
if !diff.is_empty() && diff != [0, 0] {
|
||||
let _ = session.queue_doc_update(&doc_id, diff.clone(), now);
|
||||
session.enqueue_pending_persist_updates(vec![PendingDocUpdate {
|
||||
doc_id,
|
||||
update: diff,
|
||||
}]);
|
||||
}
|
||||
Ok(full)
|
||||
});
|
||||
match session_sync {
|
||||
Some(Ok(Some(bytes))) => {
|
||||
let _ = self
|
||||
.directory
|
||||
.db_mut()
|
||||
.load_userdata_table(UserdataTableName::Settings, &bytes);
|
||||
}
|
||||
Some(Ok(None)) => {}
|
||||
Some(Err(_)) => return false,
|
||||
None => {
|
||||
if self
|
||||
.directory
|
||||
.db_mut()
|
||||
.upsert_userdata_row(UserdataTableName::Settings, &row)
|
||||
.is_err()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.touch_meta();
|
||||
true
|
||||
}
|
||||
|
||||
pub fn set_custom_property_value(&mut self, doc_id: &str, id: &str, value: &str) -> bool {
|
||||
self.write_custom_property(
|
||||
doc_id,
|
||||
@@ -155,8 +479,14 @@ impl DesktopDocStore {
|
||||
if result.is_err() {
|
||||
return false;
|
||||
}
|
||||
} else if patch_local_property(self.directory.db_mut(), doc_id, field, value, default_mode)
|
||||
.is_err()
|
||||
} else if patch_local_property(
|
||||
self.directory.db_mut(),
|
||||
doc_id,
|
||||
field,
|
||||
json!(value),
|
||||
default_mode,
|
||||
)
|
||||
.is_err()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -173,19 +503,19 @@ fn patch_local_property(
|
||||
db: &mut WorkspaceDb,
|
||||
doc_id: &str,
|
||||
field: &str,
|
||||
value: &str,
|
||||
value: JsonValue,
|
||||
default_mode: DocMode,
|
||||
) -> ClientResult<()> {
|
||||
let fields = [(field, Some(json!(value)))];
|
||||
if db
|
||||
.patch_db_row_fields(DOC_PROPERTIES, doc_id, &fields)?
|
||||
.is_none()
|
||||
{
|
||||
let mut row = json!({"id": doc_id, "primaryMode": default_mode.as_str()});
|
||||
row[field] = json!(value);
|
||||
db.upsert_db_row(DOC_PROPERTIES, &row)?;
|
||||
) -> ClientResult<Option<Vec<u8>>> {
|
||||
let fields = [(field, Some(value.clone()))];
|
||||
if let Some(diff) = db.patch_db_row_fields(DOC_PROPERTIES, doc_id, &fields)? {
|
||||
return Ok(Some(diff));
|
||||
}
|
||||
Ok(())
|
||||
if db.has_db_row_entry(DOC_PROPERTIES, doc_id)? {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut row = json!({"id": doc_id, "primaryMode": default_mode.as_str()});
|
||||
row[field] = value;
|
||||
Ok(Some(db.upsert_db_row(DOC_PROPERTIES, &row)?))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -338,4 +668,427 @@ mod tests {
|
||||
let (mut reopened, _) = open();
|
||||
verify(&mut reopened.store, &ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn template_flags_workspace_property_management_and_backup_export_work_end_to_end() {
|
||||
let mut store = DesktopDocStore::seed_showcase("2026-12-02");
|
||||
assert!(!store.doc_is_template("doc-arch"));
|
||||
assert!(store.set_doc_is_template("doc-arch", true));
|
||||
assert!(store.doc_is_template("doc-arch"));
|
||||
let templates = store.template_docs();
|
||||
assert!(templates.iter().any(|doc| doc.id == "doc-arch"));
|
||||
|
||||
let next_settings = TemplateDocSettings {
|
||||
enable_page_template: true,
|
||||
page_template_id: Some("doc-arch".into()),
|
||||
journal_template_id: Some("doc-arch".into()),
|
||||
};
|
||||
assert!(store.set_template_settings(next_settings.clone()));
|
||||
assert_eq!(store.template_settings(), next_settings);
|
||||
|
||||
let prop_id = store
|
||||
.create_workspace_custom_property("Review Status", "text")
|
||||
.expect("create custom property");
|
||||
assert!(store.set_custom_property_value("doc-sync", &prop_id, "Approved"));
|
||||
assert_eq!(store.workspace_property_doc_count(&prop_id), 1);
|
||||
assert!(store.edit_workspace_custom_property(
|
||||
&prop_id,
|
||||
Some("Audit State"),
|
||||
Some("hide-when-empty"),
|
||||
false,
|
||||
));
|
||||
let listed = store.workspace_custom_properties();
|
||||
let entry = listed.iter().find(|row| row.id == prop_id).expect("listed");
|
||||
assert_eq!(entry.name.as_deref(), Some("Audit State"));
|
||||
assert_eq!(entry.show.as_deref(), Some("hide-when-empty"));
|
||||
assert!(store.edit_workspace_custom_property(&prop_id, None, None, true));
|
||||
assert!(
|
||||
store
|
||||
.workspace_custom_properties()
|
||||
.iter()
|
||||
.all(|row| row.id != prop_id)
|
||||
);
|
||||
|
||||
let (space_id, _ws_name, updates) = store.export_workspace_updates().expect("updates");
|
||||
let update_ids: std::collections::BTreeSet<String> =
|
||||
updates.iter().map(|(id, _)| id.clone()).collect();
|
||||
assert!(update_ids.contains(&space_id));
|
||||
assert!(update_ids.contains("db$docCustomPropertyInfo"));
|
||||
assert!(update_ids.contains("db$docProperties"));
|
||||
for doc_id in store.docs.keys() {
|
||||
assert!(update_ids.contains(doc_id), "missing doc {doc_id}");
|
||||
}
|
||||
|
||||
let backup = store
|
||||
.export_workspace_backup(10_000)
|
||||
.expect("sqlite backup");
|
||||
assert!(backup.filename.ends_with(".affine"));
|
||||
assert!(!backup.bytes.is_empty());
|
||||
let nonce = blocksuite_playground_doc::try_random_client_id().expect("nonce");
|
||||
let path = std::env::temp_dir().join(format!("affine-verify-{nonce:x}.affine"));
|
||||
std::fs::write(&path, &backup.bytes).expect("write sqlite backup");
|
||||
let (reopened, _) =
|
||||
crate::sqlite_loader::open_sqlite_workspace(path.clone()).expect("open sqlite backup");
|
||||
assert_eq!(reopened.active_workspace().id, space_id);
|
||||
assert!(reopened.doc_is_template("doc-arch"));
|
||||
let settings_doc_id =
|
||||
UserdataTableName::Settings.local_doc_id(store.directory.db().user_id());
|
||||
assert!(update_ids.contains(&settings_doc_id));
|
||||
let settings_bytes = reopened
|
||||
.sqlite_backing
|
||||
.as_ref()
|
||||
.expect("sqlite backing")
|
||||
.load_doc_update(&settings_doc_id)
|
||||
.expect("load settings doc")
|
||||
.expect("settings snapshot bytes");
|
||||
let mut check_db = WorkspaceDb::new(space_id, store.directory.db().user_id(), 99);
|
||||
check_db
|
||||
.load_userdata_table(UserdataTableName::Settings, &settings_bytes)
|
||||
.expect("decode userdata settings table");
|
||||
let saved_row = check_db
|
||||
.userdata_table(UserdataTableName::Settings)
|
||||
.expect("settings table")
|
||||
.get_row::<SettingsRow>(TEMPLATE_DOC_SETTING_KEY)
|
||||
.expect("read settings row")
|
||||
.expect("template settings row");
|
||||
let saved_settings: TemplateDocSettings =
|
||||
serde_json::from_value(saved_row.value).expect("decode template settings");
|
||||
assert_eq!(saved_settings, next_settings);
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlite_backup_preserves_blobs_settings_and_queues_crdt_sync() {
|
||||
const NOW: i64 = 1_764_350_000;
|
||||
let mut store = DesktopDocStore::seed_showcase("2026-12-02");
|
||||
let space_id = store.active_workspace().id.clone();
|
||||
let user_id = store.directory.db().user_id().to_owned();
|
||||
let root_bytes = store
|
||||
.directory
|
||||
.db()
|
||||
.root()
|
||||
.encode_update_v1()
|
||||
.expect("encode root");
|
||||
let cid = blocksuite_playground_doc::try_random_client_id().expect("client id");
|
||||
let db = WorkspaceDb::from_root_update_v1(&space_id, &user_id, cid, &root_bytes, &[])
|
||||
.expect("workspace db");
|
||||
let session = affine_client::WorkspaceSession::from_workspace_db(
|
||||
db,
|
||||
cid,
|
||||
affine_client::HostKind::Native,
|
||||
"https://app.affine.pro",
|
||||
"https://app.affine.pro",
|
||||
NOW,
|
||||
)
|
||||
.expect("connected sync session");
|
||||
store.bind_writer(crate::doc_store::SessionWriter::new(
|
||||
space_id,
|
||||
std::sync::Arc::new(std::sync::Mutex::new(session)),
|
||||
Default::default(),
|
||||
NOW,
|
||||
));
|
||||
|
||||
assert!(store.set_doc_is_template("doc-arch", true));
|
||||
let next_settings = TemplateDocSettings {
|
||||
enable_page_template: true,
|
||||
page_template_id: Some("doc-arch".into()),
|
||||
journal_template_id: Some("doc-arch".into()),
|
||||
};
|
||||
assert!(store.set_template_settings(next_settings.clone()));
|
||||
store
|
||||
.with_session(NOW, |session| {
|
||||
let props_doc = DOC_PROPERTIES.local_doc_id();
|
||||
let settings_doc = UserdataTableName::Settings.local_doc_id(&user_id);
|
||||
assert!(
|
||||
session.doc_sync().has_pending_push(&props_doc),
|
||||
"set_doc_is_template must enqueue CRDT sync update"
|
||||
);
|
||||
assert!(
|
||||
session.doc_sync().has_pending_push(&settings_doc),
|
||||
"set_template_settings must enqueue CRDT sync update"
|
||||
);
|
||||
Ok(())
|
||||
})
|
||||
.expect("with_session")
|
||||
.expect("sync assertions");
|
||||
|
||||
let mut store = DesktopDocStore::seed_showcase("2026-12-02");
|
||||
let next_settings = TemplateDocSettings {
|
||||
enable_page_template: true,
|
||||
page_template_id: Some("doc-arch".into()),
|
||||
journal_template_id: Some("doc-arch".into()),
|
||||
};
|
||||
assert!(store.set_doc_is_template("doc-arch", true));
|
||||
assert!(store.set_template_settings(next_settings.clone()));
|
||||
|
||||
let image_bytes = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 1, 2, 3, 4];
|
||||
let attach_bytes = b"attachment-payload-v1".to_vec();
|
||||
let blobs = std::collections::BTreeMap::from([
|
||||
("blob-image-1".to_owned(), image_bytes.clone()),
|
||||
("blob-file-2".to_owned(), attach_bytes.clone()),
|
||||
]);
|
||||
let backup1 = store
|
||||
.export_workspace_backup_with_blobs(&blobs, 10_000)
|
||||
.expect("first export with blobs");
|
||||
|
||||
let nonce = blocksuite_playground_doc::try_random_client_id().expect("nonce");
|
||||
let path1 = std::env::temp_dir().join(format!("affine-rt1-{nonce:x}.affine"));
|
||||
let path2 = std::env::temp_dir().join(format!("affine-rt2-{nonce:x}.affine"));
|
||||
std::fs::write(&path1, &backup1.bytes).expect("write backup 1");
|
||||
|
||||
let (mut reopened1, _) =
|
||||
crate::sqlite_loader::open_sqlite_workspace(path1.clone()).expect("open 1");
|
||||
assert_eq!(reopened1.template_settings(), next_settings);
|
||||
let loaded_blobs1: std::collections::BTreeMap<String, Vec<u8>> = reopened1
|
||||
.sqlite_backing
|
||||
.as_ref()
|
||||
.expect("backing 1")
|
||||
.load_all_blobs()
|
||||
.expect("load blobs 1")
|
||||
.into_iter()
|
||||
.map(|(k, _, data)| (k, data))
|
||||
.collect();
|
||||
assert_eq!(loaded_blobs1.get("blob-image-1"), Some(&image_bytes));
|
||||
assert_eq!(loaded_blobs1.get("blob-file-2"), Some(&attach_bytes));
|
||||
|
||||
let backup2 = reopened1
|
||||
.export_workspace_backup(20_000)
|
||||
.expect("second export from sqlite");
|
||||
std::fs::write(&path2, &backup2.bytes).expect("write backup 2");
|
||||
let (reopened2, _) =
|
||||
crate::sqlite_loader::open_sqlite_workspace(path2.clone()).expect("open 2");
|
||||
assert_eq!(reopened2.template_settings(), next_settings);
|
||||
let loaded_blobs2: std::collections::BTreeMap<String, Vec<u8>> = reopened2
|
||||
.sqlite_backing
|
||||
.as_ref()
|
||||
.expect("backing 2")
|
||||
.load_all_blobs()
|
||||
.expect("load blobs 2")
|
||||
.into_iter()
|
||||
.map(|(k, _, data)| (k, data))
|
||||
.collect();
|
||||
assert_eq!(loaded_blobs2.get("blob-image-1"), Some(&image_bytes));
|
||||
assert_eq!(loaded_blobs2.get("blob-file-2"), Some(&attach_bytes));
|
||||
|
||||
let _ = std::fs::remove_file(path1);
|
||||
let _ = std::fs::remove_file(path2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backup_exports_unhydrated_session_subdoc_with_original_id_and_body() {
|
||||
use affine_store::sqlite::SqliteDocStorage;
|
||||
use blocksuite_playground_doc::{
|
||||
read::BlockContent,
|
||||
schema::{BlockSpec, ParagraphType},
|
||||
session::PageDocSession,
|
||||
};
|
||||
|
||||
const NOW: i64 = 1_764_360_000;
|
||||
let mut store = DesktopDocStore::seed_showcase("2026-12-02");
|
||||
let space_id = store.active_workspace().id.clone();
|
||||
let user_id = store.directory.db().user_id().to_owned();
|
||||
let root_bytes = store
|
||||
.directory
|
||||
.db()
|
||||
.root()
|
||||
.encode_update_v1()
|
||||
.expect("encode root");
|
||||
let cid = blocksuite_playground_doc::try_random_client_id().expect("client id");
|
||||
let db = WorkspaceDb::from_root_update_v1(&space_id, &user_id, cid, &root_bytes, &[])
|
||||
.expect("workspace db");
|
||||
let mut session = affine_client::WorkspaceSession::from_local_workspace_db(
|
||||
db,
|
||||
cid,
|
||||
affine_client::HostKind::Web,
|
||||
NOW,
|
||||
)
|
||||
.expect("local session");
|
||||
|
||||
let subdoc_id = "subdoc-unhydrated-42";
|
||||
let mut subdoc = PageDocSession::new(subdoc_id, cid).expect("subdoc");
|
||||
subdoc
|
||||
.add_block(
|
||||
"sub-root",
|
||||
BlockSpec::Page {
|
||||
title: "Hidden Subdoc".into(),
|
||||
},
|
||||
None,
|
||||
None,
|
||||
10,
|
||||
)
|
||||
.expect("root");
|
||||
subdoc
|
||||
.add_block(
|
||||
"sub-note",
|
||||
BlockSpec::Note { xywh: None },
|
||||
Some("sub-root"),
|
||||
None,
|
||||
11,
|
||||
)
|
||||
.expect("note");
|
||||
subdoc
|
||||
.add_block(
|
||||
"sub-para",
|
||||
BlockSpec::Paragraph {
|
||||
paragraph_type: ParagraphType::Text,
|
||||
text: "Hidden subdoc body".into(),
|
||||
},
|
||||
Some("sub-note"),
|
||||
None,
|
||||
12,
|
||||
)
|
||||
.expect("para");
|
||||
session.register_loaded_doc(subdoc_id, subdoc);
|
||||
assert!(store.get_doc(subdoc_id).is_none());
|
||||
|
||||
store.bind_writer(crate::doc_store::SessionWriter::new(
|
||||
space_id,
|
||||
std::sync::Arc::new(std::sync::Mutex::new(session)),
|
||||
Default::default(),
|
||||
NOW,
|
||||
));
|
||||
assert!(store.sqlite_backing.is_none());
|
||||
|
||||
let backup = store
|
||||
.export_workspace_backup(NOW + 1_000)
|
||||
.expect("backup export");
|
||||
let nonce = blocksuite_playground_doc::try_random_client_id().expect("nonce");
|
||||
let path = std::env::temp_dir().join(format!("affine-subdoc-rt-{nonce:x}.affine"));
|
||||
std::fs::write(&path, &backup.bytes).expect("write backup");
|
||||
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("tokio");
|
||||
let raw_bin = rt
|
||||
.block_on(async {
|
||||
let storage = SqliteDocStorage::new(path.to_string_lossy().into_owned());
|
||||
storage.connect().await?;
|
||||
let rec = storage.get_doc_snapshot(subdoc_id).await?;
|
||||
storage.close().await;
|
||||
Ok::<_, anyhow::Error>(rec.map(|r| r.bin))
|
||||
})
|
||||
.expect("read sqlite")
|
||||
.expect("unhydrated subdoc snapshot missing in backup");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
|
||||
let mut restored = PageDocSession::new(subdoc_id, cid + 1).expect("restore");
|
||||
restored.apply_remote_update_v1(&raw_bin).expect("apply v1");
|
||||
let snap = restored.read_page_snapshot().expect("snapshot");
|
||||
let root = snap.root.as_ref().expect("root");
|
||||
assert!(
|
||||
root.children
|
||||
.iter()
|
||||
.flat_map(|c| c.walk())
|
||||
.any(|node| matches!(&node.content, BlockContent::Paragraph { text, .. } if text.plain == "Hidden subdoc body")),
|
||||
"restored subdoc must keep full body"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlite_reexport_preserves_snapshot_only_multiuser_userdata_settings_records() {
|
||||
use affine_store::sqlite::{DocRecord, SqliteDocStorage, millis_to_naive_utc};
|
||||
|
||||
let store = DesktopDocStore::seed_showcase("2026-12-02");
|
||||
let space_id = store.active_workspace().id.clone();
|
||||
let root_bin = store
|
||||
.directory
|
||||
.db()
|
||||
.root()
|
||||
.encode_update_v1()
|
||||
.expect("encode root");
|
||||
|
||||
let cid = blocksuite_playground_doc::try_random_client_id().expect("cid");
|
||||
let nonce = blocksuite_playground_doc::try_random_client_id().expect("nonce");
|
||||
let path1 = std::env::temp_dir().join(format!("affine-snap-src-{nonce:x}.affine"));
|
||||
let path2 = std::env::temp_dir().join(format!("affine-snap-re-{nonce:x}.affine"));
|
||||
let alice_doc_id = "userdata$u-alice$settings";
|
||||
let bob_doc_id = "userdata$u-bob$settings";
|
||||
let alice_bin = {
|
||||
let mut db =
|
||||
WorkspaceDb::from_root_update_v1(&space_id, "u-alice", cid, &root_bin, &[])
|
||||
.expect("db");
|
||||
db.upsert_userdata_row(
|
||||
UserdataTableName::Settings,
|
||||
&SettingsRow {
|
||||
key: TEMPLATE_DOC_SETTING_KEY.to_owned(),
|
||||
value: serde_json::json!({ "enablePageTemplate": true }),
|
||||
},
|
||||
)
|
||||
.expect("upsert alice settings");
|
||||
let doc = db
|
||||
.userdata_table(UserdataTableName::Settings)
|
||||
.expect("alice settings");
|
||||
doc.encode_update_v1().expect("encode alice settings")
|
||||
};
|
||||
let bob_bin = {
|
||||
let mut db =
|
||||
WorkspaceDb::from_root_update_v1(&space_id, "u-bob", cid + 1, &root_bin, &[])
|
||||
.expect("db");
|
||||
db.upsert_userdata_row(
|
||||
UserdataTableName::Settings,
|
||||
&SettingsRow {
|
||||
key: TEMPLATE_DOC_SETTING_KEY.to_owned(),
|
||||
value: serde_json::json!({ "enablePageTemplate": false }),
|
||||
},
|
||||
)
|
||||
.expect("upsert bob settings");
|
||||
let doc = db
|
||||
.userdata_table(UserdataTableName::Settings)
|
||||
.expect("bob settings");
|
||||
doc.encode_update_v1().expect("encode bob settings")
|
||||
};
|
||||
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("tokio");
|
||||
let timestamp = millis_to_naive_utc(1_764_360_000);
|
||||
rt.block_on(async {
|
||||
let storage = SqliteDocStorage::new(path1.to_string_lossy().into_owned());
|
||||
storage.connect().await?;
|
||||
storage.set_space_id(&space_id).await?;
|
||||
for (doc_id, bin) in [
|
||||
(space_id.as_str(), root_bin.as_slice()),
|
||||
(alice_doc_id, alice_bin.as_slice()),
|
||||
(bob_doc_id, bob_bin.as_slice()),
|
||||
] {
|
||||
storage
|
||||
.set_doc_snapshot(&DocRecord {
|
||||
doc_id: doc_id.to_owned(),
|
||||
bin: bin.to_vec(),
|
||||
timestamp,
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
assert!(storage.get_doc_clocks(None).await?.is_empty());
|
||||
storage.close().await;
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})
|
||||
.expect("seed snapshot-only sqlite");
|
||||
|
||||
let (mut reopened, _) =
|
||||
crate::sqlite_loader::open_sqlite_workspace(path1.clone()).expect("open snapshot db");
|
||||
let reexport = reopened
|
||||
.export_workspace_backup(1_764_360_500)
|
||||
.expect("reexport backup");
|
||||
std::fs::write(&path2, &reexport.bytes).expect("write reexport");
|
||||
|
||||
let (re_ids, has_alice, has_bob) = rt
|
||||
.block_on(async {
|
||||
let storage = SqliteDocStorage::new(path2.to_string_lossy().into_owned());
|
||||
storage.connect().await?;
|
||||
let ids = storage.list_doc_ids().await?;
|
||||
let a = storage.get_doc_snapshot(alice_doc_id).await?.is_some();
|
||||
let b = storage.get_doc_snapshot(bob_doc_id).await?.is_some();
|
||||
storage.close().await;
|
||||
Ok::<_, anyhow::Error>((ids, a, b))
|
||||
})
|
||||
.expect("read reexport");
|
||||
assert!(has_alice, "missing {alice_doc_id} in {re_ids:?}");
|
||||
assert!(has_bob, "missing {bob_doc_id} in {re_ids:?}");
|
||||
|
||||
let _ = std::fs::remove_file(&path1);
|
||||
let _ = std::fs::remove_file(&path2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
//! Document template body cloning and workspace root name helpers for [`DesktopDocStore`].
|
||||
|
||||
use affine_store::workspace_db::WorkspaceRootDoc;
|
||||
use blocksuite_playground_doc::{
|
||||
read::{BlockContent, PageSnapshot},
|
||||
session::PageDocSession,
|
||||
try_random_client_id,
|
||||
};
|
||||
use y_octo::{
|
||||
Any, DocOptions, DocSession, SessionConfig, SessionReadValue, SessionTxOrigin,
|
||||
SessionUndoConfig, SessionValue, TypePath, TypeTarget, YTypeKind,
|
||||
};
|
||||
|
||||
use super::LiveDocEntry;
|
||||
|
||||
/// Clone visible body blocks from `tpl_doc` into `session`, advancing `next_seq` for fresh block IDs.
|
||||
pub(super) fn clone_template_body(
|
||||
tpl_doc: &LiveDocEntry,
|
||||
session: &mut PageDocSession,
|
||||
next_seq: &mut u64,
|
||||
now_ms: u64,
|
||||
) -> Option<(Vec<u8>, Option<String>)> {
|
||||
let before = session.encode_state_vector_v1().ok()?;
|
||||
let mut seq = *next_seq;
|
||||
let mut fresh_id = || {
|
||||
seq += 1;
|
||||
format!("b-{seq}")
|
||||
};
|
||||
let cloned = session
|
||||
.clone_body_blocks_from(&tpl_doc.session, &mut fresh_id, now_ms)
|
||||
.ok()
|
||||
.flatten();
|
||||
*next_seq = seq;
|
||||
cloned?;
|
||||
let diff = session.encode_diff_v1(&before).ok()?;
|
||||
let summary = first_nonempty_block_text(&tpl_doc.snapshot);
|
||||
Some((diff, summary))
|
||||
}
|
||||
|
||||
fn first_nonempty_block_text(snapshot: &PageSnapshot) -> Option<String> {
|
||||
let root = snapshot.root.as_ref()?;
|
||||
for child in &root.children {
|
||||
if !child.is_page_visible_note() {
|
||||
continue;
|
||||
}
|
||||
for node in child.walk() {
|
||||
let text = match &node.content {
|
||||
BlockContent::Paragraph { text, .. } | BlockContent::List { text, .. } => {
|
||||
text.plain.trim()
|
||||
}
|
||||
BlockContent::Callout { text, .. } => text.plain.trim(),
|
||||
BlockContent::Code { text, .. } => text.trim(),
|
||||
_ => "",
|
||||
};
|
||||
if !text.is_empty() {
|
||||
return Some(text.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn open_root_y_doc(root: &WorkspaceRootDoc, client_id: u64) -> Option<DocSession<()>> {
|
||||
let bytes = root.encode_update_v1().ok()?;
|
||||
let mut doc = DocSession::with_config(
|
||||
DocOptions::from_identity(client_id, root.space_id().to_owned()),
|
||||
SessionConfig {
|
||||
undo: SessionUndoConfig::Disabled,
|
||||
},
|
||||
);
|
||||
if !bytes.is_empty() && bytes != [0, 0] {
|
||||
doc.apply_update_v1(&bytes).ok()?;
|
||||
}
|
||||
Some(doc)
|
||||
}
|
||||
|
||||
pub(super) fn read_root_workspace_name(root: &WorkspaceRootDoc) -> Option<String> {
|
||||
let doc = open_root_y_doc(root, 1)?;
|
||||
let meta = TypeTarget::Path(TypePath::root("meta"));
|
||||
match doc.get_map_value(&meta, "name").ok().flatten() {
|
||||
Some(SessionReadValue::Any(Any::String(name))) => Some(name),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn write_root_workspace_name(root: &WorkspaceRootDoc, name: &str) -> Option<Vec<u8>> {
|
||||
let client_id = try_random_client_id().ok()?;
|
||||
let mut doc = open_root_y_doc(root, client_id)?;
|
||||
let before_sv = doc.encode_state_vector_v1().ok()?;
|
||||
let meta_id = doc.ensure_root("meta", YTypeKind::Map).ok()?;
|
||||
let meta_target = TypeTarget::from(meta_id);
|
||||
if matches!(
|
||||
doc.get_map_value(&meta_target, "name").ok().flatten(),
|
||||
Some(SessionReadValue::Any(Any::String(ref current))) if current == name
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
doc.begin_tx(SessionTxOrigin::Untracked).ok()?;
|
||||
let set_res = doc.map_set(
|
||||
&meta_target,
|
||||
"name".to_owned(),
|
||||
SessionValue::Any(Any::String(name.to_owned())),
|
||||
);
|
||||
let commit_res = doc.commit_tx();
|
||||
set_res.ok()?;
|
||||
commit_res.ok()?;
|
||||
let diff = doc.encode_diff_v1(&before_sv).ok()?;
|
||||
(!diff.is_empty() && diff != [0, 0]).then_some(diff)
|
||||
}
|
||||
@@ -39,6 +39,24 @@ impl WorkspaceBlobs {
|
||||
}
|
||||
|
||||
impl DesktopEditorHost {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn workspace_blobs_snapshot(&self, workspace_id: &str) -> BTreeMap<String, Vec<u8>> {
|
||||
self.workspace_blobs
|
||||
.get(workspace_id)
|
||||
.map(|blobs| {
|
||||
blobs
|
||||
.entries
|
||||
.values()
|
||||
.map(|(source, bytes)| (source.clone(), bytes.as_ref().clone()))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn clear_workspace_blobs(&mut self, workspace_id: &str) {
|
||||
self.workspace_blobs.remove(workspace_id);
|
||||
}
|
||||
|
||||
pub(crate) fn seed_workspace_blobs(&mut self, workspace_id: &str, blobs: &StoredBlobs) {
|
||||
if blobs.is_empty() {
|
||||
return;
|
||||
|
||||
@@ -286,8 +286,8 @@ fn settings_modal_keyboard_navigation_shows_focus_rings_and_configures_editor_fo
|
||||
desktop.evidence("after-settings-focus-editor-light.png");
|
||||
desktop.key("enter");
|
||||
|
||||
// Tab across Shortcuts, Preference, Storage, About, Page, Edgeless, Sans -> Serif.
|
||||
for _ in 0..8 {
|
||||
// Tab across Shortcuts, Preference, Properties, Storage, About, Page, Edgeless, Sans -> Serif.
|
||||
for _ in 0..9 {
|
||||
desktop.key("tab");
|
||||
}
|
||||
desktop.inspect(|_, window, _| {
|
||||
@@ -429,7 +429,7 @@ fn settings_modal_keyboard_navigation_shows_focus_rings_and_configures_editor_fo
|
||||
0
|
||||
);
|
||||
});
|
||||
for _ in 0..7 {
|
||||
for _ in 0..8 {
|
||||
desktop.key("tab");
|
||||
}
|
||||
desktop.inspect(|_, window, _| {
|
||||
@@ -465,11 +465,11 @@ fn settings_modal_keyboard_tab_scrolls_offscreen_controls_into_view_on_short_win
|
||||
state.open_settings();
|
||||
let desktop = Desktop::new_sized(state, w, h);
|
||||
|
||||
// Select Editor tab in compact header (Appearance -> Editor -> Enter), then step past 4 remaining nav tabs.
|
||||
// Select Editor tab in compact header (Appearance -> Editor -> Enter), then step past 5 remaining nav tabs.
|
||||
desktop.key("tab");
|
||||
desktop.key("tab");
|
||||
desktop.key("enter");
|
||||
for _ in 0..4 {
|
||||
for _ in 0..5 {
|
||||
desktop.key("tab");
|
||||
}
|
||||
for (id, top_strip) in editor_stops {
|
||||
@@ -556,7 +556,7 @@ fn settings_modal_keyboard_tab_scrolls_offscreen_controls_into_view_on_short_win
|
||||
let mut wide_short = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-03");
|
||||
wide_short.open_settings();
|
||||
let short_nav = Desktop::new_sized(wide_short, 800, 260);
|
||||
for _ in 0..6 {
|
||||
for _ in 0..7 {
|
||||
short_nav.key("tab");
|
||||
}
|
||||
short_nav.inspect(|_, window, _| {
|
||||
|
||||
@@ -31,6 +31,10 @@ impl ScrollRegion {
|
||||
.read(app)
|
||||
.clone()
|
||||
}
|
||||
|
||||
pub(super) fn reset(&self) {
|
||||
self.axis.set(ScrollAxis::default());
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn scroll_area(id: &'static str, region: &ScrollRegion, body: Div) -> Stateful<Div> {
|
||||
@@ -199,8 +203,8 @@ impl FocusStops {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn focus_stop(
|
||||
id: &'static str,
|
||||
pub(super) fn focus_stop_named(
|
||||
id: ElementId,
|
||||
stops: &mut FocusStops,
|
||||
window: &mut Window,
|
||||
app: &mut App,
|
||||
@@ -224,10 +228,39 @@ pub(super) fn focus_stop(
|
||||
stop
|
||||
}
|
||||
|
||||
pub(super) fn focus_stop(
|
||||
id: &'static str,
|
||||
stops: &mut FocusStops,
|
||||
window: &mut Window,
|
||||
app: &mut App,
|
||||
) -> FocusStop {
|
||||
focus_stop_named(
|
||||
ElementId::Name(SharedString::new_static(id)),
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn push_focus_stop(
|
||||
handle: FocusHandle,
|
||||
bounds: Rc<Cell<ui::Bounds<ui::Pixels>>>,
|
||||
stops: &mut FocusStops,
|
||||
) -> FocusStop {
|
||||
let stop = FocusStop {
|
||||
handle,
|
||||
bounds,
|
||||
scroll: stops.scroll.clone(),
|
||||
};
|
||||
stops.stops.push(stop.clone());
|
||||
stop
|
||||
}
|
||||
|
||||
pub(super) fn navigation(
|
||||
page: Page,
|
||||
selection: &Entity<Page>,
|
||||
(palette, mode): (DesktopPalette, ui_tokens::ThemeMode),
|
||||
t: &super::i18n::SettingsStrings,
|
||||
nav_scroll: Option<&ScrollRegion>,
|
||||
stops: &mut FocusStops,
|
||||
window: &mut Window,
|
||||
@@ -244,6 +277,7 @@ pub(super) fn navigation(
|
||||
let selection_key = selection.clone();
|
||||
let accent = palette.accent;
|
||||
let button = button(tab.id())
|
||||
.snapshot_text(tab.nav_label(t))
|
||||
.relative()
|
||||
.track_focus(&stop.handle)
|
||||
.snapshot_focused(stop.handle.is_focused(window))
|
||||
@@ -299,14 +333,14 @@ pub(super) fn navigation(
|
||||
.text_color(icon_color),
|
||||
)
|
||||
})
|
||||
.child(tab.labels().0)
|
||||
.child(tab.nav_label(t))
|
||||
};
|
||||
let title = div()
|
||||
.px(px(8.0))
|
||||
.text_size(px(18.0))
|
||||
.line_height(px(26.0))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.child("Settings");
|
||||
.child(t.settings);
|
||||
let nav = div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
@@ -330,8 +364,8 @@ pub(super) fn navigation(
|
||||
)
|
||||
.children(tabs.iter().copied().map(&mut item))
|
||||
};
|
||||
let general = group("General", &Page::GENERAL);
|
||||
let workspace = group("Workspace", &Page::WORKSPACE);
|
||||
let general = group(t.general_group, &Page::GENERAL);
|
||||
let workspace = group(t.workspace_group, &Page::WORKSPACE);
|
||||
let about = item(Page::About);
|
||||
let body = nav
|
||||
.min_h(ui::relative(1.0))
|
||||
@@ -556,39 +590,6 @@ pub(super) fn control_section(
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn readonly_select(
|
||||
id: &'static str,
|
||||
value: &'static str,
|
||||
palette: DesktopPalette,
|
||||
) -> Div {
|
||||
let mut capsule = div().w(px(250.0));
|
||||
capsule.style().max_size.width = Some(ui::relative(1.0).into());
|
||||
capsule
|
||||
.snapshot(id, Some(MODAL_ID))
|
||||
.flex()
|
||||
.flex_shrink(0.0)
|
||||
.items_center()
|
||||
.justify_between()
|
||||
.gap(px(8.0))
|
||||
.h(px(32.0))
|
||||
.px(px(12.0))
|
||||
.rounded(px(8.0))
|
||||
.bg(palette.bg_elevated)
|
||||
.border_1()
|
||||
.border_color(palette.border)
|
||||
.text_size(px(12.0))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(palette.text_primary)
|
||||
.child(div().min_w_0().child(value))
|
||||
.child(
|
||||
svg()
|
||||
.data(ui_tokens::icons::ARROW_DOWN_SMALL.svg.as_bytes())
|
||||
.size(px(16.0))
|
||||
.flex_shrink(0.0)
|
||||
.text_color(palette.text_secondary),
|
||||
)
|
||||
}
|
||||
|
||||
type ActivateHandler = Rc<dyn Fn(&mut App)>;
|
||||
|
||||
/// Track inset around the options of a Web `RadioGroup`.
|
||||
|
||||
@@ -47,7 +47,10 @@ pub(super) fn slider(
|
||||
let drag_shell = shell.downgrade();
|
||||
let keyboard_shell = shell.downgrade();
|
||||
let mut thumb = div()
|
||||
.snapshot("desktop.settings.font.size.thumb", Some(SLIDER_ID))
|
||||
.snapshot(
|
||||
ui::snap_id!("desktop.settings.font.size.thumb"),
|
||||
Some(SLIDER_ID),
|
||||
)
|
||||
.absolute()
|
||||
.left(ui::relative(fraction))
|
||||
.top(px((HIT_HEIGHT - THUMB) / 2.0))
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
use super::SettingsStrings;
|
||||
|
||||
pub(super) const ZH_HANS: SettingsStrings = SettingsStrings {
|
||||
settings: "设置",
|
||||
general_group: "通用",
|
||||
workspace_group: "工作区",
|
||||
nav_appearance: "外观",
|
||||
nav_editor: "编辑器",
|
||||
nav_shortcuts: "快捷键",
|
||||
nav_preference: "偏好设置",
|
||||
nav_properties: "属性",
|
||||
nav_storage: "存储",
|
||||
nav_about: "关于",
|
||||
|
||||
appearance_title: "外观设置",
|
||||
appearance_desc: "自定义 AFFiNE 的界面外观",
|
||||
theme_section: "主题",
|
||||
color_scheme: "配色方案",
|
||||
color_scheme_desc: "选择 AFFiNE 使用的颜色模式。",
|
||||
theme_light: "浅色",
|
||||
theme_dark: "深色",
|
||||
theme_system: "跟随系统",
|
||||
display_language: "显示语言",
|
||||
display_language_desc: "选择界面使用的显示语言。",
|
||||
|
||||
editor_title: "编辑器设置",
|
||||
editor_desc: "新建与编辑文档的默认偏好",
|
||||
editor_general_section: "通用",
|
||||
new_doc_default_mode: "新建文档默认模式",
|
||||
new_doc_default_mode_desc: "选择新建文档打开时的默认视图模式。",
|
||||
mode_page: "页面",
|
||||
mode_edgeless: "无界画布",
|
||||
font_style: "字体风格",
|
||||
font_style_desc: "选择文档正文的字体风格。",
|
||||
font_size: "字号",
|
||||
font_size_desc: "选择文档正文的基础字号。",
|
||||
page_section: "页面",
|
||||
default_page_width: "默认页面宽度",
|
||||
default_page_width_desc: "选择页面的默认排版宽度。",
|
||||
page_width_standard: "标准宽度",
|
||||
page_width_full: "全宽",
|
||||
|
||||
shortcuts_title: "键盘快捷键",
|
||||
shortcuts_desc: "工作台与编辑器常用快捷键",
|
||||
shortcuts_editor_section: "编辑器",
|
||||
shortcut_quick_search: "快速搜索",
|
||||
|
||||
preference_title: "工作区偏好设置",
|
||||
preference_desc: "自定义工作区名称、文档模板与生命周期",
|
||||
info_section: "信息",
|
||||
workspace_name: "工作区名称",
|
||||
workspace_name_placeholder: "工作区名称",
|
||||
save: "保存",
|
||||
cancel: "取消",
|
||||
create: "创建",
|
||||
delete: "删除",
|
||||
sync_status: "同步状态",
|
||||
sync_readonly: "只读",
|
||||
sync_server: "已配置服务器同步",
|
||||
sync_local: "仅本地",
|
||||
sync_memory: "仅内存",
|
||||
template_section: "模板",
|
||||
journal_template: "日记模板",
|
||||
journal_template_desc: "创建新日记条目时套用的模板。",
|
||||
page_template: "页面模板",
|
||||
page_template_desc: "为新建页面自动应用默认模板。",
|
||||
select_page_template: "选择页面模板",
|
||||
select_page_template_desc: "选择新建页面要复制的模板文档。",
|
||||
current_doc_as_template: "将当前文档设为模板",
|
||||
current_doc_as_template_desc: "将当前打开的文档标记为可复用工作区模板。",
|
||||
none_option: "无",
|
||||
untitled: "无标题",
|
||||
no_templates_yet: "暂未标记模板文档。",
|
||||
delete_workspace: "删除工作区",
|
||||
delete_workspace_desc: "删除此工作区将清除其本地数据,此操作不可撤销。",
|
||||
delete_workspace_title: "确定删除工作区?",
|
||||
delete_workspace_confirm_prefix: "删除 ",
|
||||
delete_workspace_confirm_suffix: " 后将无法撤销,该工作区中的所有内容都将丢失。",
|
||||
|
||||
properties_title: "工作区属性",
|
||||
properties_desc: "管理此工作区文档中显示的通用属性",
|
||||
system_properties_section: "系统属性",
|
||||
custom_properties_section: "自定义属性",
|
||||
system_badge: "系统",
|
||||
add_property: "添加属性",
|
||||
property_name_placeholder: "属性名称",
|
||||
no_custom_properties: "暂无自定义属性,点击「添加属性」创建。",
|
||||
|
||||
storage_title: "存储",
|
||||
storage_desc: "查看当前工作区存储并导出本地备份",
|
||||
backup_section: "备份",
|
||||
full_backup: "完整备份",
|
||||
full_backup_desc: "将工作区全部文档与本地资源导出为 .affine 备份文件。",
|
||||
export_workspace: "导出工作区",
|
||||
|
||||
about_title: "关于 AFFiNE",
|
||||
about_desc: "AFFiNE 应用版本与构建信息",
|
||||
version_section: "版本",
|
||||
editor_version: "编辑器版本",
|
||||
desktop_build: "桌面端构建",
|
||||
};
|
||||
|
||||
pub(super) const ZH_HANT: SettingsStrings = SettingsStrings {
|
||||
settings: "設定",
|
||||
general_group: "一般",
|
||||
workspace_group: "工作區",
|
||||
nav_appearance: "外觀",
|
||||
nav_editor: "編輯器",
|
||||
nav_shortcuts: "快捷鍵",
|
||||
nav_preference: "偏好設定",
|
||||
nav_properties: "屬性",
|
||||
nav_storage: "儲存空間",
|
||||
nav_about: "關於",
|
||||
appearance_title: "外觀設定",
|
||||
appearance_desc: "自訂 AFFiNE 介面外觀",
|
||||
theme_section: "佈景主題",
|
||||
color_scheme: "色彩模式",
|
||||
color_scheme_desc: "選擇 AFFiNE 使用的色彩模式。",
|
||||
theme_light: "淺色",
|
||||
theme_dark: "深色",
|
||||
theme_system: "跟隨系統",
|
||||
display_language: "顯示語言",
|
||||
display_language_desc: "選擇介面使用的顯示語言。",
|
||||
editor_title: "編輯器設定",
|
||||
editor_desc: "新增與編輯文件的預設偏好",
|
||||
editor_general_section: "一般",
|
||||
new_doc_default_mode: "新文件預設模式",
|
||||
new_doc_default_mode_desc: "選擇新文件開啟時的預設檢視模式。",
|
||||
mode_page: "頁面",
|
||||
mode_edgeless: "無界畫布",
|
||||
font_style: "字體樣式",
|
||||
font_style_desc: "選擇文件內文的字體樣式。",
|
||||
font_size: "字型大小",
|
||||
font_size_desc: "選擇文件內文的基礎字級。",
|
||||
page_section: "頁面",
|
||||
default_page_width: "預設頁面寬度",
|
||||
default_page_width_desc: "選擇頁面的預設版面寬度。",
|
||||
page_width_standard: "標準寬度",
|
||||
page_width_full: "全寬",
|
||||
shortcuts_title: "鍵盤快捷鍵",
|
||||
shortcuts_desc: "工作台與編輯器快捷鍵",
|
||||
shortcuts_editor_section: "編輯器",
|
||||
shortcut_quick_search: "快速搜尋",
|
||||
preference_title: "工作區偏好設定",
|
||||
preference_desc: "自訂工作區名稱、文件範本與生命週期",
|
||||
info_section: "資訊",
|
||||
workspace_name: "工作區名稱",
|
||||
workspace_name_placeholder: "工作區名稱",
|
||||
save: "儲存",
|
||||
cancel: "取消",
|
||||
create: "建立",
|
||||
delete: "刪除",
|
||||
sync_status: "同步狀態",
|
||||
sync_readonly: "唯讀",
|
||||
sync_server: "已設定伺服器同步",
|
||||
sync_local: "僅本機",
|
||||
sync_memory: "僅記憶體",
|
||||
template_section: "範本",
|
||||
journal_template: "日記範本",
|
||||
journal_template_desc: "建立新日記項目時套用的範本。",
|
||||
page_template: "頁面範本",
|
||||
page_template_desc: "為新建頁面套用預設範本。",
|
||||
select_page_template: "選擇頁面範本",
|
||||
select_page_template_desc: "選擇新建頁面要複製的範本文件。",
|
||||
current_doc_as_template: "將目前文件設為範本",
|
||||
current_doc_as_template_desc: "將目前開啟的文件標記為工作區範本。",
|
||||
none_option: "無",
|
||||
untitled: "未命名",
|
||||
no_templates_yet: "尚未標記任何範本文件。",
|
||||
delete_workspace: "刪除工作區",
|
||||
delete_workspace_desc: "刪除此工作區會移除本機資料,此操作無法復原。",
|
||||
delete_workspace_title: "確定要刪除工作區嗎?",
|
||||
delete_workspace_confirm_prefix: "刪除 ",
|
||||
delete_workspace_confirm_suffix: " 後將無法復原,此工作區中的所有內容都將遺失。",
|
||||
properties_title: "工作區屬性",
|
||||
properties_desc: "管理此工作區文件中顯示的屬性",
|
||||
system_properties_section: "系統屬性",
|
||||
custom_properties_section: "自訂屬性",
|
||||
system_badge: "系統",
|
||||
add_property: "新增屬性",
|
||||
property_name_placeholder: "屬性名稱",
|
||||
no_custom_properties: "尚無自訂屬性,點擊「新增屬性」建立。",
|
||||
storage_title: "儲存空間",
|
||||
storage_desc: "檢視目前工作區儲存空間並匯出本機備份",
|
||||
backup_section: "備份",
|
||||
full_backup: "完整備份",
|
||||
full_backup_desc: "將所有工作區文件與本機資源匯出為 .affine 備份檔。",
|
||||
export_workspace: "匯出工作區",
|
||||
about_title: "關於 AFFiNE",
|
||||
about_desc: "關於 AFFiNE 的版本資訊",
|
||||
version_section: "版本",
|
||||
editor_version: "編輯器版本",
|
||||
desktop_build: "桌面版建置",
|
||||
};
|
||||
|
||||
pub(super) const JA: SettingsStrings = SettingsStrings {
|
||||
settings: "設定",
|
||||
general_group: "一般",
|
||||
workspace_group: "ワークスペース",
|
||||
nav_appearance: "外観",
|
||||
nav_editor: "エディター",
|
||||
nav_shortcuts: "ショートカット",
|
||||
nav_preference: "環境設定",
|
||||
nav_properties: "プロパティ",
|
||||
nav_storage: "ストレージ",
|
||||
nav_about: "AFFiNEについて",
|
||||
appearance_title: "外観設定",
|
||||
appearance_desc: "AFFiNE の表示スタイルをカスタマイズします",
|
||||
theme_section: "テーマ",
|
||||
color_scheme: "配色テーマ",
|
||||
color_scheme_desc: "AFFiNE で使用する配色モードを選択します。",
|
||||
theme_light: "ライト",
|
||||
theme_dark: "ダーク",
|
||||
theme_system: "システム設定に従う",
|
||||
display_language: "表示言語",
|
||||
display_language_desc: "インターフェースの表示言語を選択します。",
|
||||
editor_title: "エディター設定",
|
||||
editor_desc: "ドキュメントの作成と編集に関する設定",
|
||||
editor_general_section: "一般",
|
||||
new_doc_default_mode: "新規ドキュメントの標準モード",
|
||||
new_doc_default_mode_desc: "新しいドキュメントを開くときの既定モードを選択します。",
|
||||
mode_page: "ページ",
|
||||
mode_edgeless: "エッジレス",
|
||||
font_style: "フォントスタイル",
|
||||
font_style_desc: "本文に使用する書体を選択します。",
|
||||
font_size: "フォントサイズ",
|
||||
font_size_desc: "本文の基本フォントサイズを選択します。",
|
||||
page_section: "ページ",
|
||||
default_page_width: "既定のページ幅",
|
||||
default_page_width_desc: "ページの標準レイアウト幅を選択します。",
|
||||
page_width_standard: "標準",
|
||||
page_width_full: "全幅",
|
||||
shortcuts_title: "キーボードショートカット",
|
||||
shortcuts_desc: "ワークベンチとエディターのショートカット",
|
||||
shortcuts_editor_section: "エディター",
|
||||
shortcut_quick_search: "クイック検索",
|
||||
preference_title: "ワークスペース設定",
|
||||
preference_desc: "ワークスペース名・テンプレート・管理設定",
|
||||
info_section: "情報",
|
||||
workspace_name: "ワークスペース名",
|
||||
workspace_name_placeholder: "ワークスペース名",
|
||||
save: "保存",
|
||||
cancel: "キャンセル",
|
||||
create: "作成",
|
||||
delete: "削除",
|
||||
sync_status: "同期ステータス",
|
||||
sync_readonly: "読み取り専用",
|
||||
sync_server: "サーバー同期設定済み",
|
||||
sync_local: "ローカル",
|
||||
sync_memory: "メモリ内のみ",
|
||||
template_section: "テンプレート",
|
||||
journal_template: "ジャーナルテンプレート",
|
||||
journal_template_desc: "新しいジャーナル作成時に使用するテンプレート。",
|
||||
page_template: "ページテンプレート",
|
||||
page_template_desc: "新規ページに既定テンプレートを適用します。",
|
||||
select_page_template: "ページテンプレートを選択",
|
||||
select_page_template_desc: "新規ページで複製するテンプレート文書を選択します。",
|
||||
current_doc_as_template: "現在のドキュメントをテンプレートに指定",
|
||||
current_doc_as_template_desc: "開いているドキュメントを再利用可能なテンプレートにします。",
|
||||
none_option: "なし",
|
||||
untitled: "無題",
|
||||
no_templates_yet: "テンプレート文書はまだありません。",
|
||||
delete_workspace: "ワークスペースを削除",
|
||||
delete_workspace_desc: "削除するとこのワークスペースのローカルデータが消去されます。",
|
||||
delete_workspace_title: "ワークスペースを削除しますか?",
|
||||
delete_workspace_confirm_prefix: "",
|
||||
delete_workspace_confirm_suffix: " を削除すると元に戻せません。このワークスペースのすべての内容が失われます。",
|
||||
properties_title: "ワークスペースプロパティ",
|
||||
properties_desc: "ワークスペース全体で使用するプロパティを管理します",
|
||||
system_properties_section: "システムプロパティ",
|
||||
custom_properties_section: "カスタムプロパティ",
|
||||
system_badge: "システム",
|
||||
add_property: "プロパティを追加",
|
||||
property_name_placeholder: "プロパティ名",
|
||||
no_custom_properties: "カスタムプロパティはまだありません。",
|
||||
storage_title: "ストレージ",
|
||||
storage_desc: "ストレージ状況の確認とローカルバックアップの出力",
|
||||
backup_section: "バックアップ",
|
||||
full_backup: "フルバックアップ",
|
||||
full_backup_desc: "ワークスペース内のすべての文書と資産を .affine ファイルへ書き出します。",
|
||||
export_workspace: "ワークスペースを書き出す",
|
||||
about_title: "AFFiNE について",
|
||||
about_desc: "AFFiNE のバージョン情報",
|
||||
version_section: "バージョン",
|
||||
editor_version: "エディターバージョン",
|
||||
desktop_build: "デスクトップビルド",
|
||||
};
|
||||
|
||||
pub(super) const KO: SettingsStrings = SettingsStrings {
|
||||
settings: "설정",
|
||||
general_group: "일반",
|
||||
workspace_group: "워크스페이스",
|
||||
nav_appearance: "화면",
|
||||
nav_editor: "에디터",
|
||||
nav_shortcuts: "단축키",
|
||||
nav_preference: "환경설정",
|
||||
nav_properties: "속성",
|
||||
nav_storage: "저장소",
|
||||
nav_about: "정보",
|
||||
appearance_title: "화면 설정",
|
||||
appearance_desc: "AFFiNE 화면 스타일을 사용자화합니다",
|
||||
theme_section: "테마",
|
||||
color_scheme: "색상 테마",
|
||||
color_scheme_desc: "AFFiNE에서 사용할 색상 모드를 선택하세요.",
|
||||
theme_light: "라이트",
|
||||
theme_dark: "다크",
|
||||
theme_system: "시스템",
|
||||
display_language: "표시 언어",
|
||||
display_language_desc: "인터페이스에 사용할 언어를 선택하세요.",
|
||||
editor_title: "에디터 설정",
|
||||
editor_desc: "문서 생성 및 편집 기본 설정",
|
||||
editor_general_section: "일반",
|
||||
new_doc_default_mode: "새 문서 기본 모드",
|
||||
new_doc_default_mode_desc: "새 문서를 열 때 사용할 기본 모드를 선택하세요.",
|
||||
mode_page: "페이지",
|
||||
mode_edgeless: "엣지리스",
|
||||
font_style: "글꼴 스타일",
|
||||
font_style_desc: "문서 본문에 사용할 서체를 선택하세요.",
|
||||
font_size: "글자 크기",
|
||||
font_size_desc: "문서 본문의 기본 글자 크기를 선택하세요.",
|
||||
page_section: "페이지",
|
||||
default_page_width: "기본 페이지 너비",
|
||||
default_page_width_desc: "페이지의 기본 너비를 선택하세요.",
|
||||
page_width_standard: "표준",
|
||||
page_width_full: "전체 너비",
|
||||
shortcuts_title: "키보드 단축키",
|
||||
shortcuts_desc: "워크벤치와 에디터 단축키",
|
||||
shortcuts_editor_section: "에디터",
|
||||
shortcut_quick_search: "빠른 검색",
|
||||
preference_title: "워크스페이스 환경설정",
|
||||
preference_desc: "워크스페이스 이름, 문서 템플릿 및 관리",
|
||||
info_section: "정보",
|
||||
workspace_name: "워크스페이스 이름",
|
||||
workspace_name_placeholder: "워크스페이스 이름",
|
||||
save: "저장",
|
||||
cancel: "취소",
|
||||
create: "생성",
|
||||
delete: "삭제",
|
||||
sync_status: "동기화 상태",
|
||||
sync_readonly: "읽기 전용",
|
||||
sync_server: "서버 동기화 구성됨",
|
||||
sync_local: "로컬",
|
||||
sync_memory: "메모리 전용",
|
||||
template_section: "템플릿",
|
||||
journal_template: "저널 템플릿",
|
||||
journal_template_desc: "새 저널 생성 시 사용할 템플릿입니다.",
|
||||
page_template: "페이지 템플릿",
|
||||
page_template_desc: "새 페이지에 기본 템플릿을 적용합니다.",
|
||||
select_page_template: "페이지 템플릿 선택",
|
||||
select_page_template_desc: "새 페이지에서 복제할 템플릿 문서를 선택하세요.",
|
||||
current_doc_as_template: "현재 문서를 템플릿으로 지정",
|
||||
current_doc_as_template_desc: "열려 있는 문서를 재사용 가능한 템플릿으로 표시합니다.",
|
||||
none_option: "없음",
|
||||
untitled: "제목 없음",
|
||||
no_templates_yet: "지정된 템플릿 문서가 없습니다.",
|
||||
delete_workspace: "워크스페이스 삭제",
|
||||
delete_workspace_desc: "삭제하면 로컬 데이터가 모두 제거되며 되돌릴 수 없습니다.",
|
||||
delete_workspace_title: "워크스페이스를 삭제할까요?",
|
||||
delete_workspace_confirm_prefix: "",
|
||||
delete_workspace_confirm_suffix: " 삭제는 되돌릴 수 없으며, 이 워크스페이스의 모든 내용이 사라집니다.",
|
||||
properties_title: "워크스페이스 속성",
|
||||
properties_desc: "이 워크스페이스 문서에 표시되는 속성을 관리합니다",
|
||||
system_properties_section: "시스템 속성",
|
||||
custom_properties_section: "사용자 지정 속성",
|
||||
system_badge: "시스템",
|
||||
add_property: "속성 추가",
|
||||
property_name_placeholder: "속성 이름",
|
||||
no_custom_properties: "사용자 지정 속성이 없습니다.",
|
||||
storage_title: "저장소",
|
||||
storage_desc: "저장소 상태를 확인하고 로컬 백업을 내보냅니다",
|
||||
backup_section: "백업",
|
||||
full_backup: "전체 백업",
|
||||
full_backup_desc: "모든 문서와 로컬 자산을 .affine 백업 파일로 내보냅니다.",
|
||||
export_workspace: "워크스페이스 내보내기",
|
||||
about_title: "AFFiNE 정보",
|
||||
about_desc: "AFFiNE 버전 및 빌드 정보",
|
||||
version_section: "버전",
|
||||
editor_version: "에디터 버전",
|
||||
desktop_build: "데스크톱 빌드",
|
||||
};
|
||||
@@ -0,0 +1,373 @@
|
||||
use super::SettingsStrings;
|
||||
|
||||
pub(super) const FR: SettingsStrings = SettingsStrings {
|
||||
settings: "Paramètres",
|
||||
general_group: "Général",
|
||||
workspace_group: "Espace de travail",
|
||||
nav_appearance: "Apparence",
|
||||
nav_editor: "Éditeur",
|
||||
nav_shortcuts: "Raccourcis",
|
||||
nav_preference: "Préférences",
|
||||
nav_properties: "Propriétés",
|
||||
nav_storage: "Stockage",
|
||||
nav_about: "À propos",
|
||||
appearance_title: "Paramètres d'apparence",
|
||||
appearance_desc: "Personnalisez l'apparence d'AFFiNE",
|
||||
theme_section: "Thème",
|
||||
color_scheme: "Schéma de couleurs",
|
||||
color_scheme_desc: "Choisissez le mode d'affichage utilisé par AFFiNE.",
|
||||
theme_light: "Clair",
|
||||
theme_dark: "Sombre",
|
||||
theme_system: "Système",
|
||||
display_language: "Langue d'affichage",
|
||||
display_language_desc: "Sélectionnez la langue de l'interface.",
|
||||
editor_title: "Paramètres de l'éditeur",
|
||||
editor_desc: "Préférences de création et d'édition des documents",
|
||||
editor_general_section: "Général",
|
||||
new_doc_default_mode: "Mode par défaut",
|
||||
new_doc_default_mode_desc: "Choisissez comment s'ouvrent les nouveaux documents.",
|
||||
mode_page: "Page",
|
||||
mode_edgeless: "Sans limites",
|
||||
font_style: "Style de police",
|
||||
font_style_desc: "Choisissez la police du texte des documents.",
|
||||
font_size: "Taille de police",
|
||||
font_size_desc: "Choisissez la taille de base du texte des documents.",
|
||||
page_section: "Page",
|
||||
default_page_width: "Largeur de page par défaut",
|
||||
default_page_width_desc: "Choisissez la largeur par défaut des pages.",
|
||||
page_width_standard: "Standard",
|
||||
page_width_full: "Pleine largeur",
|
||||
shortcuts_title: "Raccourcis clavier",
|
||||
shortcuts_desc: "Raccourcis de l'espace de travail et de l'éditeur",
|
||||
shortcuts_editor_section: "Éditeur",
|
||||
shortcut_quick_search: "Recherche rapide",
|
||||
preference_title: "Préférences de l'espace",
|
||||
preference_desc: "Nom de l'espace, modèles de document et gestion",
|
||||
info_section: "Informations",
|
||||
workspace_name: "Nom de l'espace",
|
||||
workspace_name_placeholder: "Nom de l'espace",
|
||||
save: "Enregistrer",
|
||||
cancel: "Annuler",
|
||||
create: "Créer",
|
||||
delete: "Supprimer",
|
||||
sync_status: "Synchronisation",
|
||||
sync_readonly: "Lecture seule",
|
||||
sync_server: "Synchronisation configurée",
|
||||
sync_local: "Local",
|
||||
sync_memory: "En mémoire uniquement",
|
||||
template_section: "Modèles",
|
||||
journal_template: "Modèle de journal",
|
||||
journal_template_desc: "Modèle appliqué aux nouvelles entrées du journal.",
|
||||
page_template: "Modèle de page",
|
||||
page_template_desc: "Appliquer un modèle par défaut aux nouvelles pages.",
|
||||
select_page_template: "Choisir un modèle de page",
|
||||
select_page_template_desc: "Choisissez le document modèle copié par les nouvelles pages.",
|
||||
current_doc_as_template: "Document actuel comme modèle",
|
||||
current_doc_as_template_desc: "Marquer le document ouvert comme modèle réutilisable.",
|
||||
none_option: "Aucun",
|
||||
untitled: "Sans titre",
|
||||
no_templates_yet: "Aucun document modèle marqué pour le moment.",
|
||||
delete_workspace: "Supprimer l'espace",
|
||||
delete_workspace_desc: "La suppression efface les données locales de cet espace. Action irréversible.",
|
||||
delete_workspace_title: "Supprimer l'espace ?",
|
||||
delete_workspace_confirm_prefix: "La suppression de ",
|
||||
delete_workspace_confirm_suffix: " est irréversible. Tout le contenu de cet espace sera perdu.",
|
||||
properties_title: "Propriétés de l'espace",
|
||||
properties_desc: "Gérer les propriétés affichées dans cet espace",
|
||||
system_properties_section: "Propriétés système",
|
||||
custom_properties_section: "Propriétés personnalisées",
|
||||
system_badge: "Système",
|
||||
add_property: "Ajouter une propriété",
|
||||
property_name_placeholder: "Nom de la propriété",
|
||||
no_custom_properties: "Aucune propriété personnalisée pour le moment.",
|
||||
storage_title: "Stockage",
|
||||
storage_desc: "Consulter le stockage actuel et exporter une sauvegarde",
|
||||
backup_section: "Sauvegarde",
|
||||
full_backup: "Sauvegarde complète",
|
||||
full_backup_desc: "Exporter tous les documents et fichiers locaux dans une archive .affine.",
|
||||
export_workspace: "Exporter l'espace",
|
||||
about_title: "À propos d'AFFiNE",
|
||||
about_desc: "Informations sur l'application AFFiNE",
|
||||
version_section: "Version",
|
||||
editor_version: "Version de l'éditeur",
|
||||
desktop_build: "Version bureau",
|
||||
};
|
||||
|
||||
pub(super) const DE: SettingsStrings = SettingsStrings {
|
||||
settings: "Einstellungen",
|
||||
general_group: "Allgemein",
|
||||
workspace_group: "Arbeitsbereich",
|
||||
nav_appearance: "Erscheinungsbild",
|
||||
nav_editor: "Editor",
|
||||
nav_shortcuts: "Tastenkürzel",
|
||||
nav_preference: "Einstellungen",
|
||||
nav_properties: "Eigenschaften",
|
||||
nav_storage: "Speicher",
|
||||
nav_about: "Über",
|
||||
appearance_title: "Erscheinungsbild",
|
||||
appearance_desc: "Erscheinungsbild von AFFiNE anpassen",
|
||||
theme_section: "Design",
|
||||
color_scheme: "Farbschema",
|
||||
color_scheme_desc: "Farbmodus für AFFiNE auswählen.",
|
||||
theme_light: "Hell",
|
||||
theme_dark: "Dunkel",
|
||||
theme_system: "System",
|
||||
display_language: "Anzeigesprache",
|
||||
display_language_desc: "Sprache für die Benutzeroberfläche auswählen.",
|
||||
editor_title: "Editor-Einstellungen",
|
||||
editor_desc: "Einstellungen zum Erstellen und Bearbeiten von Dokumenten",
|
||||
editor_general_section: "Allgemein",
|
||||
new_doc_default_mode: "Standardmodus für neue Dokumente",
|
||||
new_doc_default_mode_desc: "Standardansicht beim Öffnen neuer Dokumente wählen.",
|
||||
mode_page: "Seite",
|
||||
mode_edgeless: "Endlosfläche",
|
||||
font_style: "Schriftstil",
|
||||
font_style_desc: "Schriftart für den Dokumenttext wählen.",
|
||||
font_size: "Schriftgröße",
|
||||
font_size_desc: "Grundschriftgröße für den Dokumenttext wählen.",
|
||||
page_section: "Seite",
|
||||
default_page_width: "Standard-Seitenbreite",
|
||||
default_page_width_desc: "Standardbreite für Seiten festlegen.",
|
||||
page_width_standard: "Standard",
|
||||
page_width_full: "Volle Breite",
|
||||
shortcuts_title: "Tastenkürzel",
|
||||
shortcuts_desc: "Tastenkürzel für Arbeitsbereich und Editor",
|
||||
shortcuts_editor_section: "Editor",
|
||||
shortcut_quick_search: "Schnellsuche",
|
||||
preference_title: "Arbeitsbereichseinstellungen",
|
||||
preference_desc: "Name, Dokumentvorlagen und Verwaltung des Arbeitsbereichs",
|
||||
info_section: "Info",
|
||||
workspace_name: "Arbeitsbereichsname",
|
||||
workspace_name_placeholder: "Arbeitsbereichsname",
|
||||
save: "Speichern",
|
||||
cancel: "Abbrechen",
|
||||
create: "Erstellen",
|
||||
delete: "Löschen",
|
||||
sync_status: "Synchronisierungsstatus",
|
||||
sync_readonly: "Schreibgeschützt",
|
||||
sync_server: "Serversynchronisierung eingerichtet",
|
||||
sync_local: "Lokal",
|
||||
sync_memory: "Nur im Arbeitsspeicher",
|
||||
template_section: "Vorlagen",
|
||||
journal_template: "Journal-Vorlage",
|
||||
journal_template_desc: "Vorlage für neue Journaleinträge.",
|
||||
page_template: "Seitenvorlage",
|
||||
page_template_desc: "Standardvorlage für neue Seiten verwenden.",
|
||||
select_page_template: "Seitenvorlage wählen",
|
||||
select_page_template_desc: "Vorlagendokument für neue Seiten auswählen.",
|
||||
current_doc_as_template: "Aktuelles Dokument als Vorlage",
|
||||
current_doc_as_template_desc: "Geöffnetes Dokument als wiederverwendbare Vorlage markieren.",
|
||||
none_option: "Keine",
|
||||
untitled: "Unbenannt",
|
||||
no_templates_yet: "Noch keine Vorlagendokumente markiert.",
|
||||
delete_workspace: "Arbeitsbereich löschen",
|
||||
delete_workspace_desc: "Beim Löschen werden lokale Daten entfernt. Dies kann nicht rückgängig gemacht werden.",
|
||||
delete_workspace_title: "Arbeitsbereich löschen?",
|
||||
delete_workspace_confirm_prefix: "Das Löschen von ",
|
||||
delete_workspace_confirm_suffix: " kann nicht rückgängig gemacht werden. Alle Inhalte gehen verloren.",
|
||||
properties_title: "Arbeitsbereichseigenschaften",
|
||||
properties_desc: "Eigenschaften für Dokumente in diesem Arbeitsbereich verwalten",
|
||||
system_properties_section: "Systemeigenschaften",
|
||||
custom_properties_section: "Benutzerdefinierte Eigenschaften",
|
||||
system_badge: "System",
|
||||
add_property: "Eigenschaft hinzufügen",
|
||||
property_name_placeholder: "Eigenschaftsname",
|
||||
no_custom_properties: "Noch keine benutzerdefinierten Eigenschaften vorhanden.",
|
||||
storage_title: "Speicher",
|
||||
storage_desc: "Speichernutzung prüfen und lokale Sicherung exportieren",
|
||||
backup_section: "Sicherung",
|
||||
full_backup: "Vollständige Sicherung",
|
||||
full_backup_desc: "Alle Dokumente und lokalen Dateien als .affine-Sicherung exportieren.",
|
||||
export_workspace: "Arbeitsbereich exportieren",
|
||||
about_title: "Über AFFiNE",
|
||||
about_desc: "Informationen zu AFFiNE",
|
||||
version_section: "Version",
|
||||
editor_version: "Editor-Version",
|
||||
desktop_build: "Desktop-Build",
|
||||
};
|
||||
|
||||
pub(super) const ES: SettingsStrings = SettingsStrings {
|
||||
settings: "Ajustes",
|
||||
general_group: "General",
|
||||
workspace_group: "Espacio de trabajo",
|
||||
nav_appearance: "Apariencia",
|
||||
nav_editor: "Editor",
|
||||
nav_shortcuts: "Atajos",
|
||||
nav_preference: "Preferencias",
|
||||
nav_properties: "Propiedades",
|
||||
nav_storage: "Almacenamiento",
|
||||
nav_about: "Acerca de",
|
||||
appearance_title: "Ajustes de apariencia",
|
||||
appearance_desc: "Personaliza el aspecto de AFFiNE",
|
||||
theme_section: "Tema",
|
||||
color_scheme: "Esquema de color",
|
||||
color_scheme_desc: "Elige el modo de color de AFFiNE.",
|
||||
theme_light: "Claro",
|
||||
theme_dark: "Oscuro",
|
||||
theme_system: "Sistema",
|
||||
display_language: "Idioma",
|
||||
display_language_desc: "Selecciona el idioma de la interfaz.",
|
||||
editor_title: "Ajustes del editor",
|
||||
editor_desc: "Preferencias para crear y editar documentos",
|
||||
editor_general_section: "General",
|
||||
new_doc_default_mode: "Modo predeterminado",
|
||||
new_doc_default_mode_desc: "Elige cómo se abren los documentos nuevos.",
|
||||
mode_page: "Página",
|
||||
mode_edgeless: "Sin bordes",
|
||||
font_style: "Estilo de fuente",
|
||||
font_style_desc: "Elige la tipografía del texto.",
|
||||
font_size: "Tamaño de fuente",
|
||||
font_size_desc: "Elige el tamaño base del texto.",
|
||||
page_section: "Página",
|
||||
default_page_width: "Ancho predeterminado",
|
||||
default_page_width_desc: "Elige el ancho predeterminado de las páginas.",
|
||||
page_width_standard: "Estándar",
|
||||
page_width_full: "Ancho completo",
|
||||
shortcuts_title: "Atajos de teclado",
|
||||
shortcuts_desc: "Atajos del área de trabajo y del editor",
|
||||
shortcuts_editor_section: "Editor",
|
||||
shortcut_quick_search: "Búsqueda rápida",
|
||||
preference_title: "Preferencias del espacio",
|
||||
preference_desc: "Nombre del espacio, plantillas de documentos y ciclo de vida",
|
||||
info_section: "Información",
|
||||
workspace_name: "Nombre del espacio",
|
||||
workspace_name_placeholder: "Nombre del espacio",
|
||||
save: "Guardar",
|
||||
cancel: "Cancelar",
|
||||
create: "Crear",
|
||||
delete: "Eliminar",
|
||||
sync_status: "Estado de sincronización",
|
||||
sync_readonly: "Solo lectura",
|
||||
sync_server: "Sincronización configurada",
|
||||
sync_local: "Local",
|
||||
sync_memory: "Solo en memoria",
|
||||
template_section: "Plantillas",
|
||||
journal_template: "Plantilla de diario",
|
||||
journal_template_desc: "Plantilla utilizada al crear entradas de diario.",
|
||||
page_template: "Plantilla de página",
|
||||
page_template_desc: "Aplicar una plantilla predeterminada a las páginas nuevas.",
|
||||
select_page_template: "Seleccionar plantilla de página",
|
||||
select_page_template_desc: "Elige la plantilla que copiarán las nuevas páginas.",
|
||||
current_doc_as_template: "Documento actual como plantilla",
|
||||
current_doc_as_template_desc: "Marcar el documento abierto como plantilla reutilizable.",
|
||||
none_option: "Ninguna",
|
||||
untitled: "Sin título",
|
||||
no_templates_yet: "Aún no hay documentos plantilla.",
|
||||
delete_workspace: "Eliminar espacio",
|
||||
delete_workspace_desc: "Eliminar este espacio borra sus datos locales. Esta acción no se puede deshacer.",
|
||||
delete_workspace_title: "¿Eliminar espacio?",
|
||||
delete_workspace_confirm_prefix: "Eliminar ",
|
||||
delete_workspace_confirm_suffix: " no se puede deshacer. Se perderá todo el contenido de este espacio.",
|
||||
properties_title: "Propiedades del espacio",
|
||||
properties_desc: "Gestiona las propiedades mostradas en este espacio",
|
||||
system_properties_section: "Propiedades del sistema",
|
||||
custom_properties_section: "Propiedades personalizadas",
|
||||
system_badge: "Sistema",
|
||||
add_property: "Añadir propiedad",
|
||||
property_name_placeholder: "Nombre de la propiedad",
|
||||
no_custom_properties: "Aún no hay propiedades personalizadas.",
|
||||
storage_title: "Almacenamiento",
|
||||
storage_desc: "Consulta el almacenamiento y exporta una copia local",
|
||||
backup_section: "Copia de seguridad",
|
||||
full_backup: "Copia completa",
|
||||
full_backup_desc: "Exportar todos los documentos y archivos locales como archivo .affine.",
|
||||
export_workspace: "Exportar espacio",
|
||||
about_title: "Acerca de AFFiNE",
|
||||
about_desc: "Información sobre AFFiNE",
|
||||
version_section: "Versión",
|
||||
editor_version: "Versión del editor",
|
||||
desktop_build: "Compilación de escritorio",
|
||||
};
|
||||
|
||||
pub(super) const PT_BR: SettingsStrings = SettingsStrings {
|
||||
settings: "Configurações",
|
||||
general_group: "Geral",
|
||||
workspace_group: "Espaço de trabalho",
|
||||
nav_appearance: "Aparência",
|
||||
nav_editor: "Editor",
|
||||
nav_shortcuts: "Atalhos",
|
||||
nav_preference: "Preferências",
|
||||
nav_properties: "Propriedades",
|
||||
nav_storage: "Armazenamento",
|
||||
nav_about: "Sobre",
|
||||
appearance_title: "Configurações de aparência",
|
||||
appearance_desc: "Personalize a aparência do AFFiNE",
|
||||
theme_section: "Tema",
|
||||
color_scheme: "Esquema de cores",
|
||||
color_scheme_desc: "Escolha o modo de cores usado pelo AFFiNE.",
|
||||
theme_light: "Claro",
|
||||
theme_dark: "Escuro",
|
||||
theme_system: "Sistema",
|
||||
display_language: "Idioma de exibição",
|
||||
display_language_desc: "Selecione o idioma da interface.",
|
||||
editor_title: "Configurações do editor",
|
||||
editor_desc: "Preferências para criar e editar documentos",
|
||||
editor_general_section: "Geral",
|
||||
new_doc_default_mode: "Modo padrão de documento",
|
||||
new_doc_default_mode_desc: "Escolha como novos documentos são abertos.",
|
||||
mode_page: "Página",
|
||||
mode_edgeless: "Sem limites",
|
||||
font_style: "Estilo da fonte",
|
||||
font_style_desc: "Escolha a fonte do texto dos documentos.",
|
||||
font_size: "Tamanho da fonte",
|
||||
font_size_desc: "Escolha o tamanho base do texto.",
|
||||
page_section: "Página",
|
||||
default_page_width: "Largura padrão da página",
|
||||
default_page_width_desc: "Escolha a largura padrão das páginas.",
|
||||
page_width_standard: "Padrão",
|
||||
page_width_full: "Largura total",
|
||||
shortcuts_title: "Atalhos de teclado",
|
||||
shortcuts_desc: "Atalhos da área de trabalho e do editor",
|
||||
shortcuts_editor_section: "Editor",
|
||||
shortcut_quick_search: "Busca rápida",
|
||||
preference_title: "Preferências do espaço",
|
||||
preference_desc: "Nome do espaço, modelos de documento e ciclo de vida",
|
||||
info_section: "Informações",
|
||||
workspace_name: "Nome do espaço",
|
||||
workspace_name_placeholder: "Nome do espaço",
|
||||
save: "Salvar",
|
||||
cancel: "Cancelar",
|
||||
create: "Criar",
|
||||
delete: "Excluir",
|
||||
sync_status: "Status de sincronização",
|
||||
sync_readonly: "Somente leitura",
|
||||
sync_server: "Sincronização configurada",
|
||||
sync_local: "Local",
|
||||
sync_memory: "Somente em memória",
|
||||
template_section: "Modelos",
|
||||
journal_template: "Modelo de diário",
|
||||
journal_template_desc: "Modelo aplicado ao criar novas entradas de diário.",
|
||||
page_template: "Modelo de página",
|
||||
page_template_desc: "Aplicar um modelo padrão às novas páginas.",
|
||||
select_page_template: "Selecionar modelo de página",
|
||||
select_page_template_desc: "Escolha o modelo que as novas páginas copiam.",
|
||||
current_doc_as_template: "Documento atual como modelo",
|
||||
current_doc_as_template_desc: "Marcar o documento aberto como modelo reutilizável.",
|
||||
none_option: "Nenhum",
|
||||
untitled: "Sem título",
|
||||
no_templates_yet: "Nenhum documento modelo marcado ainda.",
|
||||
delete_workspace: "Excluir espaço",
|
||||
delete_workspace_desc: "Excluir este espaço remove seus dados locais. Isso não pode ser desfeito.",
|
||||
delete_workspace_title: "Excluir espaço?",
|
||||
delete_workspace_confirm_prefix: "Excluir ",
|
||||
delete_workspace_confirm_suffix: " não pode ser desfeito. Todo o conteúdo deste espaço será perdido.",
|
||||
properties_title: "Propriedades do espaço",
|
||||
properties_desc: "Gerencie as propriedades exibidas neste espaço",
|
||||
system_properties_section: "Propriedades do sistema",
|
||||
custom_properties_section: "Propriedades personalizadas",
|
||||
system_badge: "Sistema",
|
||||
add_property: "Adicionar propriedade",
|
||||
property_name_placeholder: "Nome da propriedade",
|
||||
no_custom_properties: "Nenhuma propriedade personalizada ainda.",
|
||||
storage_title: "Armazenamento",
|
||||
storage_desc: "Visualize o armazenamento atual e exporte um backup local",
|
||||
backup_section: "Backup",
|
||||
full_backup: "Backup completo",
|
||||
full_backup_desc: "Exportar todos os documentos e arquivos locais como backup .affine.",
|
||||
export_workspace: "Exportar espaço",
|
||||
about_title: "Sobre o AFFiNE",
|
||||
about_desc: "Informações sobre o AFFiNE",
|
||||
version_section: "Versão",
|
||||
editor_version: "Versão do editor",
|
||||
desktop_build: "Versão desktop",
|
||||
};
|
||||
@@ -0,0 +1,288 @@
|
||||
//! Localized UI copy for the desktop settings modal.
|
||||
|
||||
mod cjk;
|
||||
mod european;
|
||||
|
||||
/// Localized strings rendered by the settings modal for a single display language.
|
||||
#[derive(Clone, Copy)]
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
pub(super) struct SettingsStrings {
|
||||
pub settings: &'static str,
|
||||
pub general_group: &'static str,
|
||||
pub workspace_group: &'static str,
|
||||
pub nav_appearance: &'static str,
|
||||
pub nav_editor: &'static str,
|
||||
pub nav_shortcuts: &'static str,
|
||||
pub nav_preference: &'static str,
|
||||
pub nav_properties: &'static str,
|
||||
pub nav_storage: &'static str,
|
||||
pub nav_about: &'static str,
|
||||
|
||||
pub appearance_title: &'static str,
|
||||
pub appearance_desc: &'static str,
|
||||
pub theme_section: &'static str,
|
||||
pub color_scheme: &'static str,
|
||||
pub color_scheme_desc: &'static str,
|
||||
pub theme_light: &'static str,
|
||||
pub theme_dark: &'static str,
|
||||
pub theme_system: &'static str,
|
||||
pub display_language: &'static str,
|
||||
pub display_language_desc: &'static str,
|
||||
|
||||
pub editor_title: &'static str,
|
||||
pub editor_desc: &'static str,
|
||||
pub editor_general_section: &'static str,
|
||||
pub new_doc_default_mode: &'static str,
|
||||
pub new_doc_default_mode_desc: &'static str,
|
||||
pub mode_page: &'static str,
|
||||
pub mode_edgeless: &'static str,
|
||||
pub font_style: &'static str,
|
||||
pub font_style_desc: &'static str,
|
||||
pub font_size: &'static str,
|
||||
pub font_size_desc: &'static str,
|
||||
pub page_section: &'static str,
|
||||
pub default_page_width: &'static str,
|
||||
pub default_page_width_desc: &'static str,
|
||||
pub page_width_standard: &'static str,
|
||||
pub page_width_full: &'static str,
|
||||
|
||||
pub shortcuts_title: &'static str,
|
||||
pub shortcuts_desc: &'static str,
|
||||
pub shortcuts_editor_section: &'static str,
|
||||
pub shortcut_quick_search: &'static str,
|
||||
|
||||
pub preference_title: &'static str,
|
||||
pub preference_desc: &'static str,
|
||||
pub info_section: &'static str,
|
||||
pub workspace_name: &'static str,
|
||||
pub workspace_name_placeholder: &'static str,
|
||||
pub save: &'static str,
|
||||
pub cancel: &'static str,
|
||||
pub create: &'static str,
|
||||
pub delete: &'static str,
|
||||
pub sync_status: &'static str,
|
||||
pub sync_readonly: &'static str,
|
||||
pub sync_server: &'static str,
|
||||
pub sync_local: &'static str,
|
||||
pub sync_memory: &'static str,
|
||||
pub template_section: &'static str,
|
||||
pub journal_template: &'static str,
|
||||
pub journal_template_desc: &'static str,
|
||||
pub page_template: &'static str,
|
||||
pub page_template_desc: &'static str,
|
||||
pub select_page_template: &'static str,
|
||||
pub select_page_template_desc: &'static str,
|
||||
pub current_doc_as_template: &'static str,
|
||||
pub current_doc_as_template_desc: &'static str,
|
||||
pub none_option: &'static str,
|
||||
pub untitled: &'static str,
|
||||
pub no_templates_yet: &'static str,
|
||||
pub delete_workspace: &'static str,
|
||||
pub delete_workspace_desc: &'static str,
|
||||
pub delete_workspace_title: &'static str,
|
||||
pub delete_workspace_confirm_prefix: &'static str,
|
||||
pub delete_workspace_confirm_suffix: &'static str,
|
||||
|
||||
pub properties_title: &'static str,
|
||||
pub properties_desc: &'static str,
|
||||
pub system_properties_section: &'static str,
|
||||
pub custom_properties_section: &'static str,
|
||||
pub system_badge: &'static str,
|
||||
pub add_property: &'static str,
|
||||
pub property_name_placeholder: &'static str,
|
||||
pub no_custom_properties: &'static str,
|
||||
|
||||
pub storage_title: &'static str,
|
||||
pub storage_desc: &'static str,
|
||||
pub backup_section: &'static str,
|
||||
pub full_backup: &'static str,
|
||||
pub full_backup_desc: &'static str,
|
||||
pub export_workspace: &'static str,
|
||||
|
||||
pub about_title: &'static str,
|
||||
pub about_desc: &'static str,
|
||||
pub version_section: &'static str,
|
||||
pub editor_version: &'static str,
|
||||
pub desktop_build: &'static str,
|
||||
}
|
||||
|
||||
impl SettingsStrings {
|
||||
pub(super) fn delete_workspace_confirm_desc(&self, ws_name: &str) -> String {
|
||||
format!(
|
||||
"{}({ws_name}){}",
|
||||
self.delete_workspace_confirm_prefix, self.delete_workspace_confirm_suffix
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) const EN: SettingsStrings = SettingsStrings {
|
||||
settings: "Settings",
|
||||
general_group: "General",
|
||||
workspace_group: "Workspace",
|
||||
nav_appearance: "Appearance",
|
||||
nav_editor: "Editor",
|
||||
nav_shortcuts: "Shortcuts",
|
||||
nav_preference: "Preference",
|
||||
nav_properties: "Properties",
|
||||
nav_storage: "Storage",
|
||||
nav_about: "About",
|
||||
|
||||
appearance_title: "Appearance settings",
|
||||
appearance_desc: "Customize your AFFiNE appearance",
|
||||
theme_section: "Theme",
|
||||
color_scheme: "Color Scheme",
|
||||
color_scheme_desc: "Choose the color scheme used by AFFiNE.",
|
||||
theme_light: "Light",
|
||||
theme_dark: "Dark",
|
||||
theme_system: "System",
|
||||
display_language: "Display language",
|
||||
display_language_desc: "Select the language for the interface.",
|
||||
|
||||
editor_title: "Editor settings",
|
||||
editor_desc: "Preferences for creating and editing documents",
|
||||
editor_general_section: "General",
|
||||
new_doc_default_mode: "New Doc Default Mode",
|
||||
new_doc_default_mode_desc: "Choose how new documents open.",
|
||||
mode_page: "Page",
|
||||
mode_edgeless: "Edgeless",
|
||||
font_style: "Font Style",
|
||||
font_style_desc: "Choose the typeface for document text.",
|
||||
font_size: "Font Size",
|
||||
font_size_desc: "Choose the base size for document text.",
|
||||
page_section: "Page",
|
||||
default_page_width: "Default page width",
|
||||
default_page_width_desc: "Choose the default width for pages.",
|
||||
page_width_standard: "Standard",
|
||||
page_width_full: "Full width",
|
||||
|
||||
shortcuts_title: "Keyboard shortcuts",
|
||||
shortcuts_desc: "Shortcuts for the workbench and editor",
|
||||
shortcuts_editor_section: "Editor",
|
||||
shortcut_quick_search: "Quick Search",
|
||||
|
||||
preference_title: "Workspace preference",
|
||||
preference_desc: "Customize workspace name, document templates, and lifecycle",
|
||||
info_section: "Info",
|
||||
workspace_name: "Workspace Name",
|
||||
workspace_name_placeholder: "Workspace name",
|
||||
save: "Save",
|
||||
cancel: "Cancel",
|
||||
create: "Create",
|
||||
delete: "Delete",
|
||||
sync_status: "Sync status",
|
||||
sync_readonly: "Read-only",
|
||||
sync_server: "Server sync configured",
|
||||
sync_local: "Local",
|
||||
sync_memory: "In memory only",
|
||||
template_section: "Template",
|
||||
journal_template: "Journal Template",
|
||||
journal_template_desc: "Template used when creating new journal entries.",
|
||||
page_template: "Page Template",
|
||||
page_template_desc: "Apply a default template to newly created pages.",
|
||||
select_page_template: "Select Page Template",
|
||||
select_page_template_desc: "Choose which template document new pages copy.",
|
||||
current_doc_as_template: "Current doc as template",
|
||||
current_doc_as_template_desc: "Mark the open document as a reusable workspace template.",
|
||||
none_option: "None",
|
||||
untitled: "Untitled",
|
||||
no_templates_yet: "No template documents marked yet.",
|
||||
delete_workspace: "Delete workspace",
|
||||
delete_workspace_desc: "Deleting this workspace removes its local data. This cannot be undone.",
|
||||
delete_workspace_title: "Delete workspace?",
|
||||
delete_workspace_confirm_prefix: "Deleting ",
|
||||
delete_workspace_confirm_suffix: " cannot be undone. All contents in this workspace will be lost.",
|
||||
|
||||
properties_title: "Workspace properties",
|
||||
properties_desc: "Manage properties shown in documents across this workspace",
|
||||
system_properties_section: "System properties",
|
||||
custom_properties_section: "Custom properties",
|
||||
system_badge: "System",
|
||||
add_property: "Add property",
|
||||
property_name_placeholder: "Property name",
|
||||
no_custom_properties: "No custom properties yet. Click Add property to create one.",
|
||||
|
||||
storage_title: "Storage",
|
||||
storage_desc: "View current workspace storage and export a local backup",
|
||||
backup_section: "Backup",
|
||||
full_backup: "Full Backup",
|
||||
full_backup_desc: "Export all workspace documents and local assets as an .affine backup file.",
|
||||
export_workspace: "Export Workspace",
|
||||
|
||||
about_title: "About AFFiNE",
|
||||
about_desc: "Information about AFFiNE",
|
||||
version_section: "Version",
|
||||
editor_version: "Editor version",
|
||||
desktop_build: "Desktop build",
|
||||
};
|
||||
|
||||
/// Return `true` when `language_code` maps to a complete translated table in `strings_for`.
|
||||
pub(super) fn has_translation(language_code: &str) -> bool {
|
||||
language_code.eq_ignore_ascii_case("en")
|
||||
|| language_code.eq_ignore_ascii_case("zh-Hans")
|
||||
|| language_code.eq_ignore_ascii_case("zh-Hant")
|
||||
|| language_code.eq_ignore_ascii_case("ja")
|
||||
|| language_code.eq_ignore_ascii_case("ko")
|
||||
|| language_code.eq_ignore_ascii_case("fr")
|
||||
|| language_code.eq_ignore_ascii_case("de")
|
||||
|| language_code.eq_ignore_ascii_case("es")
|
||||
|| language_code.to_ascii_lowercase().starts_with("es-")
|
||||
|| language_code.eq_ignore_ascii_case("pt-BR")
|
||||
|| language_code.to_ascii_lowercase().starts_with("pt-")
|
||||
}
|
||||
|
||||
/// Return the localized copy table for `language_code` (falling back to English).
|
||||
pub(super) fn strings_for(language_code: &str) -> &'static SettingsStrings {
|
||||
if language_code.eq_ignore_ascii_case("zh-Hans") {
|
||||
&cjk::ZH_HANS
|
||||
} else if language_code.eq_ignore_ascii_case("zh-Hant") {
|
||||
&cjk::ZH_HANT
|
||||
} else if language_code.eq_ignore_ascii_case("ja") {
|
||||
&cjk::JA
|
||||
} else if language_code.eq_ignore_ascii_case("ko") {
|
||||
&cjk::KO
|
||||
} else if language_code.eq_ignore_ascii_case("fr") {
|
||||
&european::FR
|
||||
} else if language_code.eq_ignore_ascii_case("de") {
|
||||
&european::DE
|
||||
} else if language_code.eq_ignore_ascii_case("es")
|
||||
|| language_code.to_ascii_lowercase().starts_with("es-")
|
||||
{
|
||||
&european::ES
|
||||
} else if language_code.eq_ignore_ascii_case("pt-BR")
|
||||
|| language_code.to_ascii_lowercase().starts_with("pt-")
|
||||
{
|
||||
&european::PT_BR
|
||||
} else {
|
||||
&EN
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn translated_languages_have_localized_delete_confirm_and_sync_copy() {
|
||||
for lang in super::super::language::supported_languages() {
|
||||
assert!(
|
||||
has_translation(lang.code),
|
||||
"untranslated language {} must not be listed in selector",
|
||||
lang.code
|
||||
);
|
||||
let t = strings_for(lang.code);
|
||||
if !lang.code.eq_ignore_ascii_case("en") {
|
||||
assert_ne!(t.settings, EN.settings, "missing title for {}", lang.code);
|
||||
assert_ne!(
|
||||
t.sync_memory, EN.sync_memory,
|
||||
"missing sync status for {}",
|
||||
lang.code
|
||||
);
|
||||
assert_ne!(
|
||||
t.delete_workspace_confirm_suffix, EN.delete_workspace_confirm_suffix,
|
||||
"missing delete confirm copy for {}",
|
||||
lang.code
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
//! Interactive language selector for `Settings -> Appearance`.
|
||||
|
||||
use affine_client::i18n::{LanguageMeta, SUPPORTED_LANGUAGES, find_language};
|
||||
use ui::{
|
||||
Anchor, App, Entity, FontWeight, InteractiveElement, IntoElement, MouseButton, ParentElement,
|
||||
StatefulInteractiveElement, Styled, Window, anchored, deferred, div, point, px, svg,
|
||||
};
|
||||
use ui_tokens::icons;
|
||||
|
||||
use super::{
|
||||
MODAL_ID,
|
||||
controls::{FocusStops, ScrollRegion, focus_stop, scroll_area},
|
||||
i18n::has_translation,
|
||||
};
|
||||
use crate::{DesktopFlexExt, DesktopPalette, DesktopShellView};
|
||||
|
||||
const TRIGGER_RUNTIME_ID: &str = "settings-lang-trigger";
|
||||
const MENU_RUNTIME_ID: &str = "settings-lang-menu";
|
||||
const STATE_RUNTIME_ID: &str = "settings-lang-state";
|
||||
const SCROLL_RUNTIME_ID: &str = "settings-lang-scroll";
|
||||
const SCROLL_STATE_RUNTIME_ID: &str = "settings-lang-scroll-state";
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(super) struct LanguageMenuState {
|
||||
pub(super) open: bool,
|
||||
highlight: usize,
|
||||
}
|
||||
|
||||
pub(super) fn menu_state(window: &mut Window, app: &mut App) -> Entity<LanguageMenuState> {
|
||||
window.use_keyed_state(STATE_RUNTIME_ID, app, |_, _| LanguageMenuState::default())
|
||||
}
|
||||
|
||||
pub(super) fn close_if_open(menu: &Entity<LanguageMenuState>, app: &mut App) -> bool {
|
||||
if menu.read(app).open {
|
||||
menu.update(app, |state, cx| {
|
||||
state.open = false;
|
||||
cx.notify();
|
||||
});
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn supported_languages() -> Vec<&'static LanguageMeta> {
|
||||
SUPPORTED_LANGUAGES
|
||||
.iter()
|
||||
.filter(|lang| has_translation(lang.code))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn language_index(code: &str) -> usize {
|
||||
supported_languages()
|
||||
.iter()
|
||||
.position(|lang| lang.code.eq_ignore_ascii_case(code))
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn select_language(
|
||||
shell: &ui::WeakEntity<DesktopShellView>,
|
||||
state: &Entity<LanguageMenuState>,
|
||||
code: &'static str,
|
||||
scroll: &ScrollRegion,
|
||||
app: &mut App,
|
||||
) {
|
||||
let mut highlight = language_index(code);
|
||||
let _ = shell.update(app, |view, cx| {
|
||||
let saved = view.set_display_language(code, cx);
|
||||
highlight = language_index(&saved);
|
||||
});
|
||||
scroll.reset();
|
||||
state.update(app, |menu, cx| {
|
||||
menu.highlight = highlight;
|
||||
menu.open = false;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn selector(
|
||||
shell: &Entity<DesktopShellView>,
|
||||
palette: DesktopPalette,
|
||||
mode: ui_tokens::ThemeMode,
|
||||
stops: &mut FocusStops,
|
||||
window: &mut Window,
|
||||
app: &mut App,
|
||||
) -> impl IntoElement + use<> {
|
||||
let menu_state = menu_state(window, app);
|
||||
let menu_scroll = ScrollRegion::use_state(SCROLL_STATE_RUNTIME_ID, window, app);
|
||||
let snapshot_state = menu_state.read(app).clone();
|
||||
let current_code = shell.read(app).state().display_language.clone();
|
||||
let stop = focus_stop(TRIGGER_RUNTIME_ID, stops, window, app);
|
||||
let current_label = find_language(¤t_code).map_or("English", |lang| lang.original_name);
|
||||
let focused = stop.handle.is_focused(window);
|
||||
let keyboard = window.last_input_was_keyboard();
|
||||
|
||||
let click_state = menu_state.clone();
|
||||
let click_scroll = menu_scroll.clone();
|
||||
let click_focus = stop.handle.clone();
|
||||
let click_code = current_code.clone();
|
||||
let key_state = menu_state.clone();
|
||||
let key_scroll = menu_scroll.clone();
|
||||
let key_shell = shell.downgrade();
|
||||
let key_code = current_code.clone();
|
||||
let key_stop = stop.clone();
|
||||
|
||||
let languages = supported_languages();
|
||||
let lang_count = languages.len();
|
||||
let key_languages = languages.clone();
|
||||
|
||||
let mut wrapper = div().relative().w(px(250.0)).flex_shrink(0.0);
|
||||
wrapper.style().max_size.width = Some(ui::relative(1.0).into());
|
||||
|
||||
let trigger = div()
|
||||
.id(TRIGGER_RUNTIME_ID)
|
||||
.snapshot(
|
||||
ui::snap_id!("desktop.settings.appearance.language"),
|
||||
Some(MODAL_ID),
|
||||
)
|
||||
.snapshot_focused(focused)
|
||||
.track_focus(&stop.handle)
|
||||
.relative()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_between()
|
||||
.gap(px(8.0))
|
||||
.w_full()
|
||||
.h(px(32.0))
|
||||
.px(px(12.0))
|
||||
.rounded(px(8.0))
|
||||
.bg(palette.bg_elevated)
|
||||
.border_1()
|
||||
.border_color(if snapshot_state.open || (focused && keyboard) {
|
||||
palette.accent
|
||||
} else {
|
||||
palette.border
|
||||
})
|
||||
.hover(move |style| style.bg(palette.hover_overlay))
|
||||
.cursor_pointer()
|
||||
.text_size(px(12.0))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(palette.text_primary)
|
||||
.on_mouse_down(MouseButton::Left, move |_, window, app| {
|
||||
window.focus(&click_focus, app);
|
||||
})
|
||||
.on_click(move |_, _, app| {
|
||||
click_state.update(app, |menu, cx| {
|
||||
menu.open = !menu.open;
|
||||
if menu.open {
|
||||
menu.highlight = language_index(&click_code);
|
||||
} else {
|
||||
click_scroll.reset();
|
||||
}
|
||||
cx.notify();
|
||||
});
|
||||
})
|
||||
.on_key_down(move |event, window, app| {
|
||||
if event.keystroke.modifiers.modified() {
|
||||
return;
|
||||
}
|
||||
let key = event.keystroke.key.as_str();
|
||||
let open = key_state.read(app).open;
|
||||
match key {
|
||||
"escape" if open => {
|
||||
key_scroll.reset();
|
||||
key_state.update(app, |menu, cx| {
|
||||
menu.open = false;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
"up" if open => {
|
||||
key_state.update(app, |menu, cx| {
|
||||
menu.highlight = if menu.highlight == 0 {
|
||||
lang_count.saturating_sub(1)
|
||||
} else {
|
||||
menu.highlight - 1
|
||||
};
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
"down" if open => {
|
||||
key_state.update(app, |menu, cx| {
|
||||
menu.highlight = (menu.highlight + 1) % lang_count.max(1);
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
"home" if open => {
|
||||
key_state.update(app, |menu, cx| {
|
||||
menu.highlight = 0;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
"end" if open => {
|
||||
key_state.update(app, |menu, cx| {
|
||||
menu.highlight = lang_count.saturating_sub(1);
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
"enter" | "space" => {
|
||||
key_stop.reveal(window);
|
||||
if open {
|
||||
let idx = key_state.read(app).highlight;
|
||||
if let Some(lang) = key_languages.get(idx) {
|
||||
select_language(&key_shell, &key_state, lang.code, &key_scroll, app);
|
||||
}
|
||||
} else {
|
||||
key_state.update(app, |menu, cx| {
|
||||
menu.open = true;
|
||||
menu.highlight = language_index(&key_code);
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
}
|
||||
"down" if !open => {
|
||||
key_stop.reveal(window);
|
||||
key_state.update(app, |menu, cx| {
|
||||
menu.open = true;
|
||||
menu.highlight = language_index(&key_code);
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
_ => return,
|
||||
}
|
||||
window.prevent_default();
|
||||
app.stop_propagation();
|
||||
})
|
||||
.child(stop.probe())
|
||||
.child(div().min_w_0().truncate().child(current_label))
|
||||
.child(
|
||||
svg()
|
||||
.data(icons::ARROW_DOWN_SMALL.svg.as_bytes())
|
||||
.size(px(16.0))
|
||||
.flex_shrink(0.0)
|
||||
.text_color(palette.text_secondary),
|
||||
);
|
||||
|
||||
wrapper = wrapper.child(trigger);
|
||||
if snapshot_state.open {
|
||||
let bounds = stop.bounds.get();
|
||||
let tokens = crate::theme_tokens_for(mode);
|
||||
let panel_bg = crate::rgba_to_hsla(tokens.background_overlay_panel);
|
||||
let close_out = menu_state.clone();
|
||||
let out_scroll = menu_scroll.clone();
|
||||
let trigger_bounds = stop.bounds.clone();
|
||||
|
||||
let mut list = div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.flex_shrink(0.0)
|
||||
.gap(px(2.0))
|
||||
.p(px(6.0));
|
||||
for (idx, lang) in languages.iter().enumerate() {
|
||||
let selected = lang.code.eq_ignore_ascii_case(¤t_code);
|
||||
let highlighted = idx == snapshot_state.highlight;
|
||||
let pick_state = menu_state.clone();
|
||||
let pick_shell = shell.downgrade();
|
||||
let pick_scroll = menu_scroll.clone();
|
||||
let code = lang.code;
|
||||
list = list.child(
|
||||
div()
|
||||
.id(ui::SharedString::from(format!("settings-lang-opt-{code}")))
|
||||
.snapshot(
|
||||
ui::snap_id!("desktop.settings.appearance.language.menu.{code}"),
|
||||
None,
|
||||
)
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_between()
|
||||
.gap(px(8.0))
|
||||
.h(px(28.0))
|
||||
.px(px(8.0))
|
||||
.rounded(px(6.0))
|
||||
.flex_shrink(0.0)
|
||||
.cursor_pointer()
|
||||
.bg(if highlighted || selected {
|
||||
palette.hover_color
|
||||
} else {
|
||||
ui::transparent_black()
|
||||
})
|
||||
.hover(move |style| style.bg(palette.hover_color))
|
||||
.text_size(px(12.0))
|
||||
.text_color(palette.text_primary)
|
||||
.on_click(move |_, _, app| {
|
||||
select_language(&pick_shell, &pick_state, code, &pick_scroll, app);
|
||||
})
|
||||
.child(div().min_w_0().truncate().child(lang.original_name))
|
||||
.children(selected.then(|| {
|
||||
svg()
|
||||
.data(icons::DONE.svg.as_bytes())
|
||||
.size(px(14.0))
|
||||
.flex_shrink(0.0)
|
||||
.text_color(palette.accent)
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
let menu_box = div()
|
||||
.id(MENU_RUNTIME_ID)
|
||||
.snapshot(
|
||||
ui::snap_id!("desktop.settings.appearance.language.menu"),
|
||||
Some(MODAL_ID),
|
||||
)
|
||||
.occlude()
|
||||
.w(px(250.0))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.rounded(px(8.0))
|
||||
.bg(panel_bg)
|
||||
.border_1()
|
||||
.border_color(palette.border)
|
||||
.shadow(crate::theme_shadow(mode, "--affine-popover-shadow"))
|
||||
.on_mouse_down_out(move |event, _, app| {
|
||||
if !trigger_bounds.get().contains(&event.position) {
|
||||
out_scroll.reset();
|
||||
close_out.update(app, |menu, cx| {
|
||||
if menu.open {
|
||||
menu.open = false;
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
}
|
||||
})
|
||||
.child(scroll_area(SCROLL_RUNTIME_ID, &menu_scroll, list).h(px(240.0)));
|
||||
|
||||
wrapper = wrapper.child(
|
||||
deferred(
|
||||
anchored()
|
||||
.attach(bounds, Anchor::BottomLeft)
|
||||
.offset(point(px(0.0), px(4.0)))
|
||||
.child(menu_box),
|
||||
)
|
||||
.priority(2),
|
||||
);
|
||||
}
|
||||
wrapper
|
||||
}
|
||||
@@ -2,7 +2,15 @@
|
||||
|
||||
mod controls;
|
||||
mod font_size;
|
||||
mod i18n;
|
||||
mod language;
|
||||
mod pages;
|
||||
mod properties_page;
|
||||
mod property_row;
|
||||
mod storage_page;
|
||||
mod template_picker;
|
||||
mod text_input;
|
||||
mod workspace_pages;
|
||||
|
||||
use affine_store::directory::DocMode;
|
||||
use ui::{
|
||||
@@ -73,7 +81,9 @@ impl RenderOnce for SettingsModal {
|
||||
let selection =
|
||||
window.use_keyed_state("desktop.settings.selection", app, |_, _| Page::Appearance);
|
||||
let page = *selection.read(app);
|
||||
let mode = self.shell.read(app).state().theme;
|
||||
let state = self.shell.read(app).state();
|
||||
let mode = state.theme;
|
||||
let t = i18n::strings_for(&state.display_language);
|
||||
let palette = self.palette;
|
||||
let shell = self.shell.downgrade();
|
||||
let theme = crate::theme_tokens_for(mode);
|
||||
@@ -85,6 +95,7 @@ impl RenderOnce for SettingsModal {
|
||||
page,
|
||||
&selection,
|
||||
(palette, mode),
|
||||
t,
|
||||
nav_scroll.as_ref(),
|
||||
&mut stops,
|
||||
window,
|
||||
@@ -108,6 +119,22 @@ impl RenderOnce for SettingsModal {
|
||||
let close_focus = focus_stop("desktop.settings.close", &mut stops, window, app).handle;
|
||||
let close_down = close_focus.clone();
|
||||
let close_key_shell = shell.clone();
|
||||
let delete_prompt = workspace_pages::DeleteWorkspacePrompt::keyed(window, app);
|
||||
let lang_menu = language::menu_state(window, app);
|
||||
let tpl_menu = template_picker::menu_state(window, app);
|
||||
let tab_delete_prompt = delete_prompt.clone();
|
||||
let key_delete_prompt = delete_prompt.clone();
|
||||
let key_lang_menu = lang_menu.clone();
|
||||
let key_tpl_menu = tpl_menu.clone();
|
||||
let esc_shell = shell.clone();
|
||||
let delete_overlay = workspace_pages::render_delete_confirm_overlay(
|
||||
&delete_prompt,
|
||||
&self.shell,
|
||||
palette,
|
||||
mode,
|
||||
window,
|
||||
app,
|
||||
);
|
||||
let modal = div()
|
||||
.id(MODAL_ID)
|
||||
.snapshot(MODAL_ID, Some("desktop.shell.root"))
|
||||
@@ -121,12 +148,30 @@ impl RenderOnce for SettingsModal {
|
||||
&& !m.control
|
||||
&& !m.alt
|
||||
&& !m.platform
|
||||
&& !tab_delete_prompt.read(app).open
|
||||
&& stops.step(m.shift, window, app)
|
||||
{
|
||||
window.prevent_default();
|
||||
app.stop_propagation();
|
||||
}
|
||||
})
|
||||
.on_key_down(move |event, window, app| {
|
||||
if event.keystroke.key == "escape" && !event.keystroke.modifiers.modified() {
|
||||
if key_delete_prompt.read(app).open {
|
||||
workspace_pages::DeleteWorkspacePrompt::close(
|
||||
&key_delete_prompt,
|
||||
window,
|
||||
app,
|
||||
);
|
||||
} else if !template_picker::close_if_open(&key_tpl_menu, app)
|
||||
&& !language::close_if_open(&key_lang_menu, app)
|
||||
{
|
||||
let _ = esc_shell.update(app, |view, cx| view.dismiss_modal(window, cx));
|
||||
}
|
||||
window.prevent_default();
|
||||
app.stop_propagation();
|
||||
}
|
||||
})
|
||||
.occlude()
|
||||
.overflow_hidden()
|
||||
.rounded(px(12.0))
|
||||
@@ -161,6 +206,7 @@ impl RenderOnce for SettingsModal {
|
||||
})
|
||||
.child(nav)
|
||||
.child(pane)
|
||||
.children(delete_overlay)
|
||||
.child(
|
||||
button("desktop.settings.close")
|
||||
.track_focus(&close_focus)
|
||||
@@ -246,30 +292,37 @@ pub(crate) struct WorkspaceSummary {
|
||||
|
||||
impl WorkspaceSummary {
|
||||
pub(crate) fn of(shell: &DesktopShellView) -> Self {
|
||||
let workspace = shell.state().store.active_workspace();
|
||||
Self::new(&workspace.name, WorkspaceStorage::of(shell))
|
||||
let state = shell.state();
|
||||
let workspace = state.store.active_workspace();
|
||||
let t = i18n::strings_for(&state.display_language);
|
||||
Self::new_with_strings(&workspace.name, WorkspaceStorage::of(shell), t)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn new(name: &str, storage: WorkspaceStorage) -> Self {
|
||||
Self::new_with_strings(name, storage, i18n::strings_for("en"))
|
||||
}
|
||||
|
||||
fn new_with_strings(name: &str, storage: WorkspaceStorage, t: &i18n::SettingsStrings) -> Self {
|
||||
let (sync, storage, detail) = match storage {
|
||||
WorkspaceStorage::Backup => (
|
||||
"Read-only",
|
||||
t.sync_readonly,
|
||||
"Read-only SQLite backup".to_owned(),
|
||||
"This workspace opens from a backup file. Changes are not saved to it.",
|
||||
),
|
||||
// The session has a server, but the shell does not know if a sync completed.
|
||||
WorkspaceStorage::Server => (
|
||||
"Server sync configured",
|
||||
t.sync_server,
|
||||
format!("{name} is configured for server sync"),
|
||||
"Local changes are saved on this device and sync with the configured server when connected.",
|
||||
),
|
||||
WorkspaceStorage::Device => (
|
||||
"Local",
|
||||
t.sync_local,
|
||||
format!("{name} is saved on this device"),
|
||||
"Changes are saved on this device only. They do not sync to AFFiNE Cloud.",
|
||||
),
|
||||
WorkspaceStorage::Memory => (
|
||||
"In memory only",
|
||||
t.sync_memory,
|
||||
format!("{name} is an in-memory session"),
|
||||
"This session is not connected to storage. When it ends, your changes are lost.",
|
||||
),
|
||||
@@ -735,7 +788,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn settings_alignment_pages_and_appearance_controls() {
|
||||
assert_eq!(Page::ALL.len(), 6);
|
||||
assert_eq!(Page::ALL.len(), 7);
|
||||
assert!(
|
||||
Page::ALL
|
||||
.iter()
|
||||
@@ -821,4 +874,486 @@ mod tests {
|
||||
assert_eq!(summary.storage, (row.to_owned(), detail));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_preference_properties_backup_and_language_ui_roundtrip() {
|
||||
let evidence = std::env::var_os("AFFINE_SETTINGS_EVIDENCE").map(std::path::PathBuf::from);
|
||||
if let Some(dir) = &evidence {
|
||||
std::fs::create_dir_all(dir).expect("evidence folder");
|
||||
}
|
||||
|
||||
for (theme_name, theme) in [("light", ThemeMode::Light), ("dark", ThemeMode::Dark)] {
|
||||
let app = Session::new(1280, 800, theme);
|
||||
|
||||
app.click(Page::Preference.id());
|
||||
app.shell(|view, window, cx| {
|
||||
if let Some(first_doc) = view.state.store.workspace_doc_ids().into_iter().next() {
|
||||
view.state.store.set_doc_is_template(&first_doc, true);
|
||||
view.state
|
||||
.navigate_active_pane(DesktopRoute::Doc(first_doc));
|
||||
cx.notify();
|
||||
}
|
||||
let snap = window.frame_snapshot();
|
||||
assert!(
|
||||
snap.elements
|
||||
.contains_key("desktop.settings.preference.workspace_name")
|
||||
);
|
||||
assert!(
|
||||
snap.elements
|
||||
.contains_key("desktop.settings.preference.journal_template")
|
||||
);
|
||||
assert!(
|
||||
snap.elements
|
||||
.contains_key("desktop.settings.preference.page_template_toggle")
|
||||
);
|
||||
assert!(
|
||||
snap.elements
|
||||
.contains_key("desktop.settings.preference.delete_workspace")
|
||||
);
|
||||
});
|
||||
app.click("desktop.settings.preference.page_template_toggle");
|
||||
if let Some(dir) = &evidence {
|
||||
app.capture(&dir.join(format!("preference-{theme_name}.png")));
|
||||
}
|
||||
|
||||
app.click(Page::Properties.id());
|
||||
app.shell(|view, _, cx| {
|
||||
view.state
|
||||
.store
|
||||
.create_workspace_custom_property("Priority", "text");
|
||||
view.state
|
||||
.store
|
||||
.create_workspace_custom_property("Estimate", "number");
|
||||
cx.notify();
|
||||
});
|
||||
app.window.request_frame();
|
||||
app.shell(|_, window, _| {
|
||||
let snap = window.frame_snapshot();
|
||||
assert!(
|
||||
snap.elements
|
||||
.contains_key("desktop.settings.properties.add")
|
||||
);
|
||||
let violations: Vec<_> = ui::audit_frame_snapshot(snap)
|
||||
.into_iter()
|
||||
.filter(|v| v.element_id.starts_with("desktop.settings."))
|
||||
.collect();
|
||||
assert_eq!(violations, Vec::new());
|
||||
});
|
||||
if let Some(dir) = &evidence {
|
||||
app.capture(&dir.join(format!("properties-{theme_name}.png")));
|
||||
}
|
||||
|
||||
app.click(Page::Storage.id());
|
||||
app.click("desktop.settings.storage.export");
|
||||
let exported_path = app.shell(|_, window, _| {
|
||||
let status_text =
|
||||
window.frame_snapshot().elements["desktop.settings.storage.export_status"]
|
||||
.text
|
||||
.as_deref()
|
||||
.unwrap_or("");
|
||||
assert!(status_text.contains(".affine"));
|
||||
let start = status_text.find("Exported ").expect("prefix") + "Exported ".len();
|
||||
let end = status_text.rfind(" (").expect("size suffix");
|
||||
std::path::PathBuf::from(&status_text[start..end])
|
||||
});
|
||||
let meta = std::fs::metadata(&exported_path).expect("exported .affine file on disk");
|
||||
assert!(meta.len() > 0);
|
||||
let _ = std::fs::remove_file(&exported_path);
|
||||
|
||||
let nonce = blocksuite_playground_doc::try_random_client_id().expect("nonce");
|
||||
let uniq_dir = std::env::temp_dir().join(format!("affine-uniq-{nonce:x}"));
|
||||
let p1 = super::storage_page::write_unique_backup_in(&uniq_dir, "Demo.affine", b"a")
|
||||
.expect("write 1");
|
||||
let p2 = super::storage_page::write_unique_backup_in(&uniq_dir, "Demo.affine", b"b")
|
||||
.expect("write 2");
|
||||
let p3 = super::storage_page::write_unique_backup_in(&uniq_dir, "Demo.affine", b"c")
|
||||
.expect("write 3");
|
||||
assert_eq!(p1.file_name().unwrap(), "Demo.affine");
|
||||
assert_eq!(p2.file_name().unwrap(), "Demo-2.affine");
|
||||
assert_eq!(p3.file_name().unwrap(), "Demo-3.affine");
|
||||
assert_eq!(std::fs::read(&p1).unwrap(), b"a");
|
||||
assert_eq!(std::fs::read(&p2).unwrap(), b"b");
|
||||
let _ = std::fs::remove_dir_all(&uniq_dir);
|
||||
|
||||
app.click(Page::Appearance.id());
|
||||
app.click("desktop.settings.appearance.language");
|
||||
app.shell(|_, window, _| {
|
||||
assert!(
|
||||
window
|
||||
.frame_snapshot()
|
||||
.elements
|
||||
.contains_key("desktop.settings.appearance.language.menu")
|
||||
);
|
||||
});
|
||||
if let Some(dir) = &evidence {
|
||||
app.capture(&dir.join(format!("appearance-language-{theme_name}.png")));
|
||||
}
|
||||
app.click("desktop.settings.appearance.language.menu.zh-Hans");
|
||||
app.shell(|view, _, _| assert_eq!(view.state.display_language, "zh-Hans"));
|
||||
app.click("desktop.settings.appearance.language");
|
||||
app.click("desktop.settings.appearance.language.menu.en");
|
||||
app.shell(|view, _, _| assert_eq!(view.state.display_language, "en"));
|
||||
|
||||
// Wheel-scroll language menu to the bottom and click the final entry.
|
||||
app.click("desktop.settings.appearance.language");
|
||||
let menu_center = app
|
||||
.bounds("desktop.settings.appearance.language.menu")
|
||||
.center();
|
||||
app.window
|
||||
.dispatch_input(ui::PlatformInput::MouseMove(ui::MouseMoveEvent {
|
||||
position: menu_center,
|
||||
pressed_button: None,
|
||||
modifiers: ui::Modifiers::default(),
|
||||
}));
|
||||
app.window
|
||||
.dispatch_input(ui::PlatformInput::Scroll(ui::ScrollEvent {
|
||||
position: menu_center,
|
||||
delta: ui::ScrollDelta::Pixels(ui::point(px(0.0), px(-800.0))),
|
||||
modifiers: ui::Modifiers::default(),
|
||||
touch_phase: ui::TouchPhase::Moved,
|
||||
source: ui::ScrollSource::Pointer,
|
||||
}));
|
||||
app.window.request_frame();
|
||||
let last_lang = language::supported_languages()
|
||||
.last()
|
||||
.expect("last language")
|
||||
.code;
|
||||
app.click(&format!(
|
||||
"desktop.settings.appearance.language.menu.{last_lang}"
|
||||
));
|
||||
app.shell(|view, _, _| assert_eq!(view.state.display_language, last_lang));
|
||||
app.click("desktop.settings.appearance.language");
|
||||
app.click("desktop.settings.appearance.language.menu.en");
|
||||
app.shell(|view, _, _| assert_eq!(view.state.display_language, "en"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_switch_refreshes_ui_live_and_web_chrome_hides_backup() {
|
||||
let evidence = std::env::var_os("AFFINE_SETTINGS_EVIDENCE").map(std::path::PathBuf::from);
|
||||
let nonce = blocksuite_playground_doc::try_random_client_id().expect("nonce");
|
||||
let prefs_path = std::env::temp_dir().join(format!("affine-prefs-{nonce:x}.json"));
|
||||
let app = Session::new(1280, 800, ThemeMode::Light);
|
||||
app.shell(|view, _, _| view.state.bind_prefs_path(prefs_path.clone()));
|
||||
app.window.request_frame();
|
||||
|
||||
app.click("desktop.settings.appearance.language");
|
||||
app.click("desktop.settings.appearance.language.menu.zh-Hans");
|
||||
app.shell(|view, window, _| {
|
||||
assert_eq!(view.state.display_language, "zh-Hans");
|
||||
let snap = window.frame_snapshot();
|
||||
assert!(
|
||||
snap.elements[Page::Appearance.id()]
|
||||
.text
|
||||
.as_deref()
|
||||
.unwrap_or("")
|
||||
.contains("外观")
|
||||
);
|
||||
assert!(
|
||||
snap.elements[Page::Preference.id()]
|
||||
.text
|
||||
.as_deref()
|
||||
.unwrap_or("")
|
||||
.contains("偏好设置")
|
||||
);
|
||||
assert!(
|
||||
snap.elements[Page::Storage.id()]
|
||||
.text
|
||||
.as_deref()
|
||||
.unwrap_or("")
|
||||
.contains("存储")
|
||||
);
|
||||
assert!(
|
||||
snap.elements[&Page::Appearance.title_id()]
|
||||
.text
|
||||
.as_deref()
|
||||
.unwrap_or("")
|
||||
.contains("外观设置")
|
||||
);
|
||||
});
|
||||
if let Some(dir) = &evidence {
|
||||
std::fs::create_dir_all(dir).expect("evidence dir");
|
||||
app.capture(&dir.join("appearance-zh-hans-light.png"));
|
||||
}
|
||||
app.click(Page::Preference.id());
|
||||
app.shell(|view, _, _| {
|
||||
assert_eq!(WorkspaceSummary::of(view).sync, "仅内存");
|
||||
});
|
||||
app.click("desktop.settings.preference.delete_workspace");
|
||||
app.shell(|_, window, _| {
|
||||
let desc = window.frame_snapshot().elements["desktop.settings.delete_workspace_confirm.description"]
|
||||
.text
|
||||
.as_deref()
|
||||
.unwrap_or("");
|
||||
assert!(
|
||||
desc.contains("无法撤销"),
|
||||
"delete workspace confirm must localize under zh-Hans, got: {desc}"
|
||||
);
|
||||
});
|
||||
app.click("desktop.settings.delete_workspace_confirm.cancel");
|
||||
if let Some(dir) = &evidence {
|
||||
app.capture(&dir.join("preference-zh-hans-light.png"));
|
||||
}
|
||||
|
||||
// Reloading into a fresh state from the saved JSON retains zh-Hans.
|
||||
let mut reloaded = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02");
|
||||
reloaded.bind_prefs_path(prefs_path.clone());
|
||||
assert_eq!(reloaded.display_language, "zh-Hans");
|
||||
let _ = std::fs::remove_file(&prefs_path);
|
||||
|
||||
// Web chrome hides Full Backup on Storage page.
|
||||
app.shell(|view, _, cx| {
|
||||
view.state.web_chrome = true;
|
||||
cx.notify();
|
||||
});
|
||||
app.window.request_frame();
|
||||
app.click(Page::Storage.id());
|
||||
app.shell(|_, window, _| {
|
||||
assert!(
|
||||
!window
|
||||
.frame_snapshot()
|
||||
.elements
|
||||
.contains_key("desktop.settings.storage.export"),
|
||||
"web chrome must hide Full Backup export button"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_modal_physical_keyboard_typing_layered_escape_and_workspace_delete() {
|
||||
let storage = std::rc::Rc::new(crate::doc_store::LocalUpdates::default());
|
||||
let now = 1_700_000_000_000i64;
|
||||
let (state, sessions) =
|
||||
DesktopAppState::open_local(&storage.0.borrow(), ThemeMode::Light, "2026-12-02", now)
|
||||
.expect("workspace");
|
||||
let (platform, app_handle, handle, window) =
|
||||
crate::editor_host::tests::open_test_shell(state, 1280, 800);
|
||||
let session = Session {
|
||||
app: app_handle,
|
||||
window,
|
||||
handle,
|
||||
};
|
||||
session.shell(|view, _, cx| {
|
||||
view.bind_local_workspaces(sessions, storage.clone(), now, cx);
|
||||
});
|
||||
let doc_before = session.shell(|view, _, _| {
|
||||
view.state
|
||||
.store
|
||||
.get_doc("doc-sync")
|
||||
.expect("doc-sync")
|
||||
.session
|
||||
.encode_update_v1()
|
||||
.expect("update")
|
||||
});
|
||||
|
||||
session.click("desktop.sidebar.settings");
|
||||
session.click(Page::Preference.id());
|
||||
session.click("desktop.settings.preference.workspace_name");
|
||||
session.app.update(|cx| {
|
||||
ui::AnyWindowHandle::from(session.handle)
|
||||
.update(cx, |_, window, cx| {
|
||||
window.dispatch_keystroke(
|
||||
ui::Keystroke {
|
||||
key: "a".into(),
|
||||
key_char: None,
|
||||
modifiers: ui::Modifiers {
|
||||
platform: true,
|
||||
..ui::Modifiers::default()
|
||||
},
|
||||
},
|
||||
cx,
|
||||
);
|
||||
window.dispatch_keystroke(
|
||||
ui::Keystroke::parse("backspace").expect("backspace"),
|
||||
cx,
|
||||
);
|
||||
for ch in ["S", "t", "u", "d", "i", "o"] {
|
||||
window.dispatch_keystroke(
|
||||
ui::Keystroke {
|
||||
key: ch.to_lowercase(),
|
||||
key_char: Some(ch.into()),
|
||||
modifiers: ui::Modifiers::default(),
|
||||
},
|
||||
cx,
|
||||
);
|
||||
}
|
||||
})
|
||||
.expect("dispatch typing");
|
||||
});
|
||||
session.window.request_frame();
|
||||
session.shell(|view, window, _| {
|
||||
let snap = window.frame_snapshot();
|
||||
assert!(
|
||||
snap.elements
|
||||
.contains_key("desktop.settings.preference.save_name"),
|
||||
"dirty workspace name should reveal Save button"
|
||||
);
|
||||
assert_eq!(view.state.modal, Some(DesktopModal::Settings));
|
||||
});
|
||||
session.app.update(|cx| {
|
||||
ui::AnyWindowHandle::from(session.handle)
|
||||
.update(cx, |_, window, cx| {
|
||||
window.dispatch_keystroke(ui::Keystroke::parse("enter").expect("enter"), cx);
|
||||
})
|
||||
.expect("dispatch enter");
|
||||
});
|
||||
session.window.request_frame();
|
||||
platform.run_until_parked();
|
||||
session.shell(|view, _, _| {
|
||||
assert_eq!(view.state.store.active_workspace().name, "Studio");
|
||||
assert_eq!(
|
||||
view.state
|
||||
.store
|
||||
.get_doc("doc-sync")
|
||||
.expect("doc-sync")
|
||||
.session
|
||||
.encode_update_v1()
|
||||
.expect("update"),
|
||||
doc_before
|
||||
);
|
||||
});
|
||||
|
||||
// Pressing Escape right after Enter rename closes modal and preserves "Studio".
|
||||
session.app.update(|cx| {
|
||||
ui::AnyWindowHandle::from(session.handle)
|
||||
.update(cx, |_, window, cx| {
|
||||
window.dispatch_keystroke(ui::Keystroke::parse("escape").expect("escape"), cx);
|
||||
})
|
||||
.expect("dispatch esc after enter rename");
|
||||
});
|
||||
session.window.request_frame();
|
||||
session.shell(|view, _, _| {
|
||||
assert!(view.state.modal.is_none());
|
||||
assert_eq!(view.state.store.active_workspace().name, "Studio");
|
||||
});
|
||||
|
||||
// Reopen Settings, rename via Save button, then press Escape immediately.
|
||||
session.click("desktop.sidebar.settings");
|
||||
session.click(Page::Preference.id());
|
||||
session.click("desktop.settings.preference.workspace_name");
|
||||
session.app.update(|cx| {
|
||||
ui::AnyWindowHandle::from(session.handle)
|
||||
.update(cx, |_, window, cx| {
|
||||
window.dispatch_keystroke(
|
||||
ui::Keystroke {
|
||||
key: "a".into(),
|
||||
key_char: None,
|
||||
modifiers: ui::Modifiers {
|
||||
platform: true,
|
||||
..ui::Modifiers::default()
|
||||
},
|
||||
},
|
||||
cx,
|
||||
);
|
||||
window.dispatch_keystroke(
|
||||
ui::Keystroke::parse("backspace").expect("backspace"),
|
||||
cx,
|
||||
);
|
||||
for ch in ["A", "t", "e", "l", "i", "e", "r"] {
|
||||
window.dispatch_keystroke(
|
||||
ui::Keystroke {
|
||||
key: ch.to_lowercase(),
|
||||
key_char: Some(ch.into()),
|
||||
modifiers: ui::Modifiers::default(),
|
||||
},
|
||||
cx,
|
||||
);
|
||||
}
|
||||
})
|
||||
.expect("dispatch typing save btn");
|
||||
});
|
||||
session.window.request_frame();
|
||||
session.click("desktop.settings.preference.save_name");
|
||||
session.app.update(|cx| {
|
||||
ui::AnyWindowHandle::from(session.handle)
|
||||
.update(cx, |_, window, cx| {
|
||||
window.dispatch_keystroke(ui::Keystroke::parse("escape").expect("escape"), cx);
|
||||
})
|
||||
.expect("dispatch esc after save click");
|
||||
});
|
||||
session.window.request_frame();
|
||||
session.shell(|view, _, _| {
|
||||
assert!(view.state.modal.is_none());
|
||||
assert_eq!(view.state.store.active_workspace().name, "Atelier");
|
||||
});
|
||||
session.click("desktop.sidebar.settings");
|
||||
session.click(Page::Preference.id());
|
||||
|
||||
session.click("desktop.settings.preference.delete_workspace");
|
||||
session.shell(|_, window, _| {
|
||||
assert!(
|
||||
window
|
||||
.frame_snapshot()
|
||||
.elements
|
||||
.contains_key("desktop.settings.delete_workspace_confirm")
|
||||
);
|
||||
});
|
||||
session.app.update(|cx| {
|
||||
ui::AnyWindowHandle::from(session.handle)
|
||||
.update(cx, |_, window, cx| {
|
||||
window.dispatch_keystroke(ui::Keystroke::parse("escape").expect("escape"), cx);
|
||||
})
|
||||
.expect("dispatch esc 1");
|
||||
});
|
||||
session.window.request_frame();
|
||||
session.shell(|view, window, _| {
|
||||
assert!(
|
||||
!window
|
||||
.frame_snapshot()
|
||||
.elements
|
||||
.contains_key("desktop.settings.delete_workspace_confirm")
|
||||
);
|
||||
assert_eq!(view.state.modal, Some(DesktopModal::Settings));
|
||||
});
|
||||
session.app.update(|cx| {
|
||||
ui::AnyWindowHandle::from(session.handle)
|
||||
.update(cx, |_, window, cx| {
|
||||
window.dispatch_keystroke(ui::Keystroke::parse("escape").expect("escape"), cx);
|
||||
})
|
||||
.expect("dispatch esc 2");
|
||||
});
|
||||
session.window.request_frame();
|
||||
session.shell(|view, _, _| {
|
||||
assert!(view.state.modal.is_none());
|
||||
});
|
||||
|
||||
let kept_id = session.shell(|view, _, _| view.state.store.active_workspace().id.clone());
|
||||
let extra_bucket = crate::doc_store::WorkspaceBucket::empty_for_workspace("ws-custom-del")
|
||||
.expect("bucket");
|
||||
session.shell(|view, _, cx| {
|
||||
view.state
|
||||
.store
|
||||
.workspaces
|
||||
.push(crate::doc_store::DesktopWorkspace {
|
||||
id: "ws-custom-del".into(),
|
||||
name: "Disposable".into(),
|
||||
kind: crate::doc_store::WorkspaceKind::Local,
|
||||
synced: true,
|
||||
});
|
||||
let next_idx = view.state.store.workspaces.len() - 1;
|
||||
view.state
|
||||
.store
|
||||
.workspace_buckets
|
||||
.insert(next_idx, extra_bucket);
|
||||
view.state.switch_workspace(next_idx);
|
||||
view.state.open_settings();
|
||||
cx.notify();
|
||||
});
|
||||
session.window.request_frame();
|
||||
session.click(Page::Preference.id());
|
||||
session.click("desktop.settings.preference.delete_workspace");
|
||||
session.click("desktop.settings.delete_workspace_confirm.confirm");
|
||||
platform.run_until_parked();
|
||||
session.shell(|view, _, _| {
|
||||
assert_eq!(view.state.store.active_workspace().id, kept_id);
|
||||
assert!(
|
||||
view.state
|
||||
.store
|
||||
.workspaces
|
||||
.iter()
|
||||
.all(|ws| ws.id != "ws-custom-del")
|
||||
);
|
||||
});
|
||||
assert!(!storage.0.borrow().contains_key("ws-custom-del"));
|
||||
}
|
||||
}
|
||||
@@ -9,11 +9,9 @@ use ui::{
|
||||
use ui_tokens::icons;
|
||||
|
||||
use super::{
|
||||
MODAL_ID, SettingsModal, WorkspaceSummary,
|
||||
controls::{
|
||||
FocusStops, control_row, control_section, description_text, picker, readonly_select,
|
||||
section, value_row,
|
||||
},
|
||||
MODAL_ID, SettingsModal,
|
||||
controls::{FocusStops, control_row, control_section, description_text, picker, section},
|
||||
i18n::{SettingsStrings, strings_for},
|
||||
new_doc_default_mode,
|
||||
};
|
||||
use crate::{DesktopFlexExt, DesktopPalette, state::ThemePreference};
|
||||
@@ -25,21 +23,23 @@ pub(super) enum Page {
|
||||
Editor,
|
||||
Shortcuts,
|
||||
Preference,
|
||||
Properties,
|
||||
Storage,
|
||||
About,
|
||||
}
|
||||
|
||||
impl Page {
|
||||
pub(super) const ALL: [Self; 6] = [
|
||||
pub(super) const ALL: [Self; 7] = [
|
||||
Self::Appearance,
|
||||
Self::Editor,
|
||||
Self::Shortcuts,
|
||||
Self::Preference,
|
||||
Self::Properties,
|
||||
Self::Storage,
|
||||
Self::About,
|
||||
];
|
||||
pub(super) const GENERAL: [Self; 3] = [Self::Appearance, Self::Editor, Self::Shortcuts];
|
||||
pub(super) const WORKSPACE: [Self; 2] = [Self::Preference, Self::Storage];
|
||||
pub(super) const WORKSPACE: [Self; 3] = [Self::Preference, Self::Properties, Self::Storage];
|
||||
|
||||
pub(super) fn labels(self) -> (&'static str, &'static str) {
|
||||
match self {
|
||||
@@ -47,6 +47,7 @@ impl Page {
|
||||
Self::Editor => ("Editor", "desktop.settings.editor"),
|
||||
Self::Shortcuts => ("Shortcuts", "desktop.settings.shortcuts"),
|
||||
Self::Preference => ("Preference", "desktop.settings.preference"),
|
||||
Self::Properties => ("Properties", "desktop.settings.properties"),
|
||||
Self::Storage => ("Storage", "desktop.settings.storage"),
|
||||
Self::About => ("About", "desktop.settings.about"),
|
||||
}
|
||||
@@ -56,6 +57,18 @@ impl Page {
|
||||
self.labels().1
|
||||
}
|
||||
|
||||
pub(super) fn nav_label(self, t: &SettingsStrings) -> &'static str {
|
||||
match self {
|
||||
Self::Appearance => t.nav_appearance,
|
||||
Self::Editor => t.nav_editor,
|
||||
Self::Shortcuts => t.nav_shortcuts,
|
||||
Self::Preference => t.nav_preference,
|
||||
Self::Properties => t.nav_properties,
|
||||
Self::Storage => t.nav_storage,
|
||||
Self::About => t.nav_about,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn title_id(self) -> String {
|
||||
format!("{}.title", self.id())
|
||||
@@ -67,6 +80,7 @@ impl Page {
|
||||
Self::Editor => &icons::PEN,
|
||||
Self::Shortcuts => &icons::KEYBOARD,
|
||||
Self::Preference => &icons::PAGE,
|
||||
Self::Properties => &icons::TAG,
|
||||
Self::Storage => &icons::ATTACHMENT,
|
||||
Self::About => &icons::INFORMATION,
|
||||
}
|
||||
@@ -84,19 +98,12 @@ impl SettingsModal {
|
||||
) -> impl IntoElement + use<> {
|
||||
use DocMode::{Edgeless, Page as PageMode};
|
||||
let palette = self.palette;
|
||||
let values = |title, rows: &[(&'static str, &str)]| {
|
||||
section(
|
||||
title,
|
||||
rows.iter()
|
||||
.map(|&(label, value)| value_row(label, value.to_owned(), palette)),
|
||||
palette,
|
||||
)
|
||||
};
|
||||
let t = strings_for(&self.shell.read(app).state().display_language);
|
||||
let (title, description, sections) = match page {
|
||||
Page::Appearance => (
|
||||
"Appearance settings",
|
||||
"Customize your AFFiNE appearance",
|
||||
self.appearance(stacked, stops, window, app),
|
||||
t.appearance_title,
|
||||
t.appearance_desc,
|
||||
self.appearance(t, stacked, stops, window, app),
|
||||
),
|
||||
Page::Editor => {
|
||||
let default_mode = new_doc_default_mode(self.shell.read(app).state());
|
||||
@@ -104,23 +111,23 @@ impl SettingsModal {
|
||||
let font_size = self.shell.read(app).state().editor_font.size();
|
||||
let full_width = self.shell.read(app).state().full_width_layout();
|
||||
(
|
||||
"Editor settings",
|
||||
"Preferences for creating and editing documents",
|
||||
t.editor_title,
|
||||
t.editor_desc,
|
||||
vec![
|
||||
section(
|
||||
Some("General"),
|
||||
Some(t.editor_general_section),
|
||||
[
|
||||
control_row(
|
||||
"New Doc Default Mode",
|
||||
"Choose how new documents open.",
|
||||
t.new_doc_default_mode,
|
||||
t.new_doc_default_mode_desc,
|
||||
picker(
|
||||
&self.shell,
|
||||
palette,
|
||||
[
|
||||
("desktop.settings.mode.page", "Page", PageMode),
|
||||
("desktop.settings.mode.page", t.mode_page, PageMode),
|
||||
(
|
||||
"desktop.settings.mode.edgeless",
|
||||
"Edgeless",
|
||||
t.mode_edgeless,
|
||||
Edgeless,
|
||||
),
|
||||
],
|
||||
@@ -134,8 +141,8 @@ impl SettingsModal {
|
||||
palette,
|
||||
),
|
||||
control_row(
|
||||
"Font Style",
|
||||
"Choose the typeface for document text.",
|
||||
t.font_style,
|
||||
t.font_style_desc,
|
||||
picker(
|
||||
&self.shell,
|
||||
palette,
|
||||
@@ -154,8 +161,8 @@ impl SettingsModal {
|
||||
palette,
|
||||
),
|
||||
control_row(
|
||||
"Font Size",
|
||||
"Choose the base size for document text.",
|
||||
t.font_size,
|
||||
t.font_size_desc,
|
||||
super::font_size::slider(
|
||||
&self.shell,
|
||||
font_size,
|
||||
@@ -171,15 +178,19 @@ impl SettingsModal {
|
||||
palette,
|
||||
),
|
||||
control_section(
|
||||
"Page",
|
||||
"Default page width",
|
||||
"Choose the default width for pages.",
|
||||
t.page_section,
|
||||
t.default_page_width,
|
||||
t.default_page_width_desc,
|
||||
picker(
|
||||
&self.shell,
|
||||
palette,
|
||||
[
|
||||
("desktop.settings.page_width.standard", "Standard", false),
|
||||
("desktop.settings.page_width.full", "Full width", true),
|
||||
(
|
||||
"desktop.settings.page_width.standard",
|
||||
t.page_width_standard,
|
||||
false,
|
||||
),
|
||||
("desktop.settings.page_width.full", t.page_width_full, true),
|
||||
],
|
||||
full_width,
|
||||
crate::DesktopAppState::set_full_width_layout,
|
||||
@@ -194,48 +205,35 @@ impl SettingsModal {
|
||||
)
|
||||
}
|
||||
Page::Shortcuts => (
|
||||
"Keyboard shortcuts",
|
||||
"Shortcuts for the workbench and editor",
|
||||
shortcuts(app.platform_info().is_mac(), palette),
|
||||
t.shortcuts_title,
|
||||
t.shortcuts_desc,
|
||||
shortcuts(app.platform_info().is_mac(), t, palette),
|
||||
),
|
||||
Page::Preference => (
|
||||
t.preference_title,
|
||||
t.preference_desc,
|
||||
self.workspace_preference_sections(stacked, stops, window, app),
|
||||
),
|
||||
Page::Properties => (
|
||||
t.properties_title,
|
||||
t.properties_desc,
|
||||
self.workspace_properties_sections(stops, window, app),
|
||||
),
|
||||
Page::Storage => (
|
||||
t.storage_title,
|
||||
t.storage_desc,
|
||||
self.workspace_storage_sections(stacked, stops, window, app),
|
||||
),
|
||||
Page::Preference => {
|
||||
let workspace = WorkspaceSummary::of(self.shell.read(app));
|
||||
(
|
||||
"Workspace preference",
|
||||
"Your current workspace and its connection",
|
||||
vec![values(
|
||||
Some("Workspace"),
|
||||
&[
|
||||
("Workspace name", &workspace.name),
|
||||
("Sync status", workspace.sync),
|
||||
],
|
||||
)],
|
||||
)
|
||||
}
|
||||
Page::Storage => {
|
||||
let (storage, detail) = WorkspaceSummary::of(self.shell.read(app)).storage;
|
||||
let panel = setting_row(storage.clone(), detail, palette)
|
||||
.snapshot(STORAGE_PANEL, Some(MODAL_ID))
|
||||
.snapshot_text(format!("{storage}\n{detail}"))
|
||||
.p(px(10.0))
|
||||
.rounded(px(8.0))
|
||||
.bg(palette.bg_surface);
|
||||
(
|
||||
"Storage",
|
||||
"You can view current workspace's storage and files here.",
|
||||
vec![section(None, [panel], palette)],
|
||||
)
|
||||
}
|
||||
Page::About => {
|
||||
let versions = div().flex().flex_col().gap(px(25.0)).children([
|
||||
setting_row("AFFiNE", APP_VERSION, palette),
|
||||
setting_row("Editor version", APP_VERSION, palette),
|
||||
setting_row("Desktop build", env!("CARGO_PKG_VERSION"), palette),
|
||||
setting_row(t.editor_version, APP_VERSION, palette),
|
||||
setting_row(t.desktop_build, env!("CARGO_PKG_VERSION"), palette),
|
||||
]);
|
||||
(
|
||||
"About AFFiNE",
|
||||
"Information about AFFiNE",
|
||||
vec![section(Some("Version"), [versions], palette)],
|
||||
t.about_title,
|
||||
t.about_desc,
|
||||
vec![section(Some(t.version_section), [versions], palette)],
|
||||
)
|
||||
}
|
||||
};
|
||||
@@ -243,6 +241,7 @@ impl SettingsModal {
|
||||
content.style().max_size.width = Some(px(560.0).into());
|
||||
let title = div()
|
||||
.snapshot(ui::snap_id!("{}.title", page.id()), Some(MODAL_ID))
|
||||
.snapshot_text(title)
|
||||
.text_size(px(16.0))
|
||||
.line_height(px(24.0))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
@@ -265,6 +264,7 @@ impl SettingsModal {
|
||||
|
||||
fn appearance(
|
||||
&self,
|
||||
t: &SettingsStrings,
|
||||
stacked: bool,
|
||||
stops: &mut FocusStops,
|
||||
window: &mut Window,
|
||||
@@ -272,10 +272,11 @@ impl SettingsModal {
|
||||
) -> Vec<Div> {
|
||||
use ThemePreference::{Dark, Light, System};
|
||||
let palette = self.palette;
|
||||
let mode = self.shell.read(app).state().theme;
|
||||
let scheme = [
|
||||
("desktop.settings.theme.light", "Light", Light),
|
||||
("desktop.settings.theme.dark", "Dark", Dark),
|
||||
("desktop.settings.theme.system", "System", System),
|
||||
("desktop.settings.theme.light", t.theme_light, Light),
|
||||
("desktop.settings.theme.dark", t.theme_dark, Dark),
|
||||
("desktop.settings.theme.system", t.theme_system, System),
|
||||
];
|
||||
let scheme = picker(
|
||||
&self.shell,
|
||||
@@ -292,32 +293,29 @@ impl SettingsModal {
|
||||
.flex_col()
|
||||
.gap(px(20.0))
|
||||
.child(control_row(
|
||||
"Color Scheme",
|
||||
"Choose the color scheme used by AFFiNE.",
|
||||
t.color_scheme,
|
||||
t.color_scheme_desc,
|
||||
scheme,
|
||||
stacked,
|
||||
palette,
|
||||
))
|
||||
.child(control_row(
|
||||
"Display language",
|
||||
"Select the language for the interface.",
|
||||
readonly_select("desktop.settings.appearance.language", "English", palette),
|
||||
t.display_language,
|
||||
t.display_language_desc,
|
||||
super::language::selector(&self.shell, palette, mode, stops, window, app),
|
||||
stacked,
|
||||
palette,
|
||||
));
|
||||
vec![section(Some("Theme"), [rows], palette)]
|
||||
vec![section(Some(t.theme_section), [rows], palette)]
|
||||
}
|
||||
}
|
||||
|
||||
/// The storage panel of the `Storage` page.
|
||||
const STORAGE_PANEL: &str = "desktop.settings.storage.panel";
|
||||
|
||||
/// The web `0.27.5` build that this shell matches. The web app reports its package version as
|
||||
/// both the app version and the editor version.
|
||||
const APP_VERSION: &str = "0.27.5";
|
||||
|
||||
/// A web `SettingRow` without a control: a 14px semibold name over a 12px secondary description.
|
||||
fn setting_row(
|
||||
pub(super) fn setting_row(
|
||||
name: impl Into<SharedString>,
|
||||
desc: impl Into<SharedString>,
|
||||
palette: DesktopPalette,
|
||||
@@ -336,7 +334,7 @@ fn setting_row(
|
||||
)
|
||||
}
|
||||
|
||||
fn shortcuts(mac: bool, palette: DesktopPalette) -> Vec<Div> {
|
||||
fn shortcuts(mac: bool, t: &SettingsStrings, palette: DesktopPalette) -> Vec<Div> {
|
||||
let (command, shift, alt) = if mac {
|
||||
("⌘", "⇧", "⌥")
|
||||
} else {
|
||||
@@ -361,12 +359,12 @@ fn shortcuts(mac: bool, palette: DesktopPalette) -> Vec<Div> {
|
||||
};
|
||||
vec![
|
||||
section(
|
||||
Some("General"),
|
||||
[shortcut("Quick Search", format!("{command}K"))],
|
||||
Some(t.editor_general_section),
|
||||
[shortcut(t.shortcut_quick_search, format!("{command}K"))],
|
||||
palette,
|
||||
),
|
||||
section(
|
||||
Some("Editor"),
|
||||
Some(t.shortcuts_editor_section),
|
||||
[
|
||||
shortcut("Undo", format!("{command}Z")),
|
||||
shortcut("Redo", format!("{command}{shift}Z")),
|
||||
|
||||
@@ -0,0 +1,498 @@
|
||||
//! Workspace properties management page for `SettingsModal`.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use ui::{
|
||||
App, Div, ElementId, Entity, FontWeight, InteractiveElement, MouseButton, ParentElement,
|
||||
SharedString, StatefulInteractiveElement, Styled, Window, div, px, svg,
|
||||
};
|
||||
use ui_tokens::icons::{self, IconDef};
|
||||
|
||||
use super::{
|
||||
MODAL_ID, SettingsModal,
|
||||
controls::{FocusStops, description_text, focus_stop, focus_stop_named, section},
|
||||
i18n::{SettingsStrings, strings_for},
|
||||
property_row::small_action_button,
|
||||
text_input::keyed_input,
|
||||
};
|
||||
use crate::{DesktopFlexExt, DesktopPalette};
|
||||
|
||||
const ADD_PROPERTY_ID: &str = "desktop.settings.properties.add";
|
||||
const NEW_NAME_ID: &str = "desktop.settings.properties.new_name";
|
||||
const CREATE_BTN_ID: &str = "desktop.settings.properties.create";
|
||||
const CREATE_CANCEL_ID: &str = "desktop.settings.properties.create_cancel";
|
||||
|
||||
const KINDS: [(&str, &str, IconDef); 4] = [
|
||||
("text", "Text", icons::TEXT),
|
||||
("number", "Number", icons::NUMBER),
|
||||
("checkbox", "Checkbox", icons::CHECKBOX_CHECKED_LINEAR),
|
||||
("date", "Date", icons::TODAY),
|
||||
];
|
||||
|
||||
pub(super) const VISIBILITIES: [(&str, &str); 3] = [
|
||||
("always-show", "Show"),
|
||||
("hide-when-empty", "Collapse"),
|
||||
("always-hide", "Hide"),
|
||||
];
|
||||
|
||||
const SYSTEM_PROPERTIES: [(&str, &str, IconDef); 6] = [
|
||||
("Tags", "Multi-select", icons::TAG),
|
||||
("Created", "Date", icons::TODAY),
|
||||
("Updated", "Date", icons::DATE_TIME),
|
||||
("Page width", "Option", icons::PAGE_WIDTH),
|
||||
("Journal", "Date", icons::TODAY),
|
||||
("Template", "Toggle", icons::PAGE),
|
||||
];
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct PropertiesPageState {
|
||||
creating: bool,
|
||||
new_kind: &'static str,
|
||||
pub(super) renaming_id: Option<String>,
|
||||
pub(super) confirm_delete_id: Option<String>,
|
||||
}
|
||||
|
||||
impl PropertiesPageState {
|
||||
fn keyed(window: &mut Window, app: &mut App) -> Entity<Self> {
|
||||
window.use_keyed_state("desktop.settings.properties.state", app, |_, _| Self {
|
||||
creating: false,
|
||||
new_kind: "text",
|
||||
renaming_id: None,
|
||||
confirm_delete_id: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn kind_meta(kind: &str) -> (&'static str, IconDef) {
|
||||
KINDS
|
||||
.iter()
|
||||
.find(|(k, _, _)| *k == kind)
|
||||
.map_or(("Text", icons::TEXT), |(_, label, icon)| (*label, *icon))
|
||||
}
|
||||
|
||||
impl SettingsModal {
|
||||
pub(super) fn workspace_properties_sections(
|
||||
&self,
|
||||
stops: &mut FocusStops,
|
||||
window: &mut Window,
|
||||
app: &mut App,
|
||||
) -> Vec<Div> {
|
||||
let palette = self.palette;
|
||||
let t = strings_for(&self.shell.read(app).state().display_language);
|
||||
let page_state = PropertiesPageState::keyed(window, app);
|
||||
let snapshot = page_state.read(app).clone();
|
||||
|
||||
let (readonly, custom_props) = self.shell.update(app, |view, _| {
|
||||
let readonly = view.state.store.is_readonly_sqlite();
|
||||
let props: Vec<_> = view
|
||||
.state
|
||||
.store
|
||||
.workspace_custom_properties()
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
let count = view.state.store.workspace_property_doc_count(&row.id);
|
||||
(row, count)
|
||||
})
|
||||
.collect();
|
||||
(readonly, props)
|
||||
});
|
||||
|
||||
let add_bar = self.render_add_property_bar(
|
||||
&page_state,
|
||||
&snapshot,
|
||||
readonly,
|
||||
t,
|
||||
palette,
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
);
|
||||
|
||||
let system_rows = SYSTEM_PROPERTIES.map(|(name, kind_label, icon)| {
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_between()
|
||||
.gap(px(10.0))
|
||||
.px(px(8.0))
|
||||
.h(px(34.0))
|
||||
.rounded(px(6.0))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(8.0))
|
||||
.min_w_0()
|
||||
.child(
|
||||
svg()
|
||||
.data(icon.svg.as_bytes())
|
||||
.size(px(16.0))
|
||||
.flex_shrink(0.0)
|
||||
.text_color(palette.text_secondary),
|
||||
)
|
||||
.child(div().min_w_0().truncate().child(name)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(8.0))
|
||||
.flex_shrink(0.0)
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(12.0))
|
||||
.text_color(palette.text_secondary)
|
||||
.child(kind_label),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.px(px(6.0))
|
||||
.py(px(1.0))
|
||||
.rounded(px(4.0))
|
||||
.bg(palette.bg_pill)
|
||||
.text_size(px(11.0))
|
||||
.text_color(palette.text_muted)
|
||||
.child(t.system_badge),
|
||||
),
|
||||
)
|
||||
});
|
||||
let system_section = section(Some(t.system_properties_section), system_rows, palette);
|
||||
|
||||
let mut custom_rows = Vec::new();
|
||||
if custom_props.is_empty() {
|
||||
custom_rows.push(description_text(t.no_custom_properties, palette));
|
||||
} else {
|
||||
for (prop, doc_count) in custom_props {
|
||||
custom_rows.push(self.render_custom_property_row(
|
||||
&prop,
|
||||
doc_count,
|
||||
&page_state,
|
||||
&snapshot,
|
||||
readonly,
|
||||
palette,
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
));
|
||||
}
|
||||
}
|
||||
let custom_section = section(Some(t.custom_properties_section), custom_rows, palette);
|
||||
|
||||
vec![
|
||||
div().flex().flex_col().gap(px(12.0)).child(add_bar),
|
||||
system_section,
|
||||
custom_section,
|
||||
]
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn render_add_property_bar(
|
||||
&self,
|
||||
page_state: &Entity<PropertiesPageState>,
|
||||
snapshot: &PropertiesPageState,
|
||||
readonly: bool,
|
||||
t: &SettingsStrings,
|
||||
palette: DesktopPalette,
|
||||
stops: &mut FocusStops,
|
||||
window: &mut Window,
|
||||
app: &mut App,
|
||||
) -> Div {
|
||||
let mut container = div().flex().flex_col().gap(px(12.0));
|
||||
let add_btn = if readonly {
|
||||
div()
|
||||
.id(ADD_PROPERTY_ID)
|
||||
.snapshot(ADD_PROPERTY_ID, Some(MODAL_ID))
|
||||
.opacity(0.45)
|
||||
.cursor(ui::CursorStyle::Arrow)
|
||||
} else {
|
||||
let stop = focus_stop(ADD_PROPERTY_ID, stops, window, app);
|
||||
let focused = stop.handle.is_focused(window);
|
||||
let keyboard = window.last_input_was_keyboard();
|
||||
let click_focus = stop.handle.clone();
|
||||
let click_state = page_state.clone();
|
||||
let key_state = page_state.clone();
|
||||
let key_stop = stop.clone();
|
||||
div()
|
||||
.id(ADD_PROPERTY_ID)
|
||||
.snapshot(ADD_PROPERTY_ID, Some(MODAL_ID))
|
||||
.snapshot_focused(focused)
|
||||
.track_focus(&stop.handle)
|
||||
.relative()
|
||||
.border_1()
|
||||
.border_color(if focused && keyboard {
|
||||
palette.text_primary
|
||||
} else {
|
||||
ui::transparent_black()
|
||||
})
|
||||
.hover(move |s| s.bg(palette.accent.opacity(0.88)))
|
||||
.cursor_pointer()
|
||||
.on_mouse_down(MouseButton::Left, move |_, window, app| {
|
||||
window.focus(&click_focus, app);
|
||||
})
|
||||
.on_click(move |_, _, app| {
|
||||
click_state.update(app, |state, cx| {
|
||||
state.creating = !state.creating;
|
||||
if state.creating {
|
||||
state.new_kind = "text";
|
||||
}
|
||||
cx.notify();
|
||||
});
|
||||
})
|
||||
.on_key_down(move |event, window, app| {
|
||||
if matches!(event.keystroke.key.as_str(), "enter" | "space")
|
||||
&& !event.keystroke.modifiers.modified()
|
||||
{
|
||||
key_stop.reveal(window);
|
||||
key_state.update(app, |state, cx| {
|
||||
state.creating = !state.creating;
|
||||
if state.creating {
|
||||
state.new_kind = "text";
|
||||
}
|
||||
cx.notify();
|
||||
});
|
||||
window.prevent_default();
|
||||
app.stop_propagation();
|
||||
}
|
||||
})
|
||||
.child(stop.probe())
|
||||
}
|
||||
.h(px(32.0))
|
||||
.px(px(12.0))
|
||||
.rounded(px(8.0))
|
||||
.bg(palette.accent)
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(6.0))
|
||||
.text_size(px(12.0))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(ui::white())
|
||||
.child(
|
||||
svg()
|
||||
.data(icons::PLUS.svg.as_bytes())
|
||||
.size(px(14.0))
|
||||
.text_color(ui::white()),
|
||||
)
|
||||
.child(t.add_property);
|
||||
|
||||
container = container.child(div().flex().items_center().child(add_btn));
|
||||
|
||||
if !readonly && snapshot.creating {
|
||||
let mut kind_pills = div().flex().flex_wrap().items_center().gap(px(6.0));
|
||||
for (kind, label, icon) in KINDS {
|
||||
let selected = snapshot.new_kind == kind;
|
||||
let id_str = format!("desktop.settings.properties.kind.{kind}");
|
||||
let snap_id = ui::snap_id!("desktop.settings.properties.kind.{kind}");
|
||||
let stop = focus_stop_named(
|
||||
ElementId::Name(SharedString::from(id_str.clone())),
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
);
|
||||
let focused = stop.handle.is_focused(window);
|
||||
let keyboard = window.last_input_was_keyboard();
|
||||
let click_focus = stop.handle.clone();
|
||||
let click_state = page_state.clone();
|
||||
let key_state = page_state.clone();
|
||||
let key_stop = stop.clone();
|
||||
kind_pills = kind_pills.child(
|
||||
div()
|
||||
.id(SharedString::from(id_str))
|
||||
.snapshot(snap_id, Some(MODAL_ID))
|
||||
.snapshot_focused(focused)
|
||||
.track_focus(&stop.handle)
|
||||
.relative()
|
||||
.h(px(28.0))
|
||||
.px(px(10.0))
|
||||
.rounded(px(6.0))
|
||||
.bg(if selected {
|
||||
palette.accent_soft
|
||||
} else {
|
||||
palette.bg_elevated
|
||||
})
|
||||
.border_1()
|
||||
.border_color(if focused && keyboard {
|
||||
palette.accent
|
||||
} else if selected {
|
||||
palette.accent
|
||||
} else {
|
||||
palette.border
|
||||
})
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(6.0))
|
||||
.cursor_pointer()
|
||||
.text_size(px(12.0))
|
||||
.text_color(if selected {
|
||||
palette.accent
|
||||
} else {
|
||||
palette.text_primary
|
||||
})
|
||||
.on_mouse_down(MouseButton::Left, move |_, window, app| {
|
||||
window.focus(&click_focus, app);
|
||||
})
|
||||
.on_click(move |_, _, app| {
|
||||
click_state.update(app, |state, cx| {
|
||||
state.new_kind = kind;
|
||||
cx.notify();
|
||||
});
|
||||
})
|
||||
.on_key_down(move |event, window, app| {
|
||||
if matches!(event.keystroke.key.as_str(), "enter" | "space")
|
||||
&& !event.keystroke.modifiers.modified()
|
||||
{
|
||||
key_stop.reveal(window);
|
||||
key_state.update(app, |state, cx| {
|
||||
state.new_kind = kind;
|
||||
cx.notify();
|
||||
});
|
||||
window.prevent_default();
|
||||
app.stop_propagation();
|
||||
}
|
||||
})
|
||||
.child(stop.probe())
|
||||
.child(svg().data(icon.svg.as_bytes()).size(px(14.0)).text_color(
|
||||
if selected {
|
||||
palette.accent
|
||||
} else {
|
||||
palette.text_secondary
|
||||
},
|
||||
))
|
||||
.child(label),
|
||||
);
|
||||
}
|
||||
|
||||
let kind = snapshot.new_kind;
|
||||
let name_input = keyed_input(
|
||||
SharedString::new_static(NEW_NAME_ID),
|
||||
ui::snap_id!("{NEW_NAME_ID}"),
|
||||
"",
|
||||
t.property_name_placeholder,
|
||||
false,
|
||||
palette,
|
||||
None,
|
||||
None,
|
||||
Some(Rc::new({
|
||||
let cancel_state = page_state.clone();
|
||||
move |_, app| {
|
||||
cancel_state.update(app, |state, cx| {
|
||||
state.creating = false;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
})),
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
);
|
||||
|
||||
let create_action: Rc<dyn Fn(&mut Window, &mut App)> = {
|
||||
let shell = self.shell.downgrade();
|
||||
let page_state = page_state.clone();
|
||||
let input = name_input.clone();
|
||||
Rc::new(move |window, app| {
|
||||
let text = input.read(app).text().trim().to_owned();
|
||||
if text.is_empty() {
|
||||
return;
|
||||
}
|
||||
let created = shell
|
||||
.update(app, |view, cx| {
|
||||
let id = view
|
||||
.state
|
||||
.store
|
||||
.create_workspace_custom_property(&text, kind);
|
||||
if id.is_some() {
|
||||
view.flush_persistence();
|
||||
cx.notify();
|
||||
}
|
||||
id.is_some()
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if created {
|
||||
input.update(app, |field, cx| field.set_text("", window, cx));
|
||||
page_state.update(app, |state, cx| {
|
||||
state.creating = false;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
let enter_create = create_action.clone();
|
||||
name_input.update(app, |field, _| {
|
||||
field.sync(
|
||||
"",
|
||||
false,
|
||||
palette,
|
||||
None,
|
||||
Some(Rc::new(move |_, window, app| {
|
||||
enter_create(window, app);
|
||||
})),
|
||||
Some(Rc::new({
|
||||
let page_state = page_state.clone();
|
||||
move |_, app| {
|
||||
page_state.update(app, |state, cx| {
|
||||
state.creating = false;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
})),
|
||||
window,
|
||||
);
|
||||
});
|
||||
|
||||
let create_btn = small_action_button(
|
||||
CREATE_BTN_ID,
|
||||
t.create,
|
||||
true,
|
||||
palette,
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
create_action,
|
||||
);
|
||||
let cancel_btn = small_action_button(
|
||||
CREATE_CANCEL_ID,
|
||||
t.cancel,
|
||||
false,
|
||||
palette,
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
Rc::new({
|
||||
let page_state = page_state.clone();
|
||||
let input = name_input.clone();
|
||||
move |window, app| {
|
||||
input.update(app, |field, cx| field.set_text("", window, cx));
|
||||
page_state.update(app, |state, cx| {
|
||||
state.creating = false;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
let mut form_row = div().flex().flex_wrap().items_center().gap(px(8.0));
|
||||
let mut input_box = div().w(px(220.0)).min_w_0();
|
||||
input_box.style().max_size.width = Some(ui::relative(1.0).into());
|
||||
form_row = form_row
|
||||
.child(input_box.child(name_input))
|
||||
.child(create_btn)
|
||||
.child(cancel_btn);
|
||||
|
||||
container = container.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(10.0))
|
||||
.p(px(12.0))
|
||||
.rounded(px(8.0))
|
||||
.bg(palette.bg_surface)
|
||||
.border_1()
|
||||
.border_color(palette.border)
|
||||
.child(kind_pills)
|
||||
.child(form_row),
|
||||
);
|
||||
}
|
||||
container
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,617 @@
|
||||
//! Custom property row and compact button helpers for `Settings -> Workspace -> Properties`.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use ui::{
|
||||
App, Div, ElementId, Entity, FontWeight, InteractiveElement, MouseButton, ParentElement,
|
||||
SharedString, StatefulInteractiveElement, Styled, Window, div, px, svg,
|
||||
};
|
||||
use ui_tokens::icons::{self, IconDef};
|
||||
|
||||
use super::{
|
||||
MODAL_ID, SettingsModal,
|
||||
controls::{FocusStops, focus_stop_named},
|
||||
i18n::strings_for,
|
||||
properties_page::{PropertiesPageState, VISIBILITIES, kind_meta},
|
||||
text_input::keyed_input,
|
||||
};
|
||||
use crate::{DesktopFlexExt, DesktopPalette};
|
||||
|
||||
impl SettingsModal {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn render_custom_property_row(
|
||||
&self,
|
||||
prop: &affine_store::workspace_db::DocCustomPropertyInfoRow,
|
||||
doc_count: usize,
|
||||
page_state: &Entity<PropertiesPageState>,
|
||||
snapshot: &PropertiesPageState,
|
||||
readonly: bool,
|
||||
palette: DesktopPalette,
|
||||
stops: &mut FocusStops,
|
||||
window: &mut Window,
|
||||
app: &mut App,
|
||||
) -> Div {
|
||||
let id = prop.id.clone();
|
||||
let t = strings_for(&self.shell.read(app).state().display_language);
|
||||
let (kind_label, icon) = kind_meta(&prop.property_type);
|
||||
let display_name = prop
|
||||
.name
|
||||
.as_deref()
|
||||
.filter(|n| !n.trim().is_empty())
|
||||
.unwrap_or("Unnamed")
|
||||
.to_owned();
|
||||
let current_show = prop.show.as_deref().unwrap_or("always-show");
|
||||
let is_renaming = !readonly && snapshot.renaming_id.as_deref() == Some(id.as_str());
|
||||
let is_deleting = !readonly && snapshot.confirm_delete_id.as_deref() == Some(id.as_str());
|
||||
|
||||
let mut row = div()
|
||||
.id(SharedString::from(format!(
|
||||
"desktop.settings.properties.item.{id}"
|
||||
)))
|
||||
.snapshot(
|
||||
ui::snap_id!("desktop.settings.properties.item.{id}"),
|
||||
Some(MODAL_ID),
|
||||
)
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(8.0))
|
||||
.p(px(8.0))
|
||||
.rounded(px(8.0))
|
||||
.bg(palette.bg_surface);
|
||||
|
||||
let mut top_line = div()
|
||||
.flex()
|
||||
.flex_wrap()
|
||||
.items_center()
|
||||
.justify_between()
|
||||
.gap(px(8.0));
|
||||
|
||||
let mut left = div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(8.0))
|
||||
.min_w_0()
|
||||
.flex_1()
|
||||
.child(
|
||||
svg()
|
||||
.data(icon.svg.as_bytes())
|
||||
.size(px(16.0))
|
||||
.flex_shrink(0.0)
|
||||
.text_color(palette.text_secondary),
|
||||
);
|
||||
|
||||
if is_renaming {
|
||||
let rename_id_str = format!("desktop.settings.properties.rename.{id}");
|
||||
let rename_snap = ui::snap_id!("desktop.settings.properties.rename.{id}");
|
||||
let rename_input = keyed_input(
|
||||
SharedString::from(rename_id_str),
|
||||
rename_snap,
|
||||
&display_name,
|
||||
"Property name",
|
||||
false,
|
||||
palette,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
);
|
||||
let save_rename: Rc<dyn Fn(&mut Window, &mut App)> = {
|
||||
let shell = self.shell.downgrade();
|
||||
let page_state = page_state.clone();
|
||||
let prop_id = id.clone();
|
||||
let input = rename_input.clone();
|
||||
Rc::new(move |_, app| {
|
||||
let next = input.read(app).text().trim().to_owned();
|
||||
if !next.is_empty() {
|
||||
let _ = shell.update(app, |view, cx| {
|
||||
if view.state.store.edit_workspace_custom_property(
|
||||
&prop_id,
|
||||
Some(&next),
|
||||
None,
|
||||
false,
|
||||
) {
|
||||
view.flush_persistence();
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
}
|
||||
page_state.update(app, |state, cx| {
|
||||
state.renaming_id = None;
|
||||
cx.notify();
|
||||
});
|
||||
})
|
||||
};
|
||||
let enter_save = save_rename.clone();
|
||||
let cancel_state = page_state.clone();
|
||||
rename_input.update(app, |field, _| {
|
||||
field.sync(
|
||||
&display_name,
|
||||
false,
|
||||
palette,
|
||||
None,
|
||||
Some(Rc::new(move |_, window, app| enter_save(window, app))),
|
||||
Some(Rc::new(move |_, app| {
|
||||
cancel_state.update(app, |state, cx| {
|
||||
state.renaming_id = None;
|
||||
cx.notify();
|
||||
});
|
||||
})),
|
||||
window,
|
||||
);
|
||||
});
|
||||
let save_btn = small_action_button_dyn(
|
||||
format!("desktop.settings.properties.rename_save.{id}"),
|
||||
ui::snap_id!("desktop.settings.properties.rename_save.{id}"),
|
||||
t.save,
|
||||
true,
|
||||
palette,
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
save_rename,
|
||||
);
|
||||
let cancel_btn = small_action_button_dyn(
|
||||
format!("desktop.settings.properties.rename_cancel.{id}"),
|
||||
ui::snap_id!("desktop.settings.properties.rename_cancel.{id}"),
|
||||
t.cancel,
|
||||
false,
|
||||
palette,
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
Rc::new({
|
||||
let page_state = page_state.clone();
|
||||
move |_, app| {
|
||||
page_state.update(app, |state, cx| {
|
||||
state.renaming_id = None;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
left = left
|
||||
.child(div().w(px(160.0)).min_w_0().child(rename_input))
|
||||
.child(save_btn)
|
||||
.child(cancel_btn);
|
||||
} else {
|
||||
left = left
|
||||
.child(
|
||||
div()
|
||||
.min_w_0()
|
||||
.truncate()
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.child(display_name.clone()),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(11.0))
|
||||
.text_color(palette.text_muted)
|
||||
.flex_shrink(0.0)
|
||||
.child(kind_label),
|
||||
);
|
||||
}
|
||||
|
||||
let mut actions = div().flex().items_center().gap(px(6.0)).flex_shrink(0.0);
|
||||
if !readonly {
|
||||
let mut vis_group = div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(2.0))
|
||||
.p(px(2.0))
|
||||
.rounded(px(6.0))
|
||||
.bg(palette.bg_elevated)
|
||||
.border_1()
|
||||
.border_color(palette.border);
|
||||
for (vis_wire, vis_label) in VISIBILITIES {
|
||||
let selected = current_show == vis_wire;
|
||||
let vis_id = format!("desktop.settings.properties.vis.{id}.{vis_wire}");
|
||||
let vis_snap = ui::snap_id!("desktop.settings.properties.vis.{id}.{vis_wire}");
|
||||
let stop = focus_stop_named(
|
||||
ElementId::Name(SharedString::from(vis_id.clone())),
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
);
|
||||
let focused = stop.handle.is_focused(window);
|
||||
let keyboard = window.last_input_was_keyboard();
|
||||
let click_focus = stop.handle.clone();
|
||||
let apply_vis = {
|
||||
let shell = self.shell.downgrade();
|
||||
let prop_id = id.clone();
|
||||
Rc::new(move |app: &mut App| {
|
||||
let _ = shell.update(app, |view, cx| {
|
||||
if view.state.store.edit_workspace_custom_property(
|
||||
&prop_id,
|
||||
None,
|
||||
Some(vis_wire),
|
||||
false,
|
||||
) {
|
||||
view.flush_persistence();
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
})
|
||||
};
|
||||
let click_vis = apply_vis.clone();
|
||||
let key_stop = stop.clone();
|
||||
vis_group = vis_group.child(
|
||||
div()
|
||||
.id(SharedString::from(vis_id))
|
||||
.snapshot(vis_snap, Some(MODAL_ID))
|
||||
.snapshot_focused(focused)
|
||||
.track_focus(&stop.handle)
|
||||
.relative()
|
||||
.h(px(24.0))
|
||||
.px(px(7.0))
|
||||
.rounded(px(4.0))
|
||||
.bg(if selected {
|
||||
palette.accent_soft
|
||||
} else {
|
||||
ui::transparent_black()
|
||||
})
|
||||
.border_1()
|
||||
.border_color(if focused && keyboard {
|
||||
palette.accent
|
||||
} else {
|
||||
ui::transparent_black()
|
||||
})
|
||||
.flex()
|
||||
.items_center()
|
||||
.cursor_pointer()
|
||||
.hover(move |s| s.bg(palette.hover_color))
|
||||
.text_size(px(11.0))
|
||||
.font_weight(if selected {
|
||||
FontWeight::SEMIBOLD
|
||||
} else {
|
||||
FontWeight::NORMAL
|
||||
})
|
||||
.text_color(if selected {
|
||||
palette.accent
|
||||
} else {
|
||||
palette.text_secondary
|
||||
})
|
||||
.on_mouse_down(MouseButton::Left, move |_, window, app| {
|
||||
window.focus(&click_focus, app);
|
||||
})
|
||||
.on_click(move |_, _, app| click_vis(app))
|
||||
.on_key_down(move |event, window, app| {
|
||||
if matches!(event.keystroke.key.as_str(), "enter" | "space")
|
||||
&& !event.keystroke.modifiers.modified()
|
||||
{
|
||||
key_stop.reveal(window);
|
||||
apply_vis(app);
|
||||
window.prevent_default();
|
||||
app.stop_propagation();
|
||||
}
|
||||
})
|
||||
.child(stop.probe())
|
||||
.child(vis_label),
|
||||
);
|
||||
}
|
||||
actions = actions.child(vis_group);
|
||||
|
||||
if !is_renaming {
|
||||
let rename_btn = icon_action_button(
|
||||
format!("desktop.settings.properties.rename_btn.{id}"),
|
||||
ui::snap_id!("desktop.settings.properties.rename_btn.{id}"),
|
||||
icons::EDIT,
|
||||
palette.text_secondary,
|
||||
palette,
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
Rc::new({
|
||||
let page_state = page_state.clone();
|
||||
let prop_id = id.clone();
|
||||
move |_, app| {
|
||||
page_state.update(app, |state, cx| {
|
||||
state.renaming_id = Some(prop_id.clone());
|
||||
state.confirm_delete_id = None;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
actions = actions.child(rename_btn);
|
||||
}
|
||||
|
||||
let delete_btn = icon_action_button(
|
||||
format!("desktop.settings.properties.delete_btn.{id}"),
|
||||
ui::snap_id!("desktop.settings.properties.delete_btn.{id}"),
|
||||
icons::DELETE,
|
||||
palette.danger,
|
||||
palette,
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
Rc::new({
|
||||
let page_state = page_state.clone();
|
||||
let prop_id = id.clone();
|
||||
move |_, app| {
|
||||
page_state.update(app, |state, cx| {
|
||||
state.confirm_delete_id =
|
||||
if state.confirm_delete_id.as_deref() == Some(prop_id.as_str()) {
|
||||
None
|
||||
} else {
|
||||
Some(prop_id.clone())
|
||||
};
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
actions = actions.child(delete_btn);
|
||||
}
|
||||
|
||||
top_line = top_line.child(left).child(actions);
|
||||
row = row.child(top_line);
|
||||
|
||||
if is_deleting {
|
||||
let confirm_del = small_action_button_dyn(
|
||||
format!("desktop.settings.properties.delete_confirm.{id}"),
|
||||
ui::snap_id!("desktop.settings.properties.delete_confirm.{id}"),
|
||||
t.delete,
|
||||
true,
|
||||
DesktopPalette {
|
||||
accent: palette.danger,
|
||||
..palette
|
||||
},
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
Rc::new({
|
||||
let shell = self.shell.downgrade();
|
||||
let page_state = page_state.clone();
|
||||
let prop_id = id.clone();
|
||||
move |_, app| {
|
||||
let _ = shell.update(app, |view, cx| {
|
||||
if view
|
||||
.state
|
||||
.store
|
||||
.edit_workspace_custom_property(&prop_id, None, None, true)
|
||||
{
|
||||
view.flush_persistence();
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
page_state.update(app, |state, cx| {
|
||||
state.confirm_delete_id = None;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
let cancel_del = small_action_button_dyn(
|
||||
format!("desktop.settings.properties.delete_cancel.{id}"),
|
||||
ui::snap_id!("desktop.settings.properties.delete_cancel.{id}"),
|
||||
t.cancel,
|
||||
false,
|
||||
palette,
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
Rc::new({
|
||||
let page_state = page_state.clone();
|
||||
move |_, app| {
|
||||
page_state.update(app, |state, cx| {
|
||||
state.confirm_delete_id = None;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
let noun = if doc_count == 1 { "doc" } else { "docs" };
|
||||
row = row.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_wrap()
|
||||
.items_center()
|
||||
.justify_between()
|
||||
.gap(px(8.0))
|
||||
.pt(px(4.0))
|
||||
.border_t_1()
|
||||
.border_color(palette.border)
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(12.0))
|
||||
.text_color(palette.danger)
|
||||
.child(format!("Remove \"{display_name}\" ({doc_count} {noun})?")),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(6.0))
|
||||
.child(cancel_del)
|
||||
.child(confirm_del),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
div().child(row)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn small_action_button(
|
||||
id: &'static str,
|
||||
label: &'static str,
|
||||
primary: bool,
|
||||
palette: DesktopPalette,
|
||||
stops: &mut FocusStops,
|
||||
window: &mut Window,
|
||||
app: &mut App,
|
||||
on_press: Rc<dyn Fn(&mut Window, &mut App)>,
|
||||
) -> Div {
|
||||
small_action_button_dyn(
|
||||
id.to_owned(),
|
||||
ui::snap_id!("{id}"),
|
||||
label,
|
||||
primary,
|
||||
palette,
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
on_press,
|
||||
)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn small_action_button_dyn(
|
||||
id: String,
|
||||
snapshot: ui::SnapshotId,
|
||||
label: &'static str,
|
||||
primary: bool,
|
||||
palette: DesktopPalette,
|
||||
stops: &mut FocusStops,
|
||||
window: &mut Window,
|
||||
app: &mut App,
|
||||
on_press: Rc<dyn Fn(&mut Window, &mut App)>,
|
||||
) -> Div {
|
||||
let stop = focus_stop_named(
|
||||
ElementId::Name(SharedString::from(id.clone())),
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
);
|
||||
let focused = stop.handle.is_focused(window);
|
||||
let keyboard = window.last_input_was_keyboard();
|
||||
let click_focus = stop.handle.clone();
|
||||
let click_cb = on_press.clone();
|
||||
let key_stop = stop.clone();
|
||||
div().child(
|
||||
div()
|
||||
.id(SharedString::from(id))
|
||||
.snapshot(snapshot, Some(MODAL_ID))
|
||||
.snapshot_focused(focused)
|
||||
.track_focus(&stop.handle)
|
||||
.relative()
|
||||
.h(px(28.0))
|
||||
.px(px(10.0))
|
||||
.rounded(px(6.0))
|
||||
.bg(if primary {
|
||||
palette.accent
|
||||
} else {
|
||||
palette.bg_elevated
|
||||
})
|
||||
.border_1()
|
||||
.border_color(if focused && keyboard {
|
||||
if primary {
|
||||
palette.text_primary
|
||||
} else {
|
||||
palette.accent
|
||||
}
|
||||
} else if primary {
|
||||
ui::transparent_black()
|
||||
} else {
|
||||
palette.border
|
||||
})
|
||||
.hover(move |s| {
|
||||
if primary {
|
||||
s.bg(palette.accent.opacity(0.88))
|
||||
} else {
|
||||
s.bg(palette.hover_overlay)
|
||||
}
|
||||
})
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.text_size(px(12.0))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(if primary {
|
||||
ui::white()
|
||||
} else {
|
||||
palette.text_primary
|
||||
})
|
||||
.on_mouse_down(MouseButton::Left, move |_, window, app| {
|
||||
window.focus(&click_focus, app);
|
||||
})
|
||||
.on_click(move |_, window, app| {
|
||||
click_cb(window, app);
|
||||
})
|
||||
.on_key_down(move |event, window, app| {
|
||||
if matches!(event.keystroke.key.as_str(), "enter" | "space")
|
||||
&& !event.keystroke.modifiers.modified()
|
||||
{
|
||||
key_stop.reveal(window);
|
||||
on_press(window, app);
|
||||
window.prevent_default();
|
||||
app.stop_propagation();
|
||||
}
|
||||
})
|
||||
.child(stop.probe())
|
||||
.child(label),
|
||||
)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn icon_action_button(
|
||||
id: String,
|
||||
snapshot: ui::SnapshotId,
|
||||
icon: IconDef,
|
||||
color: ui::Hsla,
|
||||
palette: DesktopPalette,
|
||||
stops: &mut FocusStops,
|
||||
window: &mut Window,
|
||||
app: &mut App,
|
||||
on_press: Rc<dyn Fn(&mut Window, &mut App)>,
|
||||
) -> Div {
|
||||
let stop = focus_stop_named(
|
||||
ElementId::Name(SharedString::from(id.clone())),
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
);
|
||||
let focused = stop.handle.is_focused(window);
|
||||
let keyboard = window.last_input_was_keyboard();
|
||||
let click_focus = stop.handle.clone();
|
||||
let click_cb = on_press.clone();
|
||||
let key_stop = stop.clone();
|
||||
div().child(
|
||||
div()
|
||||
.id(SharedString::from(id))
|
||||
.snapshot(snapshot, Some(MODAL_ID))
|
||||
.snapshot_focused(focused)
|
||||
.track_focus(&stop.handle)
|
||||
.relative()
|
||||
.size(px(26.0))
|
||||
.rounded(px(6.0))
|
||||
.border_1()
|
||||
.border_color(if focused && keyboard {
|
||||
palette.accent
|
||||
} else {
|
||||
ui::transparent_black()
|
||||
})
|
||||
.hover(move |s| s.bg(palette.hover_overlay))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.on_mouse_down(MouseButton::Left, move |_, window, app| {
|
||||
window.focus(&click_focus, app);
|
||||
})
|
||||
.on_click(move |_, window, app| {
|
||||
click_cb(window, app);
|
||||
})
|
||||
.on_key_down(move |event, window, app| {
|
||||
if matches!(event.keystroke.key.as_str(), "enter" | "space")
|
||||
&& !event.keystroke.modifiers.modified()
|
||||
{
|
||||
key_stop.reveal(window);
|
||||
on_press(window, app);
|
||||
window.prevent_default();
|
||||
app.stop_propagation();
|
||||
}
|
||||
})
|
||||
.child(stop.probe())
|
||||
.child(
|
||||
svg()
|
||||
.data(icon.svg.as_bytes())
|
||||
.size(px(14.0))
|
||||
.text_color(color),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
//! Storage summary and native local `.affine` backup export for `Settings -> Storage`.
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::rc::Rc;
|
||||
|
||||
use ui::{App, InteractiveElement, Window};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use ui::{FontWeight, MouseButton, ParentElement, StatefulInteractiveElement, Styled, div, px};
|
||||
|
||||
use super::{
|
||||
MODAL_ID, SettingsModal, WorkspaceSummary,
|
||||
controls::{FocusStops, section},
|
||||
pages::setting_row,
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::{
|
||||
controls::{control_row, focus_stop},
|
||||
i18n::strings_for,
|
||||
};
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const EXPORT_WORKSPACE_RUNTIME_ID: &str = "settings-storage-export";
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const EXPORT_STATE_RUNTIME_ID: &str = "settings-storage-export-state";
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[derive(Clone, Default)]
|
||||
struct ExportFeedback {
|
||||
status: Option<String>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn write_unique_backup_in(
|
||||
dir: &std::path::Path,
|
||||
filename: &str,
|
||||
bytes: &[u8],
|
||||
) -> anyhow::Result<std::path::PathBuf> {
|
||||
use std::io::{ErrorKind, Write as _};
|
||||
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let stem = filename.strip_suffix(".affine").unwrap_or(filename);
|
||||
let mut index = 1usize;
|
||||
loop {
|
||||
let candidate_name = if index == 1 {
|
||||
format!("{stem}.affine")
|
||||
} else {
|
||||
format!("{stem}-{index}.affine")
|
||||
};
|
||||
let dest = dir.join(candidate_name);
|
||||
match std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&dest)
|
||||
{
|
||||
Ok(mut file) => {
|
||||
file.write_all(bytes)?;
|
||||
file.sync_all()?;
|
||||
return Ok(dest);
|
||||
}
|
||||
Err(err) if err.kind() == ErrorKind::AlreadyExists => {
|
||||
index += 1;
|
||||
}
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn deliver_backup(filename: &str, bytes: &[u8]) -> anyhow::Result<(String, usize)> {
|
||||
let dest = write_unique_backup_in(&std::env::temp_dir(), filename, bytes)?;
|
||||
Ok((dest.display().to_string(), bytes.len()))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn format_bytes(len: usize) -> String {
|
||||
if len >= 1024 * 1024 {
|
||||
format!("{:.1} MB", len as f64 / (1024.0 * 1024.0))
|
||||
} else if len >= 1024 {
|
||||
format!("{:.1} KB", len as f64 / 1024.0)
|
||||
} else {
|
||||
format!("{len} B")
|
||||
}
|
||||
}
|
||||
|
||||
impl SettingsModal {
|
||||
pub(super) fn workspace_storage_sections(
|
||||
&self,
|
||||
stacked: bool,
|
||||
stops: &mut FocusStops,
|
||||
window: &mut Window,
|
||||
app: &mut App,
|
||||
) -> Vec<ui::Div> {
|
||||
let palette = self.palette;
|
||||
let shell_read = self.shell.read(app);
|
||||
let (storage, detail) = WorkspaceSummary::of(shell_read).storage;
|
||||
let snapshot_text = format!("{storage}\n{detail}");
|
||||
let panel = setting_row(storage, detail, palette)
|
||||
.snapshot(
|
||||
ui::snap_id!("desktop.settings.storage.panel"),
|
||||
Some(MODAL_ID),
|
||||
)
|
||||
.snapshot_text(snapshot_text);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = (stacked, stops, window);
|
||||
vec![section(None, [panel], palette)]
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let mut sections = vec![section(None, [panel], palette)];
|
||||
if !shell_read.state().web_chrome {
|
||||
let t = strings_for(&shell_read.state().display_language);
|
||||
let export_state = window.use_keyed_state(EXPORT_STATE_RUNTIME_ID, app, |_, _| {
|
||||
ExportFeedback::default()
|
||||
});
|
||||
let export_snapshot = export_state.read(app).clone();
|
||||
|
||||
let stop = focus_stop(EXPORT_WORKSPACE_RUNTIME_ID, stops, window, app);
|
||||
let focused = stop.handle.is_focused(window);
|
||||
let keyboard = window.last_input_was_keyboard();
|
||||
let click_focus = stop.handle.clone();
|
||||
let run_export: Rc<dyn Fn(&mut App)> = {
|
||||
let shell = self.shell.downgrade();
|
||||
let export_state = export_state.clone();
|
||||
Rc::new(move |app: &mut App| {
|
||||
let result = shell.update(app, |view, cx| {
|
||||
let backup = view.export_active_workspace_backup(cx)?;
|
||||
deliver_backup(&backup.filename, &backup.bytes)
|
||||
});
|
||||
if let Ok(outcome) = result {
|
||||
match outcome {
|
||||
Ok((target, len)) => {
|
||||
let summary =
|
||||
format!("Exported {target} ({})", format_bytes(len));
|
||||
export_state.update(app, |state, cx| {
|
||||
state.status = Some(summary);
|
||||
state.error = None;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
Err(err) => {
|
||||
export_state.update(app, |state, cx| {
|
||||
state.status = None;
|
||||
state.error = Some(err.to_string());
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
let click_export = run_export.clone();
|
||||
let key_export = run_export;
|
||||
let key_stop = stop.clone();
|
||||
|
||||
let export_button = div()
|
||||
.id(EXPORT_WORKSPACE_RUNTIME_ID)
|
||||
.snapshot(
|
||||
ui::snap_id!("desktop.settings.storage.export"),
|
||||
Some(MODAL_ID),
|
||||
)
|
||||
.snapshot_focused(focused)
|
||||
.track_focus(&stop.handle)
|
||||
.relative()
|
||||
.h(px(32.0))
|
||||
.px(px(14.0))
|
||||
.rounded(px(8.0))
|
||||
.bg(palette.accent)
|
||||
.hover(move |s| s.bg(palette.accent.opacity(0.88)))
|
||||
.border_1()
|
||||
.border_color(if focused && keyboard {
|
||||
palette.text_primary
|
||||
} else {
|
||||
ui::transparent_black()
|
||||
})
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.flex_shrink(0.0)
|
||||
.cursor_pointer()
|
||||
.text_size(px(12.0))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(ui::white())
|
||||
.on_mouse_down(MouseButton::Left, move |_, window, app| {
|
||||
window.focus(&click_focus, app);
|
||||
})
|
||||
.on_click(move |_, _, app| {
|
||||
click_export(app);
|
||||
})
|
||||
.on_key_down(move |event, window, app| {
|
||||
if matches!(event.keystroke.key.as_str(), "enter" | "space")
|
||||
&& !event.keystroke.modifiers.modified()
|
||||
{
|
||||
key_stop.reveal(window);
|
||||
key_export(app);
|
||||
window.prevent_default();
|
||||
app.stop_propagation();
|
||||
}
|
||||
})
|
||||
.child(stop.probe())
|
||||
.child(t.export_workspace);
|
||||
|
||||
let mut backup_rows = vec![control_row(
|
||||
t.full_backup,
|
||||
t.full_backup_desc,
|
||||
export_button,
|
||||
stacked,
|
||||
palette,
|
||||
)];
|
||||
if let Some(status) = export_snapshot.status {
|
||||
backup_rows.push(
|
||||
div().child(
|
||||
div()
|
||||
.id("settings-storage-export-status")
|
||||
.snapshot(
|
||||
ui::snap_id!("desktop.settings.storage.export_status"),
|
||||
Some(MODAL_ID),
|
||||
)
|
||||
.snapshot_text(status.clone())
|
||||
.text_size(px(12.0))
|
||||
.text_color(palette.accent)
|
||||
.child(status),
|
||||
),
|
||||
);
|
||||
} else if let Some(err) = export_snapshot.error {
|
||||
backup_rows.push(
|
||||
div().child(
|
||||
div()
|
||||
.id("settings-storage-export-status")
|
||||
.snapshot(
|
||||
ui::snap_id!("desktop.settings.storage.export_status"),
|
||||
Some(MODAL_ID),
|
||||
)
|
||||
.snapshot_text(err.clone())
|
||||
.text_size(px(12.0))
|
||||
.text_color(palette.danger)
|
||||
.child(err),
|
||||
),
|
||||
);
|
||||
}
|
||||
sections.push(section(Some(t.backup_section), backup_rows, palette));
|
||||
}
|
||||
sections
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
//! Template toggle and template-document picker widgets for workspace settings.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use ui::{
|
||||
Anchor, App, Entity, FontWeight, InteractiveElement, IntoElement, MouseButton, ParentElement,
|
||||
SharedString, StatefulInteractiveElement, Styled, Window, anchored, deferred, div, point, px,
|
||||
svg,
|
||||
};
|
||||
use ui_tokens::{ThemeMode, icons};
|
||||
|
||||
use super::{
|
||||
MODAL_ID,
|
||||
controls::{FocusStops, ScrollRegion, focus_stop, scroll_area},
|
||||
i18n::SettingsStrings,
|
||||
};
|
||||
use crate::{DesktopFlexExt, DesktopPalette, workbench::DesktopShellView};
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum TemplateTarget {
|
||||
Journal,
|
||||
Page,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct TemplateMenuState {
|
||||
pub(super) open: Option<TemplateTarget>,
|
||||
highlight: usize,
|
||||
}
|
||||
|
||||
pub(super) fn menu_state(window: &mut Window, app: &mut App) -> Entity<TemplateMenuState> {
|
||||
window.use_keyed_state("desktop.settings.preference.template_menu", app, |_, _| {
|
||||
TemplateMenuState::default()
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn close_if_open(menu: &Entity<TemplateMenuState>, app: &mut App) -> bool {
|
||||
if menu.read(app).open.is_some() {
|
||||
menu.update(app, |state, cx| {
|
||||
state.open = None;
|
||||
cx.notify();
|
||||
});
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn toggle_switch(
|
||||
id: &'static str,
|
||||
checked: bool,
|
||||
disabled: bool,
|
||||
palette: DesktopPalette,
|
||||
stops: &mut FocusStops,
|
||||
window: &mut Window,
|
||||
app: &mut App,
|
||||
on_toggle: Rc<dyn Fn(bool, &mut App)>,
|
||||
) -> impl IntoElement + use<> {
|
||||
let stop = (!disabled).then(|| focus_stop(id, stops, window, app));
|
||||
let focused = stop.as_ref().is_some_and(|s| s.handle.is_focused(window));
|
||||
let keyboard = window.last_input_was_keyboard();
|
||||
let mut track = div()
|
||||
.relative()
|
||||
.w(px(40.0))
|
||||
.h(px(22.0))
|
||||
.p(px(2.0))
|
||||
.rounded(px(11.0))
|
||||
.bg(if checked {
|
||||
palette.accent
|
||||
} else {
|
||||
palette.border_strong
|
||||
})
|
||||
.border_1()
|
||||
.border_color(if focused && keyboard {
|
||||
palette.text_primary
|
||||
} else {
|
||||
ui::transparent_black()
|
||||
})
|
||||
.flex()
|
||||
.items_center()
|
||||
.id(id)
|
||||
.snapshot(id, Some(MODAL_ID))
|
||||
.snapshot_focused(focused)
|
||||
.child({
|
||||
let mut knob = div().size(px(16.0)).rounded(px(8.0)).bg(ui::white());
|
||||
knob.style().margin.left = Some(px(if checked { 18.0 } else { 0.0 }).into());
|
||||
knob
|
||||
});
|
||||
if disabled {
|
||||
return track.opacity(0.5).cursor(ui::CursorStyle::Arrow);
|
||||
}
|
||||
if let Some(stop) = stop {
|
||||
let click_focus = stop.handle.clone();
|
||||
let key_stop = stop.clone();
|
||||
let click_toggle = on_toggle.clone();
|
||||
track = track
|
||||
.track_focus(&stop.handle)
|
||||
.cursor_pointer()
|
||||
.on_mouse_down(MouseButton::Left, move |_, window, app| {
|
||||
window.focus(&click_focus, app);
|
||||
})
|
||||
.on_click(move |_, _, app| {
|
||||
click_toggle(!checked, app);
|
||||
})
|
||||
.on_key_down(move |event, window, app| {
|
||||
if matches!(event.keystroke.key.as_str(), "enter" | "space")
|
||||
&& !event.keystroke.modifiers.modified()
|
||||
{
|
||||
key_stop.reveal(window);
|
||||
on_toggle(!checked, app);
|
||||
window.prevent_default();
|
||||
app.stop_propagation();
|
||||
}
|
||||
})
|
||||
.child(stop.probe());
|
||||
}
|
||||
track
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn template_selector(
|
||||
id: &'static str,
|
||||
target: TemplateTarget,
|
||||
current_id: Option<&str>,
|
||||
template_docs: &[(String, String)],
|
||||
disabled: bool,
|
||||
t: &SettingsStrings,
|
||||
menu_state: &Entity<TemplateMenuState>,
|
||||
shell: &Entity<DesktopShellView>,
|
||||
palette: DesktopPalette,
|
||||
mode: ThemeMode,
|
||||
stops: &mut FocusStops,
|
||||
window: &mut Window,
|
||||
app: &mut App,
|
||||
) -> impl IntoElement + use<> {
|
||||
let tpl_scroll = ScrollRegion::use_state(
|
||||
match target {
|
||||
TemplateTarget::Journal => "settings-tpl-journal-scroll-state",
|
||||
TemplateTarget::Page => "settings-tpl-page-scroll-state",
|
||||
},
|
||||
window,
|
||||
app,
|
||||
);
|
||||
let snapshot_state = menu_state.read(app).clone();
|
||||
let is_open = !disabled && snapshot_state.open == Some(target);
|
||||
let current_label = current_id
|
||||
.and_then(|cid| template_docs.iter().find(|(did, _)| did == cid))
|
||||
.map_or(t.none_option, |(_, title)| title.as_str())
|
||||
.to_owned();
|
||||
let stop = (!disabled).then(|| focus_stop(id, stops, window, app));
|
||||
let focused = stop.as_ref().is_some_and(|s| s.handle.is_focused(window));
|
||||
let keyboard = window.last_input_was_keyboard();
|
||||
|
||||
let mut wrapper = div().relative().w(px(210.0)).flex_shrink(0.0);
|
||||
wrapper.style().max_size.width = Some(ui::relative(1.0).into());
|
||||
|
||||
let apply_choice = {
|
||||
let shell = shell.downgrade();
|
||||
let menu_state = menu_state.clone();
|
||||
Rc::new(move |doc_id: Option<String>, app: &mut App| {
|
||||
let _ = shell.update(app, |view, cx| {
|
||||
let mut current = view.state.store.template_settings();
|
||||
match target {
|
||||
TemplateTarget::Journal => current.journal_template_id = doc_id,
|
||||
TemplateTarget::Page => current.page_template_id = doc_id,
|
||||
}
|
||||
if view.state.store.set_template_settings(current) {
|
||||
view.flush_persistence();
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
menu_state.update(app, |state, cx| {
|
||||
state.open = None;
|
||||
cx.notify();
|
||||
});
|
||||
})
|
||||
};
|
||||
|
||||
let mut trigger = div()
|
||||
.id(id)
|
||||
.snapshot(id, Some(MODAL_ID))
|
||||
.snapshot_focused(focused)
|
||||
.relative()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_between()
|
||||
.gap(px(8.0))
|
||||
.w_full()
|
||||
.h(px(32.0))
|
||||
.px(px(10.0))
|
||||
.rounded(px(8.0))
|
||||
.bg(palette.bg_elevated)
|
||||
.border_1()
|
||||
.border_color(if is_open || (focused && keyboard) {
|
||||
palette.accent
|
||||
} else {
|
||||
palette.border
|
||||
})
|
||||
.text_size(px(12.0))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(palette.text_primary)
|
||||
.child(div().min_w_0().truncate().child(current_label))
|
||||
.child(
|
||||
svg()
|
||||
.data(icons::ARROW_DOWN_SMALL.svg.as_bytes())
|
||||
.size(px(16.0))
|
||||
.flex_shrink(0.0)
|
||||
.text_color(palette.text_secondary),
|
||||
);
|
||||
|
||||
let item_count = template_docs.len() + 1;
|
||||
if disabled {
|
||||
trigger = trigger.opacity(0.5).cursor(ui::CursorStyle::Arrow);
|
||||
} else if let Some(stop) = stop.clone() {
|
||||
let click_focus = stop.handle.clone();
|
||||
let click_menu = menu_state.clone();
|
||||
let key_menu = menu_state.clone();
|
||||
let key_stop = stop.clone();
|
||||
let key_apply = apply_choice.clone();
|
||||
let docs_for_keys = template_docs.to_vec();
|
||||
trigger = trigger
|
||||
.track_focus(&stop.handle)
|
||||
.hover(move |s| s.bg(palette.hover_overlay))
|
||||
.cursor_pointer()
|
||||
.on_mouse_down(MouseButton::Left, move |_, window, app| {
|
||||
window.focus(&click_focus, app);
|
||||
})
|
||||
.on_click(move |_, _, app| {
|
||||
click_menu.update(app, |state, cx| {
|
||||
state.open = (state.open != Some(target)).then_some(target);
|
||||
state.highlight = 0;
|
||||
cx.notify();
|
||||
});
|
||||
})
|
||||
.on_key_down(move |event, window, app| {
|
||||
if event.keystroke.modifiers.modified() {
|
||||
return;
|
||||
}
|
||||
let open = key_menu.read(app).open == Some(target);
|
||||
match event.keystroke.key.as_str() {
|
||||
"escape" if open => {
|
||||
key_menu.update(app, |state, cx| {
|
||||
state.open = None;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
"up" if open => {
|
||||
key_menu.update(app, |state, cx| {
|
||||
state.highlight = if state.highlight == 0 {
|
||||
item_count - 1
|
||||
} else {
|
||||
state.highlight - 1
|
||||
};
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
"down" if open => {
|
||||
key_menu.update(app, |state, cx| {
|
||||
state.highlight = (state.highlight + 1) % item_count;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
"enter" | "space" => {
|
||||
key_stop.reveal(window);
|
||||
if open {
|
||||
let idx = key_menu.read(app).highlight;
|
||||
let chosen = docs_for_keys.get(idx).map(|(id, _)| id.clone());
|
||||
key_apply(chosen, app);
|
||||
} else {
|
||||
key_menu.update(app, |state, cx| {
|
||||
state.open = Some(target);
|
||||
state.highlight = 0;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => return,
|
||||
}
|
||||
window.prevent_default();
|
||||
app.stop_propagation();
|
||||
})
|
||||
.child(stop.probe());
|
||||
}
|
||||
|
||||
wrapper = wrapper.child(trigger);
|
||||
if is_open && let Some(stop) = stop {
|
||||
let bounds = stop.bounds.get();
|
||||
let tokens = crate::theme_tokens_for(mode);
|
||||
let panel_bg = crate::rgba_to_hsla(tokens.background_overlay_panel);
|
||||
let trigger_bounds = stop.bounds.clone();
|
||||
let close_out = menu_state.clone();
|
||||
let menu_id = match target {
|
||||
TemplateTarget::Journal => "desktop.settings.preference.journal_template.menu",
|
||||
TemplateTarget::Page => "desktop.settings.preference.page_template.menu",
|
||||
};
|
||||
let scroll_id = match target {
|
||||
TemplateTarget::Journal => "settings-tpl-journal-scroll",
|
||||
TemplateTarget::Page => "settings-tpl-page-scroll",
|
||||
};
|
||||
let mut items_list = div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.flex_shrink(0.0)
|
||||
.gap(px(2.0))
|
||||
.p(px(6.0));
|
||||
|
||||
for (idx, (doc_id, title)) in template_docs.iter().enumerate() {
|
||||
let selected = current_id == Some(doc_id.as_str());
|
||||
let highlighted = idx == snapshot_state.highlight;
|
||||
let pick = apply_choice.clone();
|
||||
let chosen_id = doc_id.clone();
|
||||
let click_scroll = tpl_scroll.clone();
|
||||
items_list = items_list.child(
|
||||
div()
|
||||
.id(SharedString::from(format!("{menu_id}.{doc_id}")))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_between()
|
||||
.gap(px(6.0))
|
||||
.h(px(28.0))
|
||||
.px(px(8.0))
|
||||
.rounded(px(6.0))
|
||||
.flex_shrink(0.0)
|
||||
.cursor_pointer()
|
||||
.bg(if highlighted || selected {
|
||||
palette.hover_color
|
||||
} else {
|
||||
ui::transparent_black()
|
||||
})
|
||||
.hover(move |s| s.bg(palette.hover_color))
|
||||
.text_size(px(12.0))
|
||||
.text_color(palette.text_primary)
|
||||
.on_click(move |_, _, app| {
|
||||
click_scroll.reset();
|
||||
pick(Some(chosen_id.clone()), app);
|
||||
})
|
||||
.child(div().min_w_0().truncate().child(title.clone()))
|
||||
.children(selected.then(|| {
|
||||
svg()
|
||||
.data(icons::DONE.svg.as_bytes())
|
||||
.size(px(14.0))
|
||||
.flex_shrink(0.0)
|
||||
.text_color(palette.accent)
|
||||
})),
|
||||
);
|
||||
}
|
||||
if template_docs.is_empty() {
|
||||
items_list = items_list.child(
|
||||
div()
|
||||
.px(px(8.0))
|
||||
.py(px(6.0))
|
||||
.flex_shrink(0.0)
|
||||
.text_size(px(12.0))
|
||||
.text_color(palette.text_muted)
|
||||
.child(t.no_templates_yet),
|
||||
);
|
||||
}
|
||||
let remove_idx = template_docs.len();
|
||||
let remove_pick = apply_choice;
|
||||
let remove_scroll = tpl_scroll.clone();
|
||||
items_list = items_list
|
||||
.child(
|
||||
div()
|
||||
.h(px(1.0))
|
||||
.my(px(2.0))
|
||||
.flex_shrink(0.0)
|
||||
.bg(palette.border),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.id(SharedString::from(format!("{menu_id}.remove")))
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(6.0))
|
||||
.h(px(28.0))
|
||||
.px(px(8.0))
|
||||
.rounded(px(6.0))
|
||||
.flex_shrink(0.0)
|
||||
.cursor_pointer()
|
||||
.bg(if snapshot_state.highlight == remove_idx {
|
||||
palette.hover_color
|
||||
} else {
|
||||
ui::transparent_black()
|
||||
})
|
||||
.hover(move |s| s.bg(palette.hover_color))
|
||||
.text_size(px(12.0))
|
||||
.text_color(palette.danger)
|
||||
.on_click(move |_, _, app| {
|
||||
remove_scroll.reset();
|
||||
remove_pick(None, app);
|
||||
})
|
||||
.child(t.none_option),
|
||||
);
|
||||
|
||||
let visible_rows = template_docs.len().max(1) + 1;
|
||||
let viewport_h = ((visible_rows as f32) * 30.0 + 16.0).min(200.0);
|
||||
let out_scroll = tpl_scroll.clone();
|
||||
let menu_box = div()
|
||||
.id(menu_id)
|
||||
.snapshot(menu_id, Some(MODAL_ID))
|
||||
.occlude()
|
||||
.w(px(210.0))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.rounded(px(8.0))
|
||||
.bg(panel_bg)
|
||||
.border_1()
|
||||
.border_color(palette.border)
|
||||
.shadow(crate::theme_shadow(mode, "--affine-popover-shadow"))
|
||||
.on_mouse_down_out(move |event, _, app| {
|
||||
if !trigger_bounds.get().contains(&event.position) {
|
||||
out_scroll.reset();
|
||||
close_out.update(app, |state, cx| {
|
||||
if state.open == Some(target) {
|
||||
state.open = None;
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
}
|
||||
})
|
||||
.child(scroll_area(scroll_id, &tpl_scroll, items_list).h(px(viewport_h)));
|
||||
|
||||
wrapper = wrapper.child(
|
||||
deferred(
|
||||
anchored()
|
||||
.attach(bounds, Anchor::BottomLeft)
|
||||
.offset(point(px(0.0), px(4.0)))
|
||||
.child(menu_box),
|
||||
)
|
||||
.priority(2),
|
||||
);
|
||||
}
|
||||
wrapper
|
||||
}
|
||||
@@ -0,0 +1,533 @@
|
||||
//! Single-line IME-aware text input control for settings forms.
|
||||
|
||||
use std::{cell::Cell, ops::Range, rc::Rc};
|
||||
|
||||
use blocksuite_editor::inline_input::{Utf16ImeBuffer, utf16_len, utf16_to_byte};
|
||||
use ui::{
|
||||
App, Bounds, ClipboardItem, Context, ElementId, ElementInputHandler, Entity,
|
||||
EntityInputHandler, FocusHandle, InteractiveElement, IntoElement, KeyDownEvent, MouseButton,
|
||||
ParentElement, Pixels, Point, Render, ShapedLine, SharedString, Styled, TextAlign, TextRun,
|
||||
UTF16Selection, Window, canvas, div, fill, point, px, size,
|
||||
};
|
||||
|
||||
use super::controls::{FocusStop, FocusStops, push_focus_stop};
|
||||
use crate::{DesktopFlexExt, DesktopPalette};
|
||||
|
||||
pub(super) type InputCallback = Rc<dyn Fn(String, &mut Window, &mut App)>;
|
||||
pub(super) type CancelCallback = Rc<dyn Fn(&mut Window, &mut App)>;
|
||||
|
||||
pub(super) struct SettingsTextInput {
|
||||
id: ElementId,
|
||||
snapshot: ui::SnapshotId,
|
||||
buffer: Utf16ImeBuffer,
|
||||
source: String,
|
||||
focus: FocusHandle,
|
||||
placeholder: &'static str,
|
||||
palette: DesktopPalette,
|
||||
bounds: Option<Bounds<Pixels>>,
|
||||
stop_bounds: Rc<Cell<Bounds<Pixels>>>,
|
||||
disabled: bool,
|
||||
on_change: Option<InputCallback>,
|
||||
on_submit: Option<InputCallback>,
|
||||
on_cancel: Option<CancelCallback>,
|
||||
}
|
||||
|
||||
impl SettingsTextInput {
|
||||
pub(super) fn new(
|
||||
id: ElementId,
|
||||
snapshot: ui::SnapshotId,
|
||||
text: String,
|
||||
placeholder: &'static str,
|
||||
palette: DesktopPalette,
|
||||
cx: &Context<Self>,
|
||||
) -> Self {
|
||||
Self {
|
||||
id,
|
||||
snapshot,
|
||||
buffer: Utf16ImeBuffer::new(text.clone(), false),
|
||||
source: text,
|
||||
focus: cx.focus_handle(),
|
||||
placeholder,
|
||||
palette,
|
||||
bounds: None,
|
||||
stop_bounds: Rc::new(Cell::new(Bounds::default())),
|
||||
disabled: false,
|
||||
on_change: None,
|
||||
on_submit: None,
|
||||
on_cancel: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn sync(
|
||||
&mut self,
|
||||
text: &str,
|
||||
disabled: bool,
|
||||
palette: DesktopPalette,
|
||||
on_change: Option<InputCallback>,
|
||||
on_submit: Option<InputCallback>,
|
||||
on_cancel: Option<CancelCallback>,
|
||||
window: &Window,
|
||||
) {
|
||||
self.disabled = disabled;
|
||||
self.palette = palette;
|
||||
self.on_change = on_change;
|
||||
self.on_submit = on_submit;
|
||||
self.on_cancel = on_cancel;
|
||||
if self.buffer.text().trim() == text {
|
||||
self.source = text.to_owned();
|
||||
} else if !self.focus.is_focused(window) && self.source != text {
|
||||
self.source = text.to_owned();
|
||||
self.buffer = Utf16ImeBuffer::new(self.source.clone(), false);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn commit_source(&mut self, text: &str, cx: &mut Context<Self>) {
|
||||
self.source = text.to_owned();
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
pub(super) fn set_text(&mut self, text: &str, window: &Window, cx: &mut Context<Self>) {
|
||||
self.source = text.to_owned();
|
||||
self.buffer = Utf16ImeBuffer::new(self.source.clone(), false);
|
||||
self.notify_changed(window, cx);
|
||||
}
|
||||
|
||||
pub(super) fn text(&self) -> &str {
|
||||
self.buffer.text()
|
||||
}
|
||||
|
||||
pub(super) fn register_stop(&self, stops: &mut FocusStops) -> Option<FocusStop> {
|
||||
(!self.disabled)
|
||||
.then(|| push_focus_stop(self.focus.clone(), self.stop_bounds.clone(), stops))
|
||||
}
|
||||
|
||||
fn notify_changed(&self, window: &Window, cx: &mut Context<Self>) {
|
||||
window.notify_text_input_changed(&self.focus);
|
||||
window.notify_text_selection_changed(&self.focus);
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn emit_change(&self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if let Some(cb) = &self.on_change {
|
||||
let value = self.buffer.text().to_owned();
|
||||
cb(value, window, cx);
|
||||
}
|
||||
}
|
||||
|
||||
fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if self.disabled {
|
||||
return;
|
||||
}
|
||||
let stroke = &event.keystroke;
|
||||
let key = stroke.key.as_str();
|
||||
let command = stroke.modifiers.platform || stroke.modifiers.control;
|
||||
if self.buffer.composing() {
|
||||
match key {
|
||||
"escape" => {
|
||||
self.buffer.cancel_preedit();
|
||||
self.notify_changed(window, cx);
|
||||
window.prevent_default();
|
||||
cx.stop_propagation();
|
||||
}
|
||||
"enter" => cx.stop_propagation(),
|
||||
_ => {}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
match key {
|
||||
"escape" => {
|
||||
if let Some(cancel) = &self.on_cancel {
|
||||
cancel(window, cx);
|
||||
window.prevent_default();
|
||||
cx.stop_propagation();
|
||||
} else if self.buffer.text() != self.source {
|
||||
self.buffer = Utf16ImeBuffer::new(self.source.clone(), false);
|
||||
self.emit_change(window, cx);
|
||||
self.notify_changed(window, cx);
|
||||
window.prevent_default();
|
||||
cx.stop_propagation();
|
||||
}
|
||||
return;
|
||||
}
|
||||
"enter" if !stroke.modifiers.modified() => {
|
||||
if let Some(submit) = &self.on_submit {
|
||||
let value = self.buffer.text().to_owned();
|
||||
let trimmed = value.trim();
|
||||
if !trimmed.is_empty() {
|
||||
self.source = trimmed.to_owned();
|
||||
}
|
||||
submit(value, window, cx);
|
||||
}
|
||||
window.prevent_default();
|
||||
cx.stop_propagation();
|
||||
return;
|
||||
}
|
||||
"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, "");
|
||||
self.emit_change(window, cx);
|
||||
}
|
||||
}
|
||||
}
|
||||
"v" if command => {
|
||||
let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else {
|
||||
return;
|
||||
};
|
||||
self.buffer.replace(None, &text);
|
||||
self.emit_change(window, cx);
|
||||
}
|
||||
_ if self
|
||||
.buffer
|
||||
.key(key, stroke.modifiers.shift, command)
|
||||
.is_some() =>
|
||||
{
|
||||
self.emit_change(window, cx);
|
||||
}
|
||||
_ if command => {
|
||||
window.prevent_default();
|
||||
cx.stop_propagation();
|
||||
return;
|
||||
}
|
||||
_ => return,
|
||||
}
|
||||
self.notify_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 {
|
||||
self.placeholder.to_owned()
|
||||
} else {
|
||||
shown
|
||||
};
|
||||
let run = TextRun {
|
||||
len: text.len(),
|
||||
font,
|
||||
color: if empty {
|
||||
self.palette.text_muted
|
||||
} else if self.disabled {
|
||||
self.palette.text_secondary
|
||||
} else {
|
||||
self.palette.text_primary
|
||||
},
|
||||
background_color: None,
|
||||
underline: None,
|
||||
strikethrough: None,
|
||||
};
|
||||
let line = window
|
||||
.text_system()
|
||||
.shape_line(text.into(), px(13.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));
|
||||
let origin = point(bounds.origin.x - scroll, bounds.origin.y);
|
||||
InputLine {
|
||||
line,
|
||||
origin,
|
||||
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 SettingsTextInput {
|
||||
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.disabled && self.focus.is_focused(window);
|
||||
let entity = cx.entity();
|
||||
let layout_entity = entity.clone();
|
||||
let stop_bounds = self.stop_bounds.clone();
|
||||
let focus = self.focus.clone();
|
||||
let palette = self.palette;
|
||||
let disabled = self.disabled;
|
||||
let mut root = div()
|
||||
.id(self.id.clone())
|
||||
.snapshot(self.snapshot.clone(), Some(super::MODAL_ID))
|
||||
.snapshot_focused(focused)
|
||||
.relative()
|
||||
.h(px(32.0))
|
||||
.px(px(10.0))
|
||||
.rounded(px(8.0))
|
||||
.bg(palette.bg_elevated)
|
||||
.border_1()
|
||||
.border_color(if focused {
|
||||
palette.accent
|
||||
} else {
|
||||
palette.border
|
||||
})
|
||||
.flex()
|
||||
.items_center()
|
||||
.child(
|
||||
canvas(
|
||||
move |bounds, window, cx| {
|
||||
stop_bounds.set(bounds);
|
||||
layout_entity.read(cx).line(bounds, window)
|
||||
},
|
||||
move |bounds, layout, window, cx| {
|
||||
entity.update(cx, |field, _| field.bounds = Some(bounds));
|
||||
if !disabled {
|
||||
window.handle_input(
|
||||
&focus,
|
||||
ElementInputHandler::new(bounds, entity),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
if focused && !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 + px(5.0),
|
||||
),
|
||||
size(
|
||||
rect.size.width,
|
||||
(bounds.size.height - px(10.0)).max(px(1.0)),
|
||||
),
|
||||
),
|
||||
palette.accent_soft,
|
||||
));
|
||||
}
|
||||
}
|
||||
let y = layout.origin.y
|
||||
+ (bounds.size.height - layout.line.font_size) / 2.0
|
||||
- px(1.0);
|
||||
let _ = layout.line.paint(
|
||||
point(layout.origin.x, y),
|
||||
layout.line.font_size,
|
||||
TextAlign::Left,
|
||||
Some(bounds.size.width),
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
if let Some(marked) = marked.filter(|range| !range.is_empty()) {
|
||||
let mark = layout.range_bounds(marked);
|
||||
window.paint_quad(fill(
|
||||
Bounds::new(
|
||||
point(mark.origin.x, bounds.bottom() - px(4.0)),
|
||||
size(mark.size.width, px(1.0)),
|
||||
),
|
||||
palette.accent,
|
||||
));
|
||||
}
|
||||
if focused && selection.is_empty() {
|
||||
let caret = layout.range_bounds(selection.start..selection.start);
|
||||
window.paint_quad(fill(
|
||||
Bounds::new(
|
||||
point(caret.origin.x, bounds.origin.y + px(6.0)),
|
||||
size(px(1.5), (bounds.size.height - px(12.0)).max(px(1.0))),
|
||||
),
|
||||
palette.accent,
|
||||
));
|
||||
}
|
||||
},
|
||||
)
|
||||
.w_full()
|
||||
.h_full(),
|
||||
);
|
||||
if disabled {
|
||||
root = root.opacity(0.6).cursor(ui::CursorStyle::Arrow);
|
||||
} else {
|
||||
root = root
|
||||
.track_focus(&self.focus)
|
||||
.cursor(ui::CursorStyle::IBeam)
|
||||
.on_mouse_down(
|
||||
MouseButton::Left,
|
||||
cx.listener(|this, event: &ui::MouseDownEvent, window, cx| {
|
||||
window.focus(&this.focus, cx);
|
||||
if let Some(bounds) = this.bounds {
|
||||
let line = this.line(bounds, window);
|
||||
let index = line.index_at_x(event.position.x);
|
||||
this.buffer.move_caret(index, event.modifiers.shift);
|
||||
this.notify_changed(window, cx);
|
||||
}
|
||||
cx.stop_propagation();
|
||||
}),
|
||||
)
|
||||
.on_key_down(cx.listener(Self::key_down));
|
||||
}
|
||||
root
|
||||
}
|
||||
}
|
||||
|
||||
impl EntityInputHandler for SettingsTextInput {
|
||||
fn text_for_range(
|
||||
&mut self,
|
||||
range_utf16: Range<usize>,
|
||||
adjusted_range: &mut Option<Range<usize>>,
|
||||
_: &mut Window,
|
||||
_: &mut Context<Self>,
|
||||
) -> Option<String> {
|
||||
let len = utf16_len(self.buffer.text());
|
||||
let range = range_utf16.start.min(len)..range_utf16.end.min(len);
|
||||
*adjusted_range = Some(range.clone());
|
||||
let start = utf16_to_byte(self.buffer.text(), range.start);
|
||||
let end = utf16_to_byte(self.buffer.text(), range.end);
|
||||
Some(self.buffer.text()[start..end].to_owned())
|
||||
}
|
||||
|
||||
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.emit_change(window, cx);
|
||||
self.notify_changed(window, cx);
|
||||
}
|
||||
|
||||
fn replace_text_in_range(
|
||||
&mut self,
|
||||
range_utf16: Option<Range<usize>>,
|
||||
text: &str,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
if self.disabled {
|
||||
return;
|
||||
}
|
||||
self.buffer.replace(range_utf16, text);
|
||||
self.emit_change(window, cx);
|
||||
self.notify_changed(window, cx);
|
||||
}
|
||||
|
||||
fn replace_and_mark_text_in_range(
|
||||
&mut self,
|
||||
range_utf16: Option<Range<usize>>,
|
||||
new_text: &str,
|
||||
new_selected_range_utf16: Option<Range<usize>>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
if self.disabled {
|
||||
return;
|
||||
}
|
||||
if new_text.is_empty() {
|
||||
self.buffer.replace(range_utf16, "");
|
||||
} else {
|
||||
self.buffer
|
||||
.mark(range_utf16, new_text, new_selected_range_utf16);
|
||||
}
|
||||
self.emit_change(window, cx);
|
||||
self.notify_changed(window, cx);
|
||||
}
|
||||
|
||||
fn bounds_for_range(
|
||||
&mut self,
|
||||
range_utf16: Range<usize>,
|
||||
bounds: Bounds<Pixels>,
|
||||
window: &mut Window,
|
||||
_: &mut Context<Self>,
|
||||
) -> Option<Bounds<Pixels>> {
|
||||
Some(self.line(bounds, window).range_bounds(range_utf16))
|
||||
}
|
||||
|
||||
fn character_index_for_point(
|
||||
&mut self,
|
||||
point: Point<Pixels>,
|
||||
window: &mut Window,
|
||||
_: &mut Context<Self>,
|
||||
) -> Option<usize> {
|
||||
Some(self.line(self.bounds?, window).index_at_x(point.x))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn keyed_input(
|
||||
key: SharedString,
|
||||
snapshot: ui::SnapshotId,
|
||||
initial_text: &str,
|
||||
placeholder: &'static str,
|
||||
disabled: bool,
|
||||
palette: DesktopPalette,
|
||||
on_change: Option<InputCallback>,
|
||||
on_submit: Option<InputCallback>,
|
||||
on_cancel: Option<CancelCallback>,
|
||||
stops: &mut FocusStops,
|
||||
window: &mut Window,
|
||||
app: &mut App,
|
||||
) -> Entity<SettingsTextInput> {
|
||||
let state_key = ElementId::Name(SharedString::from(format!("{key}.state")));
|
||||
let entity = window.use_keyed_state(state_key, app, |_, cx| {
|
||||
SettingsTextInput::new(
|
||||
ElementId::Name(key),
|
||||
snapshot,
|
||||
initial_text.to_owned(),
|
||||
placeholder,
|
||||
palette,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
entity.update(app, |input, _| {
|
||||
input.sync(
|
||||
initial_text,
|
||||
disabled,
|
||||
palette,
|
||||
on_change,
|
||||
on_submit,
|
||||
on_cancel,
|
||||
window,
|
||||
);
|
||||
input.register_stop(stops);
|
||||
});
|
||||
entity
|
||||
}
|
||||
@@ -0,0 +1,608 @@
|
||||
//! Workspace preference, template, backup export, and deletion pages for `SettingsModal`.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use ui::{
|
||||
App, Div, Entity, FocusHandle, FontWeight, InteractiveElement, KeyDownEvent, MouseButton,
|
||||
ParentElement, SharedString, StatefulInteractiveElement, Styled, Window, div, px, svg,
|
||||
};
|
||||
use ui_tokens::{ThemeMode, icons};
|
||||
|
||||
use super::{
|
||||
MODAL_ID, SettingsModal, WorkspaceSummary,
|
||||
controls::{FocusStops, control_row, description_text, focus_stop, section, value_row},
|
||||
i18n::strings_for,
|
||||
template_picker::{TemplateTarget, menu_state, template_selector, toggle_switch},
|
||||
text_input::keyed_input,
|
||||
};
|
||||
use crate::{
|
||||
DesktopFlexExt, DesktopPalette,
|
||||
confirm_modal::{
|
||||
ConfirmAction, ConfirmFocus, ConfirmIds, ConfirmKey, ConfirmModal, OverlayScroll,
|
||||
confirm_key, float_confirm,
|
||||
},
|
||||
workbench::DesktopShellView,
|
||||
};
|
||||
|
||||
const WORKSPACE_NAME_INPUT_ID: &str = "desktop.settings.preference.workspace_name";
|
||||
const SAVE_NAME_ID: &str = "desktop.settings.preference.save_name";
|
||||
const JOURNAL_TEMPLATE_ID: &str = "desktop.settings.preference.journal_template";
|
||||
const PAGE_TEMPLATE_TOGGLE_ID: &str = "desktop.settings.preference.page_template_toggle";
|
||||
const PAGE_TEMPLATE_ID: &str = "desktop.settings.preference.page_template";
|
||||
const CURRENT_DOC_TEMPLATE_ID: &str = "desktop.settings.preference.current_doc_template";
|
||||
const DELETE_WORKSPACE_ID: &str = "desktop.settings.preference.delete_workspace";
|
||||
|
||||
pub(super) struct DeleteWorkspacePrompt {
|
||||
pub(super) open: bool,
|
||||
pub(super) focus: FocusHandle,
|
||||
pub(super) buttons: ConfirmFocus,
|
||||
pub(super) scroll: OverlayScroll,
|
||||
pub(super) opener: Option<FocusHandle>,
|
||||
}
|
||||
|
||||
impl DeleteWorkspacePrompt {
|
||||
pub(super) fn keyed(window: &mut Window, app: &mut App) -> Entity<Self> {
|
||||
window.use_keyed_state("desktop.settings.delete_workspace.prompt", app, |_, cx| {
|
||||
Self {
|
||||
open: false,
|
||||
focus: cx.focus_handle(),
|
||||
buttons: ConfirmFocus::new(cx),
|
||||
scroll: OverlayScroll::default(),
|
||||
opener: None,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn open_with(
|
||||
prompt: &Entity<Self>,
|
||||
writable: bool,
|
||||
opener: FocusHandle,
|
||||
window: &mut Window,
|
||||
app: &mut App,
|
||||
) {
|
||||
let initial = prompt.update(app, |state, cx| {
|
||||
state.open = true;
|
||||
state.opener = Some(opener);
|
||||
state.scroll = OverlayScroll::default();
|
||||
cx.notify();
|
||||
state.buttons.initial(writable).clone()
|
||||
});
|
||||
window.focus(&initial, app);
|
||||
}
|
||||
|
||||
pub(super) fn close(prompt: &Entity<Self>, window: &mut Window, app: &mut App) {
|
||||
let opener = prompt.update(app, |state, cx| {
|
||||
state.open = false;
|
||||
cx.notify();
|
||||
state.opener.take()
|
||||
});
|
||||
if let Some(handle) = opener {
|
||||
window.focus(&handle, app);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SettingsModal {
|
||||
pub(super) fn workspace_preference_sections(
|
||||
&self,
|
||||
stacked: bool,
|
||||
stops: &mut FocusStops,
|
||||
window: &mut Window,
|
||||
app: &mut App,
|
||||
) -> Vec<Div> {
|
||||
let shell_read = self.shell.read(app);
|
||||
let state = shell_read.state();
|
||||
let workspace = WorkspaceSummary::of(shell_read);
|
||||
let readonly = state.store.is_readonly_sqlite();
|
||||
let mode = state.theme;
|
||||
let palette = self.palette;
|
||||
let t = strings_for(&state.display_language);
|
||||
let template_settings = state.store.template_settings();
|
||||
let template_docs: Vec<(String, String)> = state
|
||||
.store
|
||||
.template_docs()
|
||||
.into_iter()
|
||||
.map(|doc| {
|
||||
let title = if doc.title.trim().is_empty() {
|
||||
t.untitled.to_owned()
|
||||
} else {
|
||||
doc.title.clone()
|
||||
};
|
||||
(doc.id.clone(), title)
|
||||
})
|
||||
.collect();
|
||||
let active_doc = state
|
||||
.split
|
||||
.active()
|
||||
.active_route()
|
||||
.doc_id()
|
||||
.and_then(|id| state.store.get_doc(id))
|
||||
.filter(|entry| !entry.meta.trashed)
|
||||
.map(|entry| {
|
||||
let title = if entry.meta.title.trim().is_empty() {
|
||||
t.untitled.to_owned()
|
||||
} else {
|
||||
entry.meta.title.clone()
|
||||
};
|
||||
(
|
||||
entry.meta.id.clone(),
|
||||
title,
|
||||
state.store.doc_is_template(&entry.meta.id),
|
||||
)
|
||||
});
|
||||
|
||||
let name_shell_submit = self.shell.downgrade();
|
||||
let name_shell_change = self.shell.downgrade();
|
||||
let name_input = keyed_input(
|
||||
SharedString::new_static(WORKSPACE_NAME_INPUT_ID),
|
||||
ui::snap_id!("{WORKSPACE_NAME_INPUT_ID}"),
|
||||
&workspace.name,
|
||||
t.workspace_name_placeholder,
|
||||
readonly,
|
||||
palette,
|
||||
Some(Rc::new(move |_, _, app| {
|
||||
let _ = name_shell_change.update(app, |_, cx| cx.notify());
|
||||
})),
|
||||
Some(Rc::new(move |value, _, app| {
|
||||
let _ = name_shell_submit.update(app, |view, cx| {
|
||||
view.rename_active_workspace(&value, cx);
|
||||
});
|
||||
})),
|
||||
None,
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
);
|
||||
let input_text = name_input.read(app).text().to_owned();
|
||||
let trimmed = input_text.trim().to_owned();
|
||||
let dirty = !readonly && !trimmed.is_empty() && trimmed != workspace.name;
|
||||
let initial: String = workspace
|
||||
.name
|
||||
.trim()
|
||||
.chars()
|
||||
.next()
|
||||
.map_or_else(|| "?".into(), |ch| ch.to_uppercase().collect());
|
||||
|
||||
let mut profile_row = div()
|
||||
.flex()
|
||||
.flex_wrap()
|
||||
.items_center()
|
||||
.gap(px(16.0))
|
||||
.child(
|
||||
div()
|
||||
.size(px(56.0))
|
||||
.flex_shrink(0.0)
|
||||
.rounded(px(8.0))
|
||||
.bg(palette.accent)
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.text_size(px(22.0))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(ui::white())
|
||||
.child(initial),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(6.0))
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(12.0))
|
||||
.text_color(palette.text_secondary)
|
||||
.child(t.workspace_name),
|
||||
)
|
||||
.child({
|
||||
let mut input_line = div().flex().items_center().gap(px(10.0)).flex_wrap();
|
||||
let mut input_wrap = div().w(px(240.0)).min_w_0();
|
||||
input_wrap.style().max_size.width = Some(ui::relative(1.0).into());
|
||||
input_line = input_line.child(input_wrap.child(name_input.clone()));
|
||||
if dirty {
|
||||
let stop = focus_stop(SAVE_NAME_ID, stops, window, app);
|
||||
let focused = stop.handle.is_focused(window);
|
||||
let keyboard = window.last_input_was_keyboard();
|
||||
let click_focus = stop.handle.clone();
|
||||
let save_shell = self.shell.downgrade();
|
||||
let save_input = name_input.clone();
|
||||
let key_shell = self.shell.downgrade();
|
||||
let key_input = name_input.clone();
|
||||
let key_stop = stop.clone();
|
||||
input_line = input_line.child(
|
||||
div()
|
||||
.id(SAVE_NAME_ID)
|
||||
.snapshot(SAVE_NAME_ID, Some(MODAL_ID))
|
||||
.snapshot_focused(focused)
|
||||
.track_focus(&stop.handle)
|
||||
.relative()
|
||||
.h(px(32.0))
|
||||
.px(px(12.0))
|
||||
.rounded(px(8.0))
|
||||
.bg(palette.accent)
|
||||
.hover(move |s| s.bg(palette.accent.opacity(0.88)))
|
||||
.border_1()
|
||||
.border_color(if focused && keyboard {
|
||||
palette.text_primary
|
||||
} else {
|
||||
ui::transparent_black()
|
||||
})
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.text_size(px(12.0))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(ui::white())
|
||||
.on_mouse_down(MouseButton::Left, move |_, window, app| {
|
||||
window.focus(&click_focus, app);
|
||||
})
|
||||
.on_click(move |_, _, app| {
|
||||
let value = save_input.read(app).text().to_owned();
|
||||
let renamed = save_shell
|
||||
.update(app, |view, cx| {
|
||||
view.rename_active_workspace(&value, cx)
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if renamed {
|
||||
save_input.update(app, |field, cx| {
|
||||
field.commit_source(value.trim(), cx);
|
||||
});
|
||||
}
|
||||
})
|
||||
.on_key_down(move |event, window, app| {
|
||||
if matches!(event.keystroke.key.as_str(), "enter" | "space")
|
||||
&& !event.keystroke.modifiers.modified()
|
||||
{
|
||||
key_stop.reveal(window);
|
||||
let value = key_input.read(app).text().to_owned();
|
||||
let renamed = key_shell
|
||||
.update(app, |view, cx| {
|
||||
view.rename_active_workspace(&value, cx)
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if renamed {
|
||||
key_input.update(app, |field, cx| {
|
||||
field.commit_source(value.trim(), cx);
|
||||
});
|
||||
}
|
||||
window.prevent_default();
|
||||
app.stop_propagation();
|
||||
}
|
||||
})
|
||||
.child(stop.probe())
|
||||
.child(t.save),
|
||||
);
|
||||
}
|
||||
input_line
|
||||
}),
|
||||
);
|
||||
profile_row.style().max_size.width = Some(ui::relative(1.0).into());
|
||||
|
||||
let info_section = section(
|
||||
Some(t.info_section),
|
||||
[
|
||||
profile_row,
|
||||
value_row(t.sync_status, workspace.sync, palette),
|
||||
],
|
||||
palette,
|
||||
);
|
||||
|
||||
let tpl_menu = menu_state(window, app);
|
||||
let journal_picker = template_selector(
|
||||
JOURNAL_TEMPLATE_ID,
|
||||
TemplateTarget::Journal,
|
||||
template_settings.journal_template_id.as_deref(),
|
||||
&template_docs,
|
||||
readonly,
|
||||
t,
|
||||
&tpl_menu,
|
||||
&self.shell,
|
||||
palette,
|
||||
mode,
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
);
|
||||
let page_toggle = toggle_switch(
|
||||
PAGE_TEMPLATE_TOGGLE_ID,
|
||||
template_settings.enable_page_template,
|
||||
readonly,
|
||||
palette,
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
{
|
||||
let shell = self.shell.downgrade();
|
||||
Rc::new(move |next, app| {
|
||||
let _ = shell.update(app, |view, cx| {
|
||||
let mut current = view.state.store.template_settings();
|
||||
current.enable_page_template = next;
|
||||
if view.state.store.set_template_settings(current) {
|
||||
view.flush_persistence();
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
})
|
||||
},
|
||||
);
|
||||
let mut template_rows = vec![
|
||||
control_row(
|
||||
t.journal_template,
|
||||
t.journal_template_desc,
|
||||
journal_picker,
|
||||
stacked,
|
||||
palette,
|
||||
),
|
||||
control_row(
|
||||
t.page_template,
|
||||
t.page_template_desc,
|
||||
page_toggle,
|
||||
stacked,
|
||||
palette,
|
||||
),
|
||||
];
|
||||
if template_settings.enable_page_template {
|
||||
let page_picker = template_selector(
|
||||
PAGE_TEMPLATE_ID,
|
||||
TemplateTarget::Page,
|
||||
template_settings.page_template_id.as_deref(),
|
||||
&template_docs,
|
||||
readonly,
|
||||
t,
|
||||
&tpl_menu,
|
||||
&self.shell,
|
||||
palette,
|
||||
mode,
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
);
|
||||
template_rows.push(control_row(
|
||||
t.select_page_template,
|
||||
t.select_page_template_desc,
|
||||
page_picker,
|
||||
stacked,
|
||||
palette,
|
||||
));
|
||||
}
|
||||
if let Some((doc_id, doc_title, is_tpl)) = active_doc {
|
||||
let doc_toggle = toggle_switch(
|
||||
CURRENT_DOC_TEMPLATE_ID,
|
||||
is_tpl,
|
||||
readonly,
|
||||
palette,
|
||||
stops,
|
||||
window,
|
||||
app,
|
||||
{
|
||||
let shell = self.shell.downgrade();
|
||||
Rc::new(move |next, app| {
|
||||
let _ = shell.update(app, |view, cx| {
|
||||
if view.state.store.set_doc_is_template(&doc_id, next) {
|
||||
view.flush_persistence();
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
})
|
||||
},
|
||||
);
|
||||
template_rows.push(control_row(
|
||||
t.current_doc_as_template,
|
||||
t.current_doc_as_template_desc,
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(10.0))
|
||||
.child({
|
||||
let mut doc_label = div()
|
||||
.truncate()
|
||||
.text_size(px(12.0))
|
||||
.text_color(palette.text_secondary)
|
||||
.child(doc_title);
|
||||
doc_label.style().max_size.width = Some(px(150.0).into());
|
||||
doc_label
|
||||
})
|
||||
.child(doc_toggle),
|
||||
stacked,
|
||||
palette,
|
||||
));
|
||||
}
|
||||
let template_section = section(Some(t.template_section), template_rows, palette);
|
||||
|
||||
let error_fg = palette.danger;
|
||||
let delete_row = if readonly {
|
||||
div()
|
||||
.id(DELETE_WORKSPACE_ID)
|
||||
.snapshot(DELETE_WORKSPACE_ID, Some(MODAL_ID))
|
||||
.opacity(0.45)
|
||||
.cursor(ui::CursorStyle::Arrow)
|
||||
} else {
|
||||
let prompt = DeleteWorkspacePrompt::keyed(window, app);
|
||||
let stop = focus_stop(DELETE_WORKSPACE_ID, stops, window, app);
|
||||
let focused = stop.handle.is_focused(window);
|
||||
let keyboard = window.last_input_was_keyboard();
|
||||
let click_focus = stop.handle.clone();
|
||||
let click_prompt = prompt.clone();
|
||||
let click_opener = stop.handle.clone();
|
||||
let key_prompt = prompt.clone();
|
||||
let key_stop = stop.clone();
|
||||
div()
|
||||
.id(DELETE_WORKSPACE_ID)
|
||||
.snapshot(DELETE_WORKSPACE_ID, Some(MODAL_ID))
|
||||
.snapshot_focused(focused)
|
||||
.track_focus(&stop.handle)
|
||||
.relative()
|
||||
.border_1()
|
||||
.border_color(if focused && keyboard {
|
||||
palette.accent
|
||||
} else {
|
||||
ui::transparent_black()
|
||||
})
|
||||
.hover(move |s| s.bg(palette.hover_overlay))
|
||||
.cursor_pointer()
|
||||
.on_mouse_down(MouseButton::Left, move |_, window, app| {
|
||||
window.focus(&click_focus, app);
|
||||
})
|
||||
.on_click(move |_, window, app| {
|
||||
DeleteWorkspacePrompt::open_with(
|
||||
&click_prompt,
|
||||
true,
|
||||
click_opener.clone(),
|
||||
window,
|
||||
app,
|
||||
);
|
||||
})
|
||||
.on_key_down(move |event, window, app| {
|
||||
if matches!(event.keystroke.key.as_str(), "enter" | "space")
|
||||
&& !event.keystroke.modifiers.modified()
|
||||
{
|
||||
key_stop.reveal(window);
|
||||
DeleteWorkspacePrompt::open_with(
|
||||
&key_prompt,
|
||||
true,
|
||||
key_stop.handle.clone(),
|
||||
window,
|
||||
app,
|
||||
);
|
||||
window.prevent_default();
|
||||
app.stop_propagation();
|
||||
}
|
||||
})
|
||||
.child(stop.probe())
|
||||
}
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_between()
|
||||
.gap(px(12.0))
|
||||
.p(px(10.0))
|
||||
.rounded(px(8.0))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(2.0))
|
||||
.min_w_0()
|
||||
.child(
|
||||
div()
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(error_fg)
|
||||
.child(t.delete_workspace),
|
||||
)
|
||||
.child(description_text(t.delete_workspace_desc, palette)),
|
||||
)
|
||||
.child(
|
||||
svg()
|
||||
.data(icons::ARROW_RIGHT_SMALL.svg.as_bytes())
|
||||
.size(px(16.0))
|
||||
.flex_shrink(0.0)
|
||||
.text_color(palette.text_secondary),
|
||||
);
|
||||
|
||||
vec![
|
||||
info_section,
|
||||
template_section,
|
||||
section(None, [div().child(delete_row)], palette),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn render_delete_confirm_overlay(
|
||||
prompt: &Entity<DeleteWorkspacePrompt>,
|
||||
shell: &Entity<DesktopShellView>,
|
||||
palette: DesktopPalette,
|
||||
mode: ThemeMode,
|
||||
window: &Window,
|
||||
app: &App,
|
||||
) -> Option<ui::AnyElement> {
|
||||
let state = prompt.read(app);
|
||||
if !state.open {
|
||||
return None;
|
||||
}
|
||||
let shell_read = shell.read(app);
|
||||
let t = strings_for(&shell_read.state().display_language);
|
||||
let ws_name = shell_read.state.store.active_workspace().name.clone();
|
||||
let writable = !shell_read.state.store.is_readonly_sqlite();
|
||||
let dismiss: ConfirmAction = {
|
||||
let prompt = prompt.clone();
|
||||
Rc::new(move |window, app| {
|
||||
DeleteWorkspacePrompt::close(&prompt, window, app);
|
||||
})
|
||||
};
|
||||
let accept: ConfirmAction = {
|
||||
let (prompt, shell) = (prompt.clone(), shell.clone());
|
||||
Rc::new(move |window, app| {
|
||||
let deleted = shell.update(app, |view, cx| view.delete_active_workspace(cx));
|
||||
DeleteWorkspacePrompt::close(&prompt, window, app);
|
||||
if deleted {
|
||||
let _ = shell.update(app, |view, cx| view.dismiss_modal(window, cx));
|
||||
}
|
||||
})
|
||||
};
|
||||
let keys = {
|
||||
let (prompt, shell) = (prompt.clone(), shell.clone());
|
||||
move |event: &KeyDownEvent, window: &mut Window, app: &mut App| {
|
||||
let writable = !shell.read(app).state.store.is_readonly_sqlite();
|
||||
let buttons = prompt.read(app).buttons.clone();
|
||||
match confirm_key(&buttons, writable, event, window, app) {
|
||||
Some(ConfirmKey::Dismiss) => {
|
||||
DeleteWorkspacePrompt::close(&prompt, window, app);
|
||||
window.prevent_default();
|
||||
app.stop_propagation();
|
||||
}
|
||||
Some(ConfirmKey::Confirm) => {
|
||||
let deleted = shell.update(app, |view, cx| view.delete_active_workspace(cx));
|
||||
DeleteWorkspacePrompt::close(&prompt, window, app);
|
||||
if deleted {
|
||||
let _ = shell.update(app, |view, cx| view.dismiss_modal(window, cx));
|
||||
}
|
||||
window.prevent_default();
|
||||
app.stop_propagation();
|
||||
}
|
||||
None if event.keystroke.key == "tab" => {
|
||||
window.prevent_default();
|
||||
app.stop_propagation();
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
};
|
||||
let viewport = window.viewport_size();
|
||||
let card = ConfirmModal {
|
||||
ids: ConfirmIds {
|
||||
dialog: "desktop.settings.delete_workspace_confirm",
|
||||
close: "desktop.settings.delete_workspace_confirm.close",
|
||||
cancel: "desktop.settings.delete_workspace_confirm.cancel",
|
||||
confirm: "desktop.settings.delete_workspace_confirm.confirm",
|
||||
close_icon: ui::snap_id!("desktop.settings.delete_workspace_confirm.close.icon"),
|
||||
title: ui::snap_id!("desktop.settings.delete_workspace_confirm.title"),
|
||||
body: ui::snap_id!("desktop.settings.delete_workspace_confirm.body"),
|
||||
description: ui::snap_id!("desktop.settings.delete_workspace_confirm.description"),
|
||||
},
|
||||
title: t.delete_workspace_title.into(),
|
||||
description: t.delete_workspace_confirm_desc(&ws_name).into(),
|
||||
confirm_label: t.delete,
|
||||
writable,
|
||||
focus: &state.buttons,
|
||||
scroll: &state.scroll,
|
||||
entity: shell.entity_id(),
|
||||
viewport: (viewport.width.into(), viewport.height.into()),
|
||||
theme: mode,
|
||||
palette,
|
||||
dismiss: dismiss.clone(),
|
||||
confirm: accept,
|
||||
}
|
||||
.render(Some(window));
|
||||
let layer = div()
|
||||
.id("desktop.settings.delete_workspace_confirm.layer")
|
||||
.track_focus(&state.focus)
|
||||
.capture_key_down(keys);
|
||||
Some(float_confirm(
|
||||
layer,
|
||||
"desktop.settings.delete_workspace_confirm.backdrop",
|
||||
card,
|
||||
(palette, viewport),
|
||||
&dismiss,
|
||||
))
|
||||
}
|
||||
@@ -14,7 +14,7 @@ use std::{
|
||||
use affine_client::{LinkGraph, WeightedSearchEngine};
|
||||
use affine_store::{
|
||||
sqlite::SqliteDocStorage,
|
||||
workspace_db::{WorkspaceDb, WorkspaceDbTableName},
|
||||
workspace_db::{UserdataTableName, WorkspaceDb, WorkspaceDbTableName},
|
||||
};
|
||||
use anyhow::{Context as _, Result};
|
||||
use blocksuite_playground_doc::try_random_client_id;
|
||||
@@ -24,7 +24,13 @@ use crate::doc_store::{
|
||||
load_workspace,
|
||||
};
|
||||
|
||||
type WorkspaceOpenPayload = (String, Vec<u8>, Vec<(WorkspaceDbTableName, Vec<u8>)>, usize);
|
||||
type WorkspaceOpenPayload = (
|
||||
String,
|
||||
Vec<u8>,
|
||||
Vec<(WorkspaceDbTableName, Vec<u8>)>,
|
||||
Option<Vec<u8>>,
|
||||
usize,
|
||||
);
|
||||
|
||||
enum SqliteWorkerReq {
|
||||
OpenWorkspace {
|
||||
@@ -37,6 +43,16 @@ enum SqliteWorkerReq {
|
||||
opens: Arc<AtomicU64>,
|
||||
reply: mpsc::Sender<Result<Option<Vec<u8>>>>,
|
||||
},
|
||||
ListDocIds {
|
||||
path: PathBuf,
|
||||
opens: Arc<AtomicU64>,
|
||||
reply: mpsc::Sender<Result<Vec<String>>>,
|
||||
},
|
||||
LoadAllBlobs {
|
||||
path: PathBuf,
|
||||
opens: Arc<AtomicU64>,
|
||||
reply: mpsc::Sender<Result<Vec<(String, String, Vec<u8>)>>>,
|
||||
},
|
||||
/// The last handle of a backing went away: close its read connection.
|
||||
Release { opens: Arc<AtomicU64> },
|
||||
}
|
||||
@@ -71,6 +87,7 @@ async fn read_workspace_snapshot(storage: &SqliteDocStorage) -> Result<Workspace
|
||||
WorkspaceDbTableName::Folders,
|
||||
WorkspaceDbTableName::DocProperties,
|
||||
WorkspaceDbTableName::DocCustomPropertyInfo,
|
||||
WorkspaceDbTableName::PinnedCollections,
|
||||
] {
|
||||
let doc_id = table.local_doc_id();
|
||||
if let Some(rec) = storage
|
||||
@@ -82,7 +99,35 @@ async fn read_workspace_snapshot(storage: &SqliteDocStorage) -> Result<Workspace
|
||||
db_tables.push((table, rec.bin));
|
||||
}
|
||||
}
|
||||
Ok((space_id, root_bytes, db_tables, blobs.len()))
|
||||
let doc_ids = storage.list_doc_ids().await.unwrap_or_default();
|
||||
let mut settings_id = doc_ids
|
||||
.into_iter()
|
||||
.find(|id| id.starts_with("userdata$") && id.ends_with("$settings"));
|
||||
if settings_id.is_none() {
|
||||
for candidate in ["userdata$local-user$settings", "userdata$u-demo$settings"] {
|
||||
if let Ok(Some(rec)) = storage.get_doc_readonly(candidate).await
|
||||
&& !rec.bin.is_empty()
|
||||
{
|
||||
return Ok((space_id, root_bytes, db_tables, Some(rec.bin), blobs.len()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let userdata_settings = if let Some(id) = settings_id.take() {
|
||||
storage
|
||||
.get_doc_readonly(&id)
|
||||
.await?
|
||||
.map(|rec| rec.bin)
|
||||
.filter(|b| !b.is_empty())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok((
|
||||
space_id,
|
||||
root_bytes,
|
||||
db_tables,
|
||||
userdata_settings,
|
||||
blobs.len(),
|
||||
))
|
||||
}
|
||||
|
||||
fn is_readonly_shm_error(err: &anyhow::Error) -> bool {
|
||||
@@ -157,14 +202,17 @@ async fn read_doc(storage: &SqliteDocStorage, doc_id: &str) -> Result<Option<Vec
|
||||
.map_err(anyhow::Error::from)
|
||||
}
|
||||
|
||||
/// Read one document through the cached read connection of `path`, opening it first when the
|
||||
/// cache holds another file or a stale identity of this one.
|
||||
async fn load_doc(
|
||||
async fn with_read_connection<T, F>(
|
||||
cached: &mut Option<ReadConnection>,
|
||||
path: &Path,
|
||||
doc_id: &str,
|
||||
opens: &Arc<AtomicU64>,
|
||||
) -> Result<Option<Vec<u8>>> {
|
||||
op: F,
|
||||
) -> Result<T>
|
||||
where
|
||||
F: for<'a> Fn(
|
||||
&'a SqliteDocStorage,
|
||||
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<T>> + 'a>>,
|
||||
{
|
||||
let canonical = std::fs::canonicalize(path)
|
||||
.with_context(|| format!("canonicalizing SQLite path `{}`", path.display()))?;
|
||||
let identity = FileIdentity::of(&canonical)?;
|
||||
@@ -185,8 +233,8 @@ async fn load_doc(
|
||||
immutable: false,
|
||||
}
|
||||
});
|
||||
match read_doc(&conn.storage, doc_id).await {
|
||||
Ok(bytes) => Ok(bytes),
|
||||
match op(&conn.storage).await {
|
||||
Ok(value) => Ok(value),
|
||||
Err(err) if !conn.immutable && is_readonly_shm_error(&err) => {
|
||||
close_connection(cached).await;
|
||||
let storage = SqliteDocStorage::open_backup_immutable(path_str)?;
|
||||
@@ -198,7 +246,7 @@ async fn load_doc(
|
||||
storage,
|
||||
immutable: true,
|
||||
});
|
||||
let res = read_doc(&conn.storage, doc_id).await;
|
||||
let res = op(&conn.storage).await;
|
||||
if res.is_err() {
|
||||
close_connection(cached).await;
|
||||
}
|
||||
@@ -211,6 +259,59 @@ async fn load_doc(
|
||||
}
|
||||
}
|
||||
|
||||
/// Read one document through the cached read connection of `path`, opening it first when the
|
||||
/// cache holds another file or a stale identity of this one.
|
||||
async fn load_doc(
|
||||
cached: &mut Option<ReadConnection>,
|
||||
path: &Path,
|
||||
doc_id: &str,
|
||||
opens: &Arc<AtomicU64>,
|
||||
) -> Result<Option<Vec<u8>>> {
|
||||
let doc_id = doc_id.to_owned();
|
||||
with_read_connection(cached, path, opens, move |storage| {
|
||||
let doc_id = doc_id.clone();
|
||||
Box::pin(async move { read_doc(storage, &doc_id).await })
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn read_all_blobs(storage: &SqliteDocStorage) -> Result<Vec<(String, String, Vec<u8>)>> {
|
||||
let listed = storage.list_blobs().await?;
|
||||
let mut out = Vec::with_capacity(listed.len());
|
||||
for entry in listed {
|
||||
if let Some(rec) = storage.get_blob(&entry.key).await? {
|
||||
out.push((rec.key, rec.mime, rec.data));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
async fn read_doc_ids(storage: &SqliteDocStorage) -> Result<Vec<String>> {
|
||||
Ok(storage.list_doc_ids().await?)
|
||||
}
|
||||
|
||||
async fn load_all_blobs(
|
||||
cached: &mut Option<ReadConnection>,
|
||||
path: &Path,
|
||||
opens: &Arc<AtomicU64>,
|
||||
) -> Result<Vec<(String, String, Vec<u8>)>> {
|
||||
with_read_connection(cached, path, opens, |storage| {
|
||||
Box::pin(read_all_blobs(storage))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn list_doc_ids(
|
||||
cached: &mut Option<ReadConnection>,
|
||||
path: &Path,
|
||||
opens: &Arc<AtomicU64>,
|
||||
) -> Result<Vec<String>> {
|
||||
with_read_connection(cached, path, opens, |storage| {
|
||||
Box::pin(read_doc_ids(storage))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
static SQLITE_WORKER: OnceLock<std::result::Result<mpsc::Sender<SqliteWorkerReq>, String>> =
|
||||
OnceLock::new();
|
||||
|
||||
@@ -250,6 +351,14 @@ fn sqlite_worker() -> Result<&'static mpsc::Sender<SqliteWorkerReq>> {
|
||||
rt.block_on(load_doc(&mut cached, &path, &doc_id, &opens));
|
||||
let _ = reply.send(res);
|
||||
}
|
||||
SqliteWorkerReq::ListDocIds { path, opens, reply } => {
|
||||
let res = rt.block_on(list_doc_ids(&mut cached, &path, &opens));
|
||||
let _ = reply.send(res);
|
||||
}
|
||||
SqliteWorkerReq::LoadAllBlobs { path, opens, reply } => {
|
||||
let res = rt.block_on(load_all_blobs(&mut cached, &path, &opens));
|
||||
let _ = reply.send(res);
|
||||
}
|
||||
SqliteWorkerReq::Release { opens } => {
|
||||
if cached
|
||||
.as_ref()
|
||||
@@ -345,6 +454,34 @@ impl SqliteLazyBacking {
|
||||
.recv()
|
||||
.context("receiving sqlite doc hydration reply")?
|
||||
}
|
||||
|
||||
pub fn list_doc_ids(&self) -> Result<Vec<String>> {
|
||||
let (reply_tx, reply_rx) = mpsc::channel();
|
||||
sqlite_worker()?
|
||||
.send(SqliteWorkerReq::ListDocIds {
|
||||
path: self.path.clone(),
|
||||
opens: Arc::clone(&self.lease.opens),
|
||||
reply: reply_tx,
|
||||
})
|
||||
.map_err(|_| anyhow::anyhow!("sqlite read-only worker channel closed"))?;
|
||||
reply_rx
|
||||
.recv()
|
||||
.context("receiving sqlite doc id list reply")?
|
||||
}
|
||||
|
||||
pub fn load_all_blobs(&self) -> Result<Vec<(String, String, Vec<u8>)>> {
|
||||
let (reply_tx, reply_rx) = mpsc::channel();
|
||||
sqlite_worker()?
|
||||
.send(SqliteWorkerReq::LoadAllBlobs {
|
||||
path: self.path.clone(),
|
||||
opens: Arc::clone(&self.lease.opens),
|
||||
reply: reply_tx,
|
||||
})
|
||||
.map_err(|_| anyhow::anyhow!("sqlite read-only worker channel closed"))?;
|
||||
reply_rx
|
||||
.recv()
|
||||
.context("receiving sqlite blob export reply")?
|
||||
}
|
||||
}
|
||||
|
||||
/// Summary metrics produced when opening a real SQLite workspace (strictly privacy-safe counts).
|
||||
@@ -376,7 +513,7 @@ pub fn open_sqlite_workspace(path: impl AsRef<Path>) -> Result<(DesktopDocStore,
|
||||
reply: reply_tx,
|
||||
})
|
||||
.map_err(|_| anyhow::anyhow!("sqlite read-only worker channel closed"))?;
|
||||
let (space_id, root_bytes, db_tables, blob_count) = reply_rx
|
||||
let (space_id, root_bytes, db_tables, userdata_settings, blob_count) = reply_rx
|
||||
.recv()
|
||||
.context("receiving sqlite workspace open reply")??;
|
||||
|
||||
@@ -405,6 +542,10 @@ pub fn open_sqlite_workspace(path: impl AsRef<Path>) -> Result<(DesktopDocStore,
|
||||
)
|
||||
})?;
|
||||
}
|
||||
if let Some(bytes) = &userdata_settings {
|
||||
db.load_userdata_table(UserdataTableName::Settings, bytes)
|
||||
.context("failed to decode SQLite workspace settings table")?;
|
||||
}
|
||||
let pending_writebacks = db.pending_updates().len();
|
||||
let LoadedWorkspace {
|
||||
directory,
|
||||
|
||||
@@ -107,6 +107,8 @@ pub struct DesktopAppState {
|
||||
pub theme: ThemeMode,
|
||||
pub theme_preference: ThemePreference,
|
||||
pub system_theme: ThemeMode,
|
||||
pub display_language: String,
|
||||
pub(crate) prefs_path: Option<std::path::PathBuf>,
|
||||
pub default_doc_mode: DocMode,
|
||||
pub editor_font: EditorFontPreferences,
|
||||
pub today_date: String,
|
||||
@@ -254,11 +256,19 @@ impl DesktopAppState {
|
||||
ThemeMode::Light => ThemePreference::Light,
|
||||
ThemeMode::Dark => ThemePreference::Dark,
|
||||
};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let prefs_path = None;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let prefs_path = crate::workbench::preferences::default_prefs_path();
|
||||
let display_language =
|
||||
crate::workbench::preferences::load_language_from(prefs_path.as_deref());
|
||||
|
||||
Self {
|
||||
theme,
|
||||
theme_preference,
|
||||
system_theme: theme,
|
||||
display_language,
|
||||
prefs_path,
|
||||
default_doc_mode: DocMode::Page,
|
||||
editor_font: EditorFontPreferences::default(),
|
||||
today_date: today_date.to_string(),
|
||||
@@ -317,6 +327,12 @@ impl DesktopAppState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bind an explicit JSON preferences file path and reload `display_language` from it.
|
||||
pub fn bind_prefs_path(&mut self, path: std::path::PathBuf) {
|
||||
self.display_language = crate::workbench::preferences::load_language_from(Some(&path));
|
||||
self.prefs_path = Some(path);
|
||||
}
|
||||
|
||||
pub(crate) fn current_scope(&self) -> Scope {
|
||||
Scope::new(
|
||||
"local-user",
|
||||
|
||||
@@ -327,6 +327,12 @@ mod web_store {
|
||||
|
||||
#[wasm_bindgen(method, js_name = reportError)]
|
||||
pub fn report_error(this: &WebDesktopStore, message: &str);
|
||||
|
||||
#[wasm_bindgen(method, catch, js_name = deleteWorkspace)]
|
||||
fn delete_workspace(
|
||||
this: &WebDesktopStore,
|
||||
workspace_id: &str,
|
||||
) -> Result<(), wasm_bindgen::JsValue>;
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
@@ -349,10 +355,12 @@ mod web_store {
|
||||
});
|
||||
}
|
||||
|
||||
const WORKSPACE_REGISTRY_KEY: &str = "affine.desktop.workspaceRegistry";
|
||||
|
||||
impl WebDesktopStore {
|
||||
/// The update frames that the store held at startup for each of `workspace_ids`.
|
||||
pub fn stored_workspaces(&self, workspace_ids: &[String]) -> StoredWorkspaces {
|
||||
workspace_ids
|
||||
let mut stored: StoredWorkspaces = workspace_ids
|
||||
.iter()
|
||||
.map(|ws| {
|
||||
let docs = self
|
||||
@@ -369,12 +377,30 @@ mod web_store {
|
||||
.collect();
|
||||
(ws.clone(), docs)
|
||||
})
|
||||
.collect()
|
||||
.collect();
|
||||
if let Some(raw) = super::web_local_storage_get(WORKSPACE_REGISTRY_KEY) {
|
||||
stored.insert(
|
||||
crate::workbench::LOCAL_REGISTRY_WORKSPACE_ID.to_owned(),
|
||||
std::collections::BTreeMap::from([(
|
||||
"workspaces".to_owned(),
|
||||
vec![raw.into_bytes()],
|
||||
)]),
|
||||
);
|
||||
}
|
||||
stored
|
||||
}
|
||||
}
|
||||
|
||||
impl LocalDocStore for WebDesktopStore {
|
||||
fn push_update(&self, workspace_id: &str, doc_id: &str, update: Vec<u8>) {
|
||||
if workspace_id == crate::workbench::LOCAL_REGISTRY_WORKSPACE_ID
|
||||
&& doc_id == "workspaces"
|
||||
{
|
||||
if let Ok(json) = std::str::from_utf8(&update) {
|
||||
super::web_local_storage_set(WORKSPACE_REGISTRY_KEY, json);
|
||||
}
|
||||
return;
|
||||
}
|
||||
WebDesktopStore::push_update(self, workspace_id, doc_id, update);
|
||||
}
|
||||
|
||||
@@ -382,6 +408,10 @@ mod web_store {
|
||||
WebDesktopStore::delete_doc(self, workspace_id, doc_id);
|
||||
}
|
||||
|
||||
fn clear_workspace_blobs(&self, workspace_id: &str) {
|
||||
let _ = WebDesktopStore::delete_workspace(self, workspace_id);
|
||||
}
|
||||
|
||||
fn load_blobs(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
@@ -535,6 +565,18 @@ fn system_theme(dark: bool) -> ThemeMode {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
#[wasm_bindgen::prelude::wasm_bindgen]
|
||||
pub fn web_desktop_workspace_ids() -> Vec<String> {
|
||||
if let Some(raw) = web_local_storage_get("affine.desktop.workspaceRegistry")
|
||||
&& let Ok(entries) = serde_json::from_str::<Vec<serde_json::Value>>(&raw)
|
||||
{
|
||||
let ids: Vec<String> = entries
|
||||
.into_iter()
|
||||
.filter_map(|v| v.get("id")?.as_str().map(str::to_owned))
|
||||
.filter(|id| !id.is_empty())
|
||||
.collect();
|
||||
if !ids.is_empty() {
|
||||
return ids;
|
||||
}
|
||||
}
|
||||
crate::showcase::SHOWCASE_WORKSPACE_IDS
|
||||
.map(str::to_owned)
|
||||
.to_vec()
|
||||
|
||||
@@ -326,14 +326,7 @@ impl DesktopShellView {
|
||||
cx.stop_propagation();
|
||||
}
|
||||
} else if matches!(self.state.modal, Some(DesktopModal::Settings)) {
|
||||
let m = &event.keystroke.modifiers;
|
||||
let plain = !m.control && !m.alt && !m.platform;
|
||||
if (matches!(
|
||||
event.keystroke.key.as_str(),
|
||||
"left" | "down" | "right" | "up" | "home" | "end" | "enter" | "space"
|
||||
) && !m.modified())
|
||||
|| (event.keystroke.key == "tab" && plain)
|
||||
{
|
||||
if self.settings_focus.contains_focused(window, cx) {
|
||||
return;
|
||||
}
|
||||
if event.keystroke.key == "escape" {
|
||||
|
||||
@@ -18,22 +18,20 @@ use std::{
|
||||
};
|
||||
|
||||
use affine_client::{HostKind, WorkspaceSession};
|
||||
use affine_store::{
|
||||
directory::WorkspaceDirectory,
|
||||
workspace_db::{PendingDocUpdate, WorkspaceDb, WorkspaceDbTableName},
|
||||
use affine_store::workspace_db::{
|
||||
PendingDocUpdate, UserdataTableName, WorkspaceDb, WorkspaceDbTableName,
|
||||
};
|
||||
use anyhow::{Context as _, Result, anyhow};
|
||||
use blocksuite_playground_doc::{session::PageDocSession, try_random_client_id};
|
||||
use ui::{Context, Entity};
|
||||
use ui_tokens::ThemeMode;
|
||||
|
||||
use super::{DesktopAppState, DesktopShellView, topbar::SavedTabs};
|
||||
use super::{DesktopAppState, DesktopShellView, registry, topbar::SavedTabs};
|
||||
use crate::{
|
||||
doc_store::{
|
||||
DesktopDocStore, ExplorerPrefsStore, LoadedWorkspace, PendingUpdates, SessionWriter,
|
||||
load_workspace, merge_pending_updates,
|
||||
},
|
||||
showcase::SHOWCASE_WORKSPACE_ID,
|
||||
split_view::DesktopRoute,
|
||||
};
|
||||
|
||||
@@ -82,34 +80,50 @@ pub trait LocalDocStore {
|
||||
|
||||
/// Ask a host with asynchronous writes to retry its pending blob writes.
|
||||
fn retry_blob_writes(&self) {}
|
||||
|
||||
/// Remember the app tabs of workspace `workspace_id`, as JSON.
|
||||
fn set_tabs(&self, _workspace_id: &str, _tabs: &str) {}
|
||||
|
||||
/// The app tabs that [`LocalDocStore::set_tabs`] remembered for workspace `workspace_id`.
|
||||
fn tabs(&self, _workspace_id: &str) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Remember the explorer display preferences of workspace `workspace_id`, as JSON.
|
||||
fn set_explorer_prefs(&self, _workspace_id: &str, _prefs: &str) {}
|
||||
|
||||
/// The explorer display preferences that [`LocalDocStore::set_explorer_prefs`] remembered
|
||||
/// for workspace `workspace_id`.
|
||||
fn explorer_prefs(&self, _workspace_id: &str) -> Option<String> {
|
||||
None
|
||||
}
|
||||
/// Remove stored media blobs and workspace-scoped records kept for `workspace_id`.
|
||||
fn clear_workspace_blobs(&self, _workspace_id: &str) {}
|
||||
}
|
||||
|
||||
struct LocalSession {
|
||||
session: Arc<Mutex<WorkspaceSession>>,
|
||||
pending: PendingUpdates,
|
||||
blobs: RefCell<LocalBlobs>,
|
||||
pub(super) struct LocalSession {
|
||||
pub(super) session: Arc<Mutex<WorkspaceSession>>,
|
||||
pub(super) pending: PendingUpdates,
|
||||
pub(super) blobs: RefCell<LocalBlobs>,
|
||||
// Document writes that wait for the media writes of the workspace, one entry per
|
||||
// document in the order of its first write.
|
||||
deferred: RefCell<Vec<DeferredDoc>>,
|
||||
}
|
||||
|
||||
impl LocalSession {
|
||||
pub(super) fn new(session: WorkspaceSession, submitted: StoredBlobs) -> Self {
|
||||
Self {
|
||||
session: Arc::new(Mutex::new(session)),
|
||||
pending: PendingUpdates::default(),
|
||||
blobs: RefCell::new(LocalBlobs {
|
||||
submitted: submitted
|
||||
.iter()
|
||||
.map(|(source, bytes)| (source.clone(), Arc::downgrade(bytes)))
|
||||
.collect(),
|
||||
pending: StoredBlobs::new(),
|
||||
paused: false,
|
||||
}),
|
||||
deferred: RefCell::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A queued deletion followed by the updates that came after it.
|
||||
struct DeferredDoc {
|
||||
doc_id: String,
|
||||
@@ -191,7 +205,7 @@ fn defer_writes(
|
||||
}
|
||||
}
|
||||
|
||||
struct LocalBlobs {
|
||||
pub(super) struct LocalBlobs {
|
||||
// The host may still have this data in its write queue. The editor host keeps the
|
||||
// current bytes of each source, so a replaced or dropped buffer is freed at once.
|
||||
submitted: BTreeMap<String, Weak<Vec<u8>>>,
|
||||
@@ -210,8 +224,8 @@ impl LocalBlobs {
|
||||
|
||||
/// The sessions of the local workspaces and the store that keeps them.
|
||||
pub struct LocalWorkspaces {
|
||||
store: Rc<dyn LocalDocStore>,
|
||||
sessions: BTreeMap<String, LocalSession>,
|
||||
pub(super) store: Rc<dyn LocalDocStore>,
|
||||
pub(super) sessions: RefCell<BTreeMap<String, LocalSession>>,
|
||||
now_ms: Box<dyn Fn() -> i64>,
|
||||
}
|
||||
|
||||
@@ -219,14 +233,15 @@ impl LocalWorkspaces {
|
||||
/// Flush queued changes now, including writes that paused after a failure.
|
||||
pub fn save(&self) {
|
||||
self.save_queued(true);
|
||||
if !self.sessions.is_empty() {
|
||||
if !self.sessions.borrow().is_empty() {
|
||||
self.store.retry_blob_writes();
|
||||
}
|
||||
}
|
||||
|
||||
fn save_queued(&self, flush: bool) {
|
||||
let now_ms = (self.now_ms)();
|
||||
for (workspace_id, local) in &self.sessions {
|
||||
let sessions = self.sessions.borrow();
|
||||
for (workspace_id, local) in sessions.iter() {
|
||||
let (updates, deleted) = {
|
||||
let mut session = local.session.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if merge_pending_updates(&local.pending, &mut session, now_ms).is_err() {
|
||||
@@ -289,7 +304,7 @@ impl LocalWorkspaces {
|
||||
}
|
||||
|
||||
pub(crate) fn record_blob(&self, workspace_id: &str, blob_id: String, bytes: Arc<Vec<u8>>) {
|
||||
if let Some(local) = self.sessions.get(workspace_id) {
|
||||
if let Some(local) = self.sessions.borrow().get(workspace_id) {
|
||||
let mut blobs = local.blobs.borrow_mut();
|
||||
let queued = match blobs.pending.get(&blob_id) {
|
||||
Some(pending) => *pending == bytes,
|
||||
@@ -304,7 +319,8 @@ impl LocalWorkspaces {
|
||||
}
|
||||
|
||||
fn writer(&self, workspace_id: &str) -> Option<SessionWriter> {
|
||||
let local = self.sessions.get(workspace_id)?;
|
||||
let sessions = self.sessions.borrow();
|
||||
let local = sessions.get(workspace_id)?;
|
||||
Some(SessionWriter::new(
|
||||
workspace_id,
|
||||
local.session.clone(),
|
||||
@@ -318,11 +334,12 @@ impl LocalWorkspaces {
|
||||
type SavedView = (String, u64, DesktopRoute);
|
||||
|
||||
pub(super) struct LocalBinding {
|
||||
workspaces: Rc<LocalWorkspaces>,
|
||||
bound: Option<String>,
|
||||
pub(super) workspaces: Rc<LocalWorkspaces>,
|
||||
pub(super) bound: Option<String>,
|
||||
saved: Option<SavedView>,
|
||||
/// The workspace and the JSON of its app tabs at the last save.
|
||||
saved_tabs: Option<(String, String)>,
|
||||
saved_registry: Option<Vec<u8>>,
|
||||
_timer: ui::Task<()>,
|
||||
}
|
||||
|
||||
@@ -342,6 +359,7 @@ fn merge_frames<T: AsRef<[u8]>>(frames: &[T]) -> Result<Vec<u8>> {
|
||||
struct MergedWorkspace {
|
||||
root: Vec<u8>,
|
||||
tables: Vec<(WorkspaceDbTableName, Vec<u8>)>,
|
||||
userdata: Vec<(UserdataTableName, Vec<u8>)>,
|
||||
pages: BTreeMap<String, Vec<u8>>,
|
||||
}
|
||||
|
||||
@@ -360,9 +378,18 @@ impl MergedWorkspace {
|
||||
.into_iter()
|
||||
.filter_map(|table| merged.remove(&table.local_doc_id()).map(|b| (table, b)))
|
||||
.collect();
|
||||
let settings_key = merged
|
||||
.keys()
|
||||
.find(|id| id.starts_with("userdata$") && id.ends_with("$settings"))
|
||||
.cloned();
|
||||
let settings = settings_key.and_then(|key| merged.remove(&key));
|
||||
Ok(Self {
|
||||
root,
|
||||
tables,
|
||||
userdata: settings
|
||||
.map(|b| (UserdataTableName::Settings, b))
|
||||
.into_iter()
|
||||
.collect(),
|
||||
pages: merged,
|
||||
})
|
||||
}
|
||||
@@ -377,6 +404,10 @@ impl MergedWorkspace {
|
||||
tables.push((table, doc.encode_update_v1()?));
|
||||
}
|
||||
}
|
||||
let mut userdata = Vec::new();
|
||||
if let Some(doc) = db.userdata_table(UserdataTableName::Settings) {
|
||||
userdata.push((UserdataTableName::Settings, doc.encode_update_v1()?));
|
||||
}
|
||||
let mut pages = BTreeMap::new();
|
||||
for (id, entry) in &store.docs {
|
||||
pages.insert(id.clone(), entry.session.encode_update_v1()?);
|
||||
@@ -384,6 +415,7 @@ impl MergedWorkspace {
|
||||
Ok(Self {
|
||||
root,
|
||||
tables,
|
||||
userdata,
|
||||
pages,
|
||||
})
|
||||
}
|
||||
@@ -394,8 +426,18 @@ impl MergedWorkspace {
|
||||
.iter()
|
||||
.map(|(table, bytes)| (*table, bytes.as_slice()))
|
||||
.collect();
|
||||
WorkspaceDb::from_root_update_v1(space_id, "local-user", client_id, &self.root, &tables)
|
||||
.with_context(|| format!("failed to decode workspace root `{space_id}`"))
|
||||
let mut db = WorkspaceDb::from_root_update_v1(
|
||||
space_id,
|
||||
"local-user",
|
||||
client_id,
|
||||
&self.root,
|
||||
&tables,
|
||||
)
|
||||
.with_context(|| format!("failed to decode workspace root `{space_id}`"))?;
|
||||
for (table, bytes) in &self.userdata {
|
||||
db.load_userdata_table(*table, bytes)?;
|
||||
}
|
||||
Ok(db)
|
||||
}
|
||||
|
||||
/// A session that holds the root, the tables, and every page.
|
||||
@@ -421,6 +463,11 @@ impl MergedWorkspace {
|
||||
.into_iter()
|
||||
.map(|(t, b)| doc(t.local_doc_id(), b)),
|
||||
);
|
||||
out.extend(
|
||||
self.userdata
|
||||
.into_iter()
|
||||
.map(|(t, b)| doc(t.local_doc_id("local-user"), b)),
|
||||
);
|
||||
out.extend(self.pages.into_iter().map(|(id, b)| doc(id, b)));
|
||||
out
|
||||
}
|
||||
@@ -484,25 +531,14 @@ impl DesktopAppState {
|
||||
today_date: &str,
|
||||
now_ms: i64,
|
||||
) -> Result<(Self, Vec<(String, WorkspaceSession)>)> {
|
||||
let seeded = stored
|
||||
.get(SHOWCASE_WORKSPACE_ID)
|
||||
.is_none_or(|docs| docs.is_empty());
|
||||
let mut store = if seeded {
|
||||
DesktopDocStore::seed_showcase(today_date)
|
||||
} else {
|
||||
let client_id = try_random_client_id()?;
|
||||
DesktopDocStore::showcase_shell(WorkspaceDirectory::new(WorkspaceDb::new(
|
||||
SHOWCASE_WORKSPACE_ID,
|
||||
"local-user",
|
||||
client_id,
|
||||
)))
|
||||
};
|
||||
let (mut store, seeded) = registry::init_local_store(stored, today_date)?;
|
||||
let mut sessions = Vec::new();
|
||||
for index in 0..store.workspaces.len() {
|
||||
store.switch_workspace(index);
|
||||
let id = store.active_workspace().id.clone();
|
||||
let session = open_active_workspace(&mut store, stored.get(&id), now_ms)
|
||||
.with_context(|| format!("failed to open workspace `{id}`"))?;
|
||||
store.sync_active_workspace_name_from_root();
|
||||
sessions.push((id, session));
|
||||
}
|
||||
store.switch_workspace(0);
|
||||
@@ -549,28 +585,17 @@ impl DesktopShellView {
|
||||
let start = clock.now();
|
||||
let readonly = self.state.store.is_readonly_sqlite();
|
||||
let workspaces = Rc::new(LocalWorkspaces {
|
||||
sessions: sessions
|
||||
.into_iter()
|
||||
.filter(|_| !readonly)
|
||||
.map(|(id, session)| {
|
||||
let submitted = initial_blobs.remove(&id).unwrap_or_default();
|
||||
self.editor_host.seed_workspace_blobs(&id, &submitted);
|
||||
let local = LocalSession {
|
||||
session: Arc::new(Mutex::new(session)),
|
||||
pending: PendingUpdates::default(),
|
||||
blobs: RefCell::new(LocalBlobs {
|
||||
submitted: submitted
|
||||
.iter()
|
||||
.map(|(source, bytes)| (source.clone(), Arc::downgrade(bytes)))
|
||||
.collect(),
|
||||
pending: StoredBlobs::new(),
|
||||
paused: false,
|
||||
}),
|
||||
deferred: RefCell::default(),
|
||||
};
|
||||
(id, local)
|
||||
})
|
||||
.collect(),
|
||||
sessions: RefCell::new(
|
||||
sessions
|
||||
.into_iter()
|
||||
.filter(|_| !readonly)
|
||||
.map(|(id, session)| {
|
||||
let submitted = initial_blobs.remove(&id).unwrap_or_default();
|
||||
self.editor_host.seed_workspace_blobs(&id, &submitted);
|
||||
(id, LocalSession::new(session, submitted))
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
store,
|
||||
now_ms: {
|
||||
let clock = clock.clone();
|
||||
@@ -603,6 +628,7 @@ impl DesktopShellView {
|
||||
bound: None,
|
||||
saved: None,
|
||||
saved_tabs: None,
|
||||
saved_registry: None,
|
||||
_timer: cx.spawn(async move |view, cx| {
|
||||
loop {
|
||||
clock.timer(Self::LOCAL_SAVE_INTERVAL).await;
|
||||
@@ -644,6 +670,11 @@ impl DesktopShellView {
|
||||
}
|
||||
local.bound = Some(active.clone());
|
||||
}
|
||||
registry::sync_registry_update(
|
||||
&mut local.saved_registry,
|
||||
local.workspaces.store.as_ref(),
|
||||
&store.workspaces,
|
||||
);
|
||||
if flush {
|
||||
local.workspaces.save();
|
||||
} else {
|
||||
@@ -673,10 +704,15 @@ impl DesktopShellView {
|
||||
/// Save at once when the active workspace, its document list, or the active route
|
||||
/// changed since the last save.
|
||||
pub(super) fn save_local_workspaces_if_changed(&mut self) {
|
||||
let Some(local) = &self.local else {
|
||||
let Some(local) = &mut self.local else {
|
||||
return;
|
||||
};
|
||||
let store = &self.state.store;
|
||||
registry::sync_registry_update(
|
||||
&mut local.saved_registry,
|
||||
local.workspaces.store.as_ref(),
|
||||
&store.workspaces,
|
||||
);
|
||||
let route = self.state.split.active().active_route();
|
||||
let unchanged = local.saved.as_ref().is_some_and(|(id, rev, saved_route)| {
|
||||
*id == store.active_workspace().id
|
||||
@@ -767,7 +803,7 @@ mod tests {
|
||||
use ui::{AppContext as _, Application, Entity, HeadlessPlatform};
|
||||
|
||||
use super::*;
|
||||
use crate::showcase::SHOWCASE_WORKSPACE_IDS;
|
||||
use crate::showcase::{SHOWCASE_WORKSPACE_ID, SHOWCASE_WORKSPACE_IDS};
|
||||
|
||||
thread_local! {
|
||||
static MERGE_WORK: Cell<(usize, usize)> = const { Cell::new((0, 0)) };
|
||||
@@ -868,6 +904,16 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn clear_workspace_blobs(&self, workspace_id: &str) {
|
||||
self.blobs.borrow_mut().remove(workspace_id);
|
||||
self.workspaces.borrow_mut().remove(workspace_id);
|
||||
self.tabs.borrow_mut().remove(workspace_id);
|
||||
self.explorer_prefs.borrow_mut().remove(workspace_id);
|
||||
if let Some(dir) = &self.blob_dir {
|
||||
let _ = std::fs::remove_dir_all(dir.join(workspace_id));
|
||||
}
|
||||
}
|
||||
|
||||
fn set_route(&self, workspace_id: &str, doc_id: Option<&str>) {
|
||||
*self.route.borrow_mut() = Some((workspace_id.to_owned(), doc_id.map(str::to_owned)));
|
||||
}
|
||||
@@ -1888,7 +1934,8 @@ mod tests {
|
||||
last += elapsed;
|
||||
last_bytes += bytes;
|
||||
}
|
||||
let deferred = bound.sessions[SHOWCASE_WORKSPACE_ID].deferred.borrow();
|
||||
let sessions = bound.sessions.borrow();
|
||||
let deferred = sessions[SHOWCASE_WORKSPACE_ID].deferred.borrow();
|
||||
let doc = deferred.iter().find(|doc| doc.doc_id == DOC).unwrap();
|
||||
assert!(doc.updates.len() <= 9, "edit {}", i + 1);
|
||||
}
|
||||
@@ -1905,7 +1952,8 @@ mod tests {
|
||||
assert_eq!(frames(SHOWCASE_WORKSPACE_ID, DOC), stored_frames);
|
||||
assert!(local.holds(SHOWCASE_WORKSPACE_ID, "doc-legacy-draft"));
|
||||
{
|
||||
let deferred = bound.sessions[SHOWCASE_WORKSPACE_ID].deferred.borrow();
|
||||
let sessions = bound.sessions.borrow();
|
||||
let deferred = sessions[SHOWCASE_WORKSPACE_ID].deferred.borrow();
|
||||
let ids: Vec<_> = deferred.iter().map(|doc| doc.doc_id.as_str()).collect();
|
||||
assert!(ids.contains(&DOC), "{ids:?}");
|
||||
for doc in deferred.iter() {
|
||||
@@ -1928,7 +1976,7 @@ mod tests {
|
||||
assert_eq!(frames(SHOWCASE_WORKSPACE_ID, DOC), stored_frames + 1);
|
||||
assert!(!local.holds(SHOWCASE_WORKSPACE_ID, "doc-legacy-draft"));
|
||||
assert!(
|
||||
bound.sessions[SHOWCASE_WORKSPACE_ID]
|
||||
bound.sessions.borrow()[SHOWCASE_WORKSPACE_ID]
|
||||
.deferred
|
||||
.borrow()
|
||||
.is_empty()
|
||||
@@ -1980,7 +2028,7 @@ mod tests {
|
||||
stored_frames + EDITS
|
||||
);
|
||||
assert!(
|
||||
bound.sessions[SHOWCASE_WORKSPACE_ID]
|
||||
bound.sessions.borrow()[SHOWCASE_WORKSPACE_ID]
|
||||
.deferred
|
||||
.borrow()
|
||||
.is_empty()
|
||||
@@ -2108,4 +2156,198 @@ mod tests {
|
||||
.unwrap();
|
||||
assert!(format!("{err:#}").contains(SHOWCASE_WORKSPACE_ID));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_default_workspace_persists_remaining_scratch_across_cold_reopen() {
|
||||
use crate::editor_host::tests::open_test_shell;
|
||||
|
||||
let local = Rc::new(MemoryStore::default());
|
||||
let (state, sessions) = open(&local);
|
||||
let (platform, app, window, _) = open_test_shell(state, 1280, 800);
|
||||
let bound = app.update(|cx| {
|
||||
window
|
||||
.update(cx, |shell, _, cx| {
|
||||
let bound = shell.bind_local_workspaces(sessions, local.clone(), NOW_MS, cx);
|
||||
assert_eq!(
|
||||
shell.state.store.active_workspace().id,
|
||||
SHOWCASE_WORKSPACE_ID
|
||||
);
|
||||
assert!(shell.delete_active_workspace(cx));
|
||||
assert_eq!(
|
||||
shell.state.store.active_workspace().id,
|
||||
SHOWCASE_WORKSPACE_IDS[1]
|
||||
);
|
||||
bound
|
||||
})
|
||||
.unwrap()
|
||||
});
|
||||
platform.run_until_parked();
|
||||
bound.save();
|
||||
|
||||
let (reopened, _) = open(&local);
|
||||
assert_eq!(reopened.store.workspaces.len(), 1);
|
||||
assert_eq!(
|
||||
reopened.store.active_workspace().id,
|
||||
SHOWCASE_WORKSPACE_IDS[1]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_all_workspaces_persists_fallback_default_with_new_doc_across_cold_reopen() {
|
||||
use crate::editor_host::tests::open_test_shell;
|
||||
use blocksuite_playground_doc::read::BlockContent;
|
||||
|
||||
let local = Rc::new(MemoryStore::default());
|
||||
let (state, sessions) = open(&local);
|
||||
let (platform, app, window, _) = open_test_shell(state, 1280, 800);
|
||||
let (bound, fallback_id, doc_id) = app.update(|cx| {
|
||||
window
|
||||
.update(cx, |shell, _, cx| {
|
||||
let bound = shell.bind_local_workspaces(sessions, local.clone(), NOW_MS, cx);
|
||||
assert!(shell.delete_active_workspace(cx));
|
||||
assert!(shell.delete_active_workspace(cx));
|
||||
let fallback_id = shell.state.store.active_workspace().id.clone();
|
||||
assert!(
|
||||
fallback_id.starts_with("ws-local-")
|
||||
&& fallback_id != "ws-local-default"
|
||||
&& fallback_id != SHOWCASE_WORKSPACE_IDS[1],
|
||||
"fallback ID must not reuse fixed ws-local-default: {fallback_id}"
|
||||
);
|
||||
let doc_id = shell.state.store.create_doc(
|
||||
"Fresh Fallback",
|
||||
affine_store::directory::DocMode::Page,
|
||||
None,
|
||||
NOW_MS + 100,
|
||||
);
|
||||
assert!(
|
||||
shell
|
||||
.state
|
||||
.store
|
||||
.append_paragraph(&doc_id, "Survives cold reopen", NOW_MS + 101)
|
||||
.is_some()
|
||||
);
|
||||
shell.flush_persistence();
|
||||
(bound, fallback_id, doc_id)
|
||||
})
|
||||
.unwrap()
|
||||
});
|
||||
platform.run_until_parked();
|
||||
bound.save();
|
||||
|
||||
let (mut reopened, _) = open(&local);
|
||||
assert_eq!(reopened.store.workspaces.len(), 1);
|
||||
assert_eq!(reopened.store.active_workspace().id, fallback_id);
|
||||
reopened
|
||||
.store
|
||||
.ensure_doc_hydrated(&doc_id)
|
||||
.expect("hydrate fallback doc");
|
||||
let entry = reopened
|
||||
.store
|
||||
.get_doc(&doc_id)
|
||||
.expect("doc exists after reopen");
|
||||
let texts: Vec<String> = entry
|
||||
.snapshot
|
||||
.root
|
||||
.as_ref()
|
||||
.into_iter()
|
||||
.flat_map(|r| r.children.iter())
|
||||
.filter(|n| n.is_page_visible_note())
|
||||
.flat_map(|n| n.walk())
|
||||
.filter_map(|node| match &node.content {
|
||||
BlockContent::Paragraph { text, .. } => Some(text.plain.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(
|
||||
texts.iter().any(|t| t == "Survives cold reopen"),
|
||||
"unexpected reopened texts: {texts:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_workspace_with_blobs_clears_media_and_rebuild_backup_has_zero_stale_blobs() {
|
||||
use crate::editor_host::tests::open_test_shell;
|
||||
|
||||
let nonce = blocksuite_playground_doc::try_random_client_id().expect("nonce");
|
||||
let blob_dir = std::env::temp_dir().join(format!("affine-del-blobs-{nonce:x}"));
|
||||
let local = Rc::new(MemoryStore {
|
||||
blob_dir: Some(blob_dir.clone()),
|
||||
..MemoryStore::default()
|
||||
});
|
||||
let stale_bytes = Arc::new(vec![0x89, b'P', b'N', b'G', 9, 8, 7, 6]);
|
||||
let seeded_blobs = BTreeMap::from([(
|
||||
SHOWCASE_WORKSPACE_ID.to_owned(),
|
||||
BTreeMap::from([("stale-attachment".to_owned(), stale_bytes.clone())]),
|
||||
)]);
|
||||
local
|
||||
.put_blob(SHOWCASE_WORKSPACE_ID, "stale-attachment", &stale_bytes)
|
||||
.expect("write initial disk blob");
|
||||
|
||||
let (state, sessions) = open(&local);
|
||||
let (platform, app, window, _) = open_test_shell(state, 1280, 800);
|
||||
let (bound, fallback_id, backup) = app.update(|cx| {
|
||||
window
|
||||
.update(cx, |shell, _, cx| {
|
||||
let bound = shell.bind_local_workspaces_with_blobs(
|
||||
sessions,
|
||||
local.clone(),
|
||||
seeded_blobs,
|
||||
NOW_MS,
|
||||
cx,
|
||||
);
|
||||
assert!(
|
||||
!shell
|
||||
.editor_host
|
||||
.workspace_blobs_snapshot(SHOWCASE_WORKSPACE_ID)
|
||||
.is_empty()
|
||||
);
|
||||
assert!(shell.delete_active_workspace(cx));
|
||||
assert!(shell.delete_active_workspace(cx));
|
||||
|
||||
assert!(
|
||||
shell
|
||||
.editor_host
|
||||
.workspace_blobs_snapshot(SHOWCASE_WORKSPACE_ID)
|
||||
.is_empty(),
|
||||
"deleted workspace blobs must clear from editor_host memory"
|
||||
);
|
||||
assert!(
|
||||
local.load_blobs(SHOWCASE_WORKSPACE_ID).is_empty(),
|
||||
"deleted workspace blobs must clear from local store"
|
||||
);
|
||||
|
||||
let fallback_id = shell.state.store.active_workspace().id.clone();
|
||||
assert_ne!(fallback_id, SHOWCASE_WORKSPACE_ID);
|
||||
assert_ne!(fallback_id, SHOWCASE_WORKSPACE_IDS[1]);
|
||||
assert_ne!(fallback_id, "ws-local-default");
|
||||
|
||||
let backup = shell
|
||||
.export_active_workspace_backup(cx)
|
||||
.expect("export rebuilt workspace backup");
|
||||
(bound, fallback_id, backup)
|
||||
})
|
||||
.unwrap()
|
||||
});
|
||||
platform.run_until_parked();
|
||||
bound.save();
|
||||
|
||||
let backup_path = std::env::temp_dir().join(format!("affine-rebuilt-{nonce:x}.affine"));
|
||||
std::fs::write(&backup_path, &backup.bytes).expect("write backup");
|
||||
let (reopened, _) =
|
||||
crate::sqlite_loader::open_sqlite_workspace(backup_path.clone()).expect("open backup");
|
||||
assert_eq!(reopened.active_workspace().id, fallback_id);
|
||||
let reopened_blobs = reopened
|
||||
.sqlite_backing
|
||||
.as_ref()
|
||||
.expect("sqlite backing")
|
||||
.load_all_blobs()
|
||||
.expect("load backup blobs");
|
||||
assert!(
|
||||
reopened_blobs.is_empty(),
|
||||
"rebuilt workspace backup must contain zero stale blobs, got: {reopened_blobs:?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_file(&backup_path);
|
||||
let _ = std::fs::remove_dir_all(&blob_dir);
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,8 @@
|
||||
mod connected_workspace;
|
||||
mod interaction;
|
||||
mod local_workspace;
|
||||
mod preferences;
|
||||
pub(crate) mod preferences;
|
||||
mod registry;
|
||||
mod search_input;
|
||||
mod topbar;
|
||||
|
||||
@@ -14,6 +15,8 @@ mod peek_lifecycle_tests;
|
||||
|
||||
pub(crate) use local_workspace::StoredBlobs;
|
||||
pub use local_workspace::{LocalDocStore, LocalWorkspaces, StoredDocs, StoredWorkspaces};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) use registry::LOCAL_REGISTRY_WORKSPACE_ID;
|
||||
|
||||
use blocksuite_editor::inline_input::Utf16ImeBuffer;
|
||||
pub(crate) use interaction::backdrop;
|
||||
|
||||
@@ -1,13 +1,174 @@
|
||||
//! Desktop appearance and creation preferences.
|
||||
|
||||
use affine_store::directory::DocMode;
|
||||
use affine_client::{HostKind, WorkspaceSession, i18n::find_language};
|
||||
use affine_store::{
|
||||
directory::DocMode,
|
||||
workspace_db::{PendingDocUpdate, WorkspaceDb},
|
||||
};
|
||||
use blocksuite_playground_doc::try_random_client_id;
|
||||
|
||||
use super::DesktopShellView;
|
||||
use crate::{
|
||||
doc_store::PageWidth,
|
||||
split_view::{DesktopRoute, DocViewMode, SplitLayout},
|
||||
state::{EditorFontPreferences, ThemePreference},
|
||||
};
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
const LANGUAGE_STORAGE_KEY: &str = "affine.desktop.language";
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[derive(serde::Serialize, serde::Deserialize, Default)]
|
||||
struct NativePreferences {
|
||||
#[serde(default)]
|
||||
language: String,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn platform_prefs_path(
|
||||
os: &str,
|
||||
read_var: impl Fn(&str) -> Option<std::ffi::OsString>,
|
||||
) -> Option<std::path::PathBuf> {
|
||||
use std::path::PathBuf;
|
||||
|
||||
let read_path = |name| {
|
||||
read_var(name)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(PathBuf::from)
|
||||
};
|
||||
let base = if let Some(xdg) = read_path("XDG_CONFIG_HOME") {
|
||||
xdg
|
||||
} else if let Some(local) = (os == "windows")
|
||||
.then(|| read_path("LOCALAPPDATA"))
|
||||
.flatten()
|
||||
{
|
||||
local
|
||||
} else {
|
||||
let home = read_path("HOME")?;
|
||||
if os == "macos" {
|
||||
home.join("Library").join("Application Support")
|
||||
} else {
|
||||
home.join(".config")
|
||||
}
|
||||
};
|
||||
Some(base.join("affine-desktop").join("preferences.json"))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn default_prefs_path() -> Option<std::path::PathBuf> {
|
||||
if let Some(explicit) = std::env::var_os("AFFINE_DESKTOP_PREFS_PATH").filter(|v| !v.is_empty())
|
||||
{
|
||||
return Some(std::path::PathBuf::from(explicit));
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
None
|
||||
}
|
||||
#[cfg(not(test))]
|
||||
{
|
||||
platform_prefs_path(std::env::consts::OS, |name| std::env::var_os(name))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
use std::path::Path;
|
||||
|
||||
use super::platform_prefs_path;
|
||||
|
||||
#[test]
|
||||
fn preferences_path_uses_platform_home_and_respects_config_overrides() {
|
||||
for (os, xdg, local, home, expected) in [
|
||||
(
|
||||
"macos",
|
||||
"",
|
||||
"",
|
||||
"home",
|
||||
Some("home/Library/Application Support"),
|
||||
),
|
||||
("linux", "", "local", "home", Some("home/.config")),
|
||||
("macos", "xdg", "", "home", Some("xdg")),
|
||||
("linux", "xdg", "", "home", Some("xdg")),
|
||||
("windows", "xdg", "local", "home", Some("xdg")),
|
||||
("windows", "", "local", "home", Some("local")),
|
||||
("linux", "", "", "", None),
|
||||
] {
|
||||
let path = platform_prefs_path(os, |name| {
|
||||
[
|
||||
("XDG_CONFIG_HOME", xdg),
|
||||
("LOCALAPPDATA", local),
|
||||
("HOME", home),
|
||||
]
|
||||
.into_iter()
|
||||
.find_map(|(key, value)| (key == name).then(|| value.into()))
|
||||
});
|
||||
assert_eq!(
|
||||
path,
|
||||
expected.map(|base| Path::new(base)
|
||||
.join("affine-desktop")
|
||||
.join("preferences.json")),
|
||||
"{os}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn load_language_from(path: Option<&std::path::Path>) -> String {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = path;
|
||||
crate::wasm_entry::web_local_storage_get(LANGUAGE_STORAGE_KEY)
|
||||
.and_then(|code| find_language(&code).map(|meta| meta.code.to_owned()))
|
||||
.unwrap_or_else(|| "en".to_owned())
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let Some(path) = path else {
|
||||
return "en".to_owned();
|
||||
};
|
||||
let Ok(raw) = std::fs::read_to_string(path) else {
|
||||
return "en".to_owned();
|
||||
};
|
||||
serde_json::from_str::<NativePreferences>(&raw)
|
||||
.ok()
|
||||
.and_then(|prefs| find_language(&prefs.language).map(|meta| meta.code.to_owned()))
|
||||
.unwrap_or_else(|| "en".to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn save_language_to(path: Option<&std::path::Path>, code: &str) -> String {
|
||||
let canonical = find_language(code)
|
||||
.map(|meta| meta.code)
|
||||
.unwrap_or("en")
|
||||
.to_owned();
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = path;
|
||||
crate::wasm_entry::web_local_storage_set(LANGUAGE_STORAGE_KEY, &canonical);
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(path) = path
|
||||
&& let Ok(bytes) = serde_json::to_vec_pretty(&NativePreferences {
|
||||
language: canonical.clone(),
|
||||
})
|
||||
{
|
||||
if let Some(parent) = path.parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
let nonce = try_random_client_id().unwrap_or(0);
|
||||
let tmp = path.with_extension(format!("tmp.{}.{nonce:x}", std::process::id()));
|
||||
if std::fs::write(&tmp, &bytes).is_ok() {
|
||||
if std::fs::rename(&tmp, path).is_err() {
|
||||
let _ = std::fs::write(path, &bytes);
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
} else {
|
||||
let _ = std::fs::write(path, &bytes);
|
||||
}
|
||||
}
|
||||
canonical
|
||||
}
|
||||
|
||||
impl DesktopShellView {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn use_web_chrome(&mut self, host: Option<crate::wasm_entry::WebDesktopHost>) {
|
||||
@@ -91,4 +252,147 @@ impl DesktopShellView {
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn rename_active_workspace(
|
||||
&mut self,
|
||||
new_name: &str,
|
||||
cx: &mut ui::Context<Self>,
|
||||
) -> bool {
|
||||
if !self.state.store.rename_workspace(new_name) {
|
||||
return false;
|
||||
}
|
||||
self.flush_persistence();
|
||||
cx.notify();
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn delete_active_workspace(&mut self, cx: &mut ui::Context<Self>) -> bool {
|
||||
if self.state.store.is_readonly_sqlite() {
|
||||
return false;
|
||||
}
|
||||
self.sync_editors(cx);
|
||||
let doc_ids = self.state.store.workspace_doc_ids();
|
||||
let was_last = self.state.store.workspaces.len() <= 1;
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
if self.disconnect_workspace().is_err() {
|
||||
return false;
|
||||
}
|
||||
let Some(deleted_id) = self.state.store.delete_active_workspace() else {
|
||||
return false;
|
||||
};
|
||||
self.state.parked_layouts.remove(&deleted_id);
|
||||
self.editor_host.clear_workspace_blobs(&deleted_id);
|
||||
let next_ws = self.state.store.active_workspace().id.clone();
|
||||
if was_last {
|
||||
self.state.parked_layouts.clear();
|
||||
self.state.split = SplitLayout::single(
|
||||
self.state.current_scope(),
|
||||
DesktopRoute::AllDocs,
|
||||
DocViewMode::Page,
|
||||
);
|
||||
} else {
|
||||
let next_layout = self
|
||||
.state
|
||||
.parked_layouts
|
||||
.remove(&next_ws)
|
||||
.unwrap_or_else(|| {
|
||||
let route = self
|
||||
.state
|
||||
.store
|
||||
.visible_docs()
|
||||
.first()
|
||||
.map_or(DesktopRoute::AllDocs, |doc| {
|
||||
DesktopRoute::Doc(doc.id.clone())
|
||||
});
|
||||
SplitLayout::single(self.state.current_scope(), route, DocViewMode::Page)
|
||||
});
|
||||
self.state.split = next_layout;
|
||||
}
|
||||
self.state.peek_view.close();
|
||||
self.state.sidebar.scroll_y = 0.0;
|
||||
self.state.sidebar.expanded_groups.clear();
|
||||
self.state.reconcile_doc_routes();
|
||||
if let Some(local) = &mut self.local {
|
||||
local.workspaces.sessions.borrow_mut().remove(&deleted_id);
|
||||
for doc_id in &doc_ids {
|
||||
local.workspaces.store.delete_doc(&deleted_id, doc_id);
|
||||
}
|
||||
local.workspaces.store.clear_workspace_blobs(&deleted_id);
|
||||
local.workspaces.store.set_tabs(&deleted_id, "");
|
||||
local.workspaces.store.set_explorer_prefs(&deleted_id, "");
|
||||
if was_last
|
||||
&& let Ok(client_id) = try_random_client_id()
|
||||
&& let Ok(root_bytes) = self.state.store.directory.db().root().encode_update_v1()
|
||||
&& let Ok(mut db) = WorkspaceDb::from_root_update_v1(
|
||||
&next_ws,
|
||||
"local-user",
|
||||
client_id,
|
||||
&root_bytes,
|
||||
&[],
|
||||
)
|
||||
{
|
||||
let _ = db.drain_pending_updates();
|
||||
let host_kind = if self.state.web_chrome {
|
||||
HostKind::Web
|
||||
} else {
|
||||
HostKind::Native
|
||||
};
|
||||
if let Ok(mut session) = WorkspaceSession::from_local_workspace_db(
|
||||
db,
|
||||
client_id,
|
||||
host_kind,
|
||||
self.state.logical_clock_ms,
|
||||
) {
|
||||
session.enqueue_pending_persist_updates(vec![PendingDocUpdate {
|
||||
doc_id: next_ws.clone(),
|
||||
update: root_bytes,
|
||||
}]);
|
||||
local.workspaces.sessions.borrow_mut().insert(
|
||||
next_ws,
|
||||
super::local_workspace::LocalSession::new(session, Default::default()),
|
||||
);
|
||||
}
|
||||
}
|
||||
local.bound = None;
|
||||
self.save_local_workspaces();
|
||||
self.sync_explorer_prefs(cx);
|
||||
}
|
||||
cx.notify();
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn set_display_language(
|
||||
&mut self,
|
||||
code: &str,
|
||||
cx: &mut ui::Context<Self>,
|
||||
) -> String {
|
||||
let canonical = save_language_to(self.state.prefs_path.as_deref(), code);
|
||||
if self.state.display_language != canonical {
|
||||
self.state.display_language = canonical.clone();
|
||||
cx.notify();
|
||||
}
|
||||
canonical
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn export_active_workspace_backup(
|
||||
&mut self,
|
||||
cx: &mut ui::Context<Self>,
|
||||
) -> anyhow::Result<crate::doc_store::WorkspaceBackup> {
|
||||
self.sync_editors(cx);
|
||||
let ws_id = self.state.store.active_workspace().id.clone();
|
||||
let mut blobs = std::collections::BTreeMap::new();
|
||||
if let Some(local) = &self.local {
|
||||
for (key, bytes) in local.workspaces.store.load_blobs(&ws_id) {
|
||||
blobs.insert(key, (*bytes).clone());
|
||||
}
|
||||
}
|
||||
for (key, bytes) in self.editor_host.workspace_blobs_snapshot(&ws_id) {
|
||||
blobs.insert(key, bytes);
|
||||
}
|
||||
let now_ms = self.state.logical_clock_ms;
|
||||
self.state
|
||||
.store
|
||||
.export_workspace_backup_with_blobs(&blobs, now_ms)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
//! Persistent local workspace registry helpers for [`super::local_workspace`].
|
||||
|
||||
use affine_store::{directory::WorkspaceDirectory, workspace_db::WorkspaceDb};
|
||||
use anyhow::Result;
|
||||
use blocksuite_playground_doc::try_random_client_id;
|
||||
|
||||
use super::local_workspace::{LocalDocStore, StoredWorkspaces};
|
||||
use crate::{
|
||||
doc_store::{DesktopDocStore, DesktopWorkspace, WorkspaceKind},
|
||||
showcase::SHOWCASE_WORKSPACE_ID,
|
||||
};
|
||||
|
||||
/// Reserved `LocalDocStore` workspace slot persisting the ordered active workspace registry.
|
||||
pub(crate) const LOCAL_REGISTRY_WORKSPACE_ID: &str = "__affine_desktop_registry__";
|
||||
pub(super) const LOCAL_REGISTRY_DOC_ID: &str = "workspaces";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
struct RegisteredWorkspace {
|
||||
id: String,
|
||||
name: String,
|
||||
cloud: bool,
|
||||
}
|
||||
|
||||
pub(super) fn encode_workspace_registry(workspaces: &[DesktopWorkspace]) -> Vec<u8> {
|
||||
let entries: Vec<RegisteredWorkspace> = workspaces
|
||||
.iter()
|
||||
.map(|ws| RegisteredWorkspace {
|
||||
id: ws.id.clone(),
|
||||
name: ws.name.clone(),
|
||||
cloud: ws.kind == WorkspaceKind::Cloud,
|
||||
})
|
||||
.collect();
|
||||
serde_json::to_vec(&entries).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(super) fn decode_workspace_registry(
|
||||
stored: &StoredWorkspaces,
|
||||
) -> Option<Vec<DesktopWorkspace>> {
|
||||
let docs = stored.get(LOCAL_REGISTRY_WORKSPACE_ID)?;
|
||||
let bytes = docs.get(LOCAL_REGISTRY_DOC_ID)?.last()?;
|
||||
let entries: Vec<RegisteredWorkspace> = serde_json::from_slice(bytes).ok()?;
|
||||
Some(
|
||||
entries
|
||||
.into_iter()
|
||||
.map(|entry| DesktopWorkspace {
|
||||
id: entry.id,
|
||||
name: entry.name,
|
||||
kind: if entry.cloud {
|
||||
WorkspaceKind::Cloud
|
||||
} else {
|
||||
WorkspaceKind::Local
|
||||
},
|
||||
synced: true,
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn init_local_store(
|
||||
stored: &StoredWorkspaces,
|
||||
today_date: &str,
|
||||
) -> Result<(DesktopDocStore, bool)> {
|
||||
let registered = decode_workspace_registry(stored);
|
||||
let has_legacy_workspace = stored
|
||||
.iter()
|
||||
.any(|(id, docs)| id != LOCAL_REGISTRY_WORKSPACE_ID && !docs.is_empty());
|
||||
let seeded = registered.is_none() && !has_legacy_workspace;
|
||||
let store =
|
||||
if seeded {
|
||||
DesktopDocStore::seed_showcase(today_date)
|
||||
} else if let Some(mut entries) = registered.filter(|list| !list.is_empty()) {
|
||||
let client_id = try_random_client_id()?;
|
||||
let first_id = entries[0].id.clone();
|
||||
let mut shell = DesktopDocStore::showcase_shell(WorkspaceDirectory::new(
|
||||
WorkspaceDb::new(first_id, "local-user", client_id),
|
||||
));
|
||||
shell.workspaces.clear();
|
||||
shell.workspaces.append(&mut entries);
|
||||
shell
|
||||
} else {
|
||||
let client_id = try_random_client_id()?;
|
||||
DesktopDocStore::showcase_shell(WorkspaceDirectory::new(WorkspaceDb::new(
|
||||
SHOWCASE_WORKSPACE_ID,
|
||||
"local-user",
|
||||
client_id,
|
||||
)))
|
||||
};
|
||||
Ok((store, seeded))
|
||||
}
|
||||
|
||||
pub(super) fn sync_registry_update(
|
||||
saved_registry: &mut Option<Vec<u8>>,
|
||||
store: &dyn LocalDocStore,
|
||||
workspaces: &[DesktopWorkspace],
|
||||
) {
|
||||
let registry_bytes = encode_workspace_registry(workspaces);
|
||||
if saved_registry.as_ref() != Some(®istry_bytes) {
|
||||
store.push_update(
|
||||
LOCAL_REGISTRY_WORKSPACE_ID,
|
||||
LOCAL_REGISTRY_DOC_ID,
|
||||
registry_bytes.clone(),
|
||||
);
|
||||
*saved_registry = Some(registry_bytes);
|
||||
}
|
||||
}
|
||||
@@ -171,6 +171,32 @@ fn render_readonly_sqlite_badge(
|
||||
.child("Read-only")
|
||||
}
|
||||
|
||||
fn render_template_badge(
|
||||
ControlId { element, snapshot }: ControlId,
|
||||
theme: ui_tokens::ThemeMode,
|
||||
) -> impl IntoElement {
|
||||
let tokens = crate::theme_tokens_for(theme);
|
||||
let bg = crate::theme_color(
|
||||
tokens,
|
||||
"--affine-v2-button-templateLabelBackground",
|
||||
tokens.background_secondary,
|
||||
);
|
||||
let fg = crate::theme_color(tokens, "--affine-v2-button-primary", tokens.text_primary);
|
||||
div()
|
||||
.id(element)
|
||||
.snapshot(snapshot, Some("desktop.workbench.topbar"))
|
||||
.flex_shrink(0.0)
|
||||
.rounded(px(4.0))
|
||||
.px(px(8.0))
|
||||
.py(px(2.0))
|
||||
.bg(bg)
|
||||
.text_size(px(12.0))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.line_height(px(20.0))
|
||||
.text_color(fg)
|
||||
.child("Template")
|
||||
}
|
||||
|
||||
pub(super) fn sidebar_switch(
|
||||
id: &'static str,
|
||||
palette: DesktopPalette,
|
||||
@@ -437,6 +463,8 @@ pub(super) fn render_detail_header(
|
||||
tab: pane.active_tab().id,
|
||||
doc: entry.meta.id.clone(),
|
||||
};
|
||||
let is_template = shell.state.store.doc_is_template(&entry.meta.id);
|
||||
let show_journal_template = journal && is_template && width > 400.0;
|
||||
let writable = !readonly && !entry.meta.trashed && entry.is_hydrated();
|
||||
let ControlId { element, snapshot } = id("mode_switch");
|
||||
let mut modes = div()
|
||||
@@ -512,6 +540,12 @@ pub(super) fn render_detail_header(
|
||||
};
|
||||
}
|
||||
header = header.child(title);
|
||||
if is_template {
|
||||
header = header.child(render_template_badge(
|
||||
id("template_badge"),
|
||||
shell.state.theme,
|
||||
));
|
||||
}
|
||||
}
|
||||
header = header.children(readonly.then(readonly_badge));
|
||||
if journal {
|
||||
@@ -522,9 +556,19 @@ pub(super) fn render_detail_header(
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let template_width = if show_journal_template {
|
||||
72.0 + gap
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let share_width = if hide_share { 0.0 } else { share_width + gap };
|
||||
let calendar_width =
|
||||
width - 2.0 * inset - icons_width - mode_width - badge_width - share_width;
|
||||
let calendar_width = width
|
||||
- 2.0 * inset
|
||||
- icons_width
|
||||
- mode_width
|
||||
- badge_width
|
||||
- template_width
|
||||
- share_width;
|
||||
header = header.child(div().min_w_0().flex_1().flex().items_center().child(
|
||||
DesktopShellView::journal_week_picker(
|
||||
index,
|
||||
@@ -535,6 +579,12 @@ pub(super) fn render_detail_header(
|
||||
cx,
|
||||
),
|
||||
));
|
||||
if show_journal_template {
|
||||
header = header.child(render_template_badge(
|
||||
id("template_badge"),
|
||||
shell.state.theme,
|
||||
));
|
||||
}
|
||||
}
|
||||
if show_doc_actions {
|
||||
let favorite = entry.meta.is_favorite;
|
||||
@@ -860,4 +910,87 @@ mod tests {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn template_badge_appears_when_doc_is_marked_template() {
|
||||
let mut plain = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02");
|
||||
plain.navigate_active_pane(DesktopRoute::Doc("doc-arch".into()));
|
||||
let without_badge = render_header(plain, 640);
|
||||
assert!(
|
||||
!without_badge
|
||||
.elements
|
||||
.contains_key("desktop.topbar.template_badge")
|
||||
);
|
||||
|
||||
let mut marked = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02");
|
||||
assert!(marked.store.set_doc_is_template("doc-arch", true));
|
||||
marked.navigate_active_pane(DesktopRoute::Doc("doc-arch".into()));
|
||||
let with_badge = render_header(marked, 640);
|
||||
assert!(
|
||||
with_badge
|
||||
.elements
|
||||
.contains_key("desktop.topbar.template_badge")
|
||||
);
|
||||
|
||||
let mut journal = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02");
|
||||
assert!(journal.store.set_doc_is_template("doc-journal-today", true));
|
||||
journal.navigate_active_pane(DesktopRoute::Doc("doc-journal-today".into()));
|
||||
let narrow_journal = render_header(journal, 380);
|
||||
assert!(
|
||||
!narrow_journal
|
||||
.elements
|
||||
.contains_key("desktop.topbar.template_badge")
|
||||
);
|
||||
|
||||
if let Some(dir) =
|
||||
std::env::var_os("AFFINE_SETTINGS_EVIDENCE").map(std::path::PathBuf::from)
|
||||
{
|
||||
std::fs::create_dir_all(&dir).expect("evidence folder");
|
||||
for (name, theme) in [("light", ThemeMode::Light), ("dark", ThemeMode::Dark)] {
|
||||
let platform = HeadlessPlatform::new(1280, 800, 1.0);
|
||||
let app = Application::with_platform(platform.clone()).run_embedded(|_| {});
|
||||
let shell = app.update(|cx| {
|
||||
register_desktop_fonts(cx).expect("desktop fonts");
|
||||
cx.open_window(
|
||||
WindowOptions {
|
||||
window_bounds: Some(WindowBounds::Windowed(Bounds::new(
|
||||
point(px(0.0), px(0.0)),
|
||||
size(px(1280.0), px(800.0)),
|
||||
))),
|
||||
..WindowOptions::default()
|
||||
},
|
||||
|_, cx| {
|
||||
cx.new(|cx| {
|
||||
let mut state = DesktopAppState::seed_showcase(theme, "2026-12-02");
|
||||
state.store.set_doc_is_template("doc-arch", true);
|
||||
state.navigate_active_pane(DesktopRoute::Doc("doc-arch".into()));
|
||||
DesktopShellView::new(state, cx)
|
||||
})
|
||||
},
|
||||
)
|
||||
.expect("desktop window")
|
||||
});
|
||||
let window = platform.windows().pop().expect("headless window");
|
||||
window.request_frame();
|
||||
platform.run_until_parked();
|
||||
app.update(|cx| {
|
||||
shell
|
||||
.update(cx, |_, window, _| {
|
||||
assert!(
|
||||
window
|
||||
.frame_snapshot()
|
||||
.elements
|
||||
.contains_key("desktop.topbar.template_badge")
|
||||
);
|
||||
window
|
||||
.render_to_image()
|
||||
.expect("offscreen topbar render")
|
||||
.save(dir.join(format!("topbar-template-{name}.png")))
|
||||
.expect("save topbar png");
|
||||
})
|
||||
.expect("capture topbar");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
#![cfg(not(target_family = "wasm"))]
|
||||
|
||||
use affine_desktop::{DesktopDocStore, doc_store::TemplateDocSettings};
|
||||
use affine_store::directory::DocMode;
|
||||
use blocksuite_playground_doc::{
|
||||
read::{BlockContent, PageSnapshot, SurfaceElementKind},
|
||||
schema::{MindmapNodeSpec, SurfaceElementSpec},
|
||||
session::PageDocSession,
|
||||
try_random_client_id,
|
||||
};
|
||||
|
||||
fn mindmap_edges(snapshot: &PageSnapshot) -> (&str, &str) {
|
||||
let (elements, mindmap) = snapshot
|
||||
.root
|
||||
.as_ref()
|
||||
.expect("page root")
|
||||
.walk()
|
||||
.find_map(|block| {
|
||||
let BlockContent::Surface { elements, .. } = &block.content else {
|
||||
return None;
|
||||
};
|
||||
elements.iter().find_map(|element| match &element.kind {
|
||||
SurfaceElementKind::Mindmap(mindmap) => Some((elements, mindmap)),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
.expect("mindmap");
|
||||
assert_eq!(mindmap.nodes.len(), 2);
|
||||
let (root, _) = mindmap
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| node.parent.is_none())
|
||||
.expect("mindmap root");
|
||||
let (branch, detail) = mindmap
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| node.parent.is_some())
|
||||
.expect("mindmap branch");
|
||||
assert_eq!(detail.parent.as_ref(), Some(root));
|
||||
for id in [root, branch] {
|
||||
assert!(elements.iter().any(|element| &element.id == id));
|
||||
}
|
||||
(root, branch)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_and_journal_template_mindmaps_keep_their_branches_after_backup_reopen() {
|
||||
const TODAY: &str = "2026-12-02";
|
||||
const JOURNAL_DATE: &str = "2026-12-03";
|
||||
const NOW: i64 = 1_764_400_000;
|
||||
let mut store = DesktopDocStore::seed_showcase(TODAY);
|
||||
let template = store.create_doc("Mind Map Template", DocMode::Page, None, NOW);
|
||||
let entry = store.get_doc(&template).expect("template entry");
|
||||
let surface = entry.surface_id.clone();
|
||||
let seed = entry.session.encode_update_v1().expect("template bytes");
|
||||
let mut editor =
|
||||
PageDocSession::new(&template, try_random_client_id().expect("editor client ID"))
|
||||
.expect("template editor");
|
||||
editor.apply_remote_update_v1(&seed).expect("load template");
|
||||
let before = editor
|
||||
.encode_state_vector_v1()
|
||||
.expect("template state vector");
|
||||
for (id, index) in [("template-root", "a1"), ("template-branch", "a2")] {
|
||||
editor
|
||||
.add_surface_element(
|
||||
&surface,
|
||||
id,
|
||||
index,
|
||||
SurfaceElementSpec::Shape {
|
||||
shape_type: "rect".into(),
|
||||
xywh: "[0,0,100,50]".into(),
|
||||
seed: 1,
|
||||
filled: true,
|
||||
text: None,
|
||||
},
|
||||
(NOW + 1) as u64,
|
||||
)
|
||||
.expect("add node shape");
|
||||
}
|
||||
editor
|
||||
.add_surface_element(
|
||||
&surface,
|
||||
"template-map",
|
||||
"a0",
|
||||
SurfaceElementSpec::Mindmap {
|
||||
seed: 1,
|
||||
style: 1,
|
||||
layout_type: 0,
|
||||
children: vec![
|
||||
(
|
||||
"template-root".into(),
|
||||
MindmapNodeSpec {
|
||||
index: "a0".into(),
|
||||
parent: None,
|
||||
collapsed: false,
|
||||
},
|
||||
),
|
||||
(
|
||||
"template-branch".into(),
|
||||
MindmapNodeSpec {
|
||||
index: "a1".into(),
|
||||
parent: Some("template-root".into()),
|
||||
collapsed: false,
|
||||
},
|
||||
),
|
||||
],
|
||||
},
|
||||
(NOW + 2) as u64,
|
||||
)
|
||||
.expect("add mindmap");
|
||||
let update = editor.encode_diff_v1(&before).expect("template edit");
|
||||
assert!(store.apply_remote_doc_update(&template, &update));
|
||||
assert!(store.set_doc_is_template(&template, true));
|
||||
assert!(store.set_template_settings(TemplateDocSettings {
|
||||
enable_page_template: true,
|
||||
page_template_id: Some(template.clone()),
|
||||
journal_template_id: Some(template.clone()),
|
||||
}));
|
||||
|
||||
let page = store.create_doc("New Page", DocMode::Page, None, NOW + 3);
|
||||
let journal = store.open_or_create_journal(JOURNAL_DATE, NOW + 4);
|
||||
assert_eq!(
|
||||
store
|
||||
.get_doc(&journal)
|
||||
.expect("journal")
|
||||
.meta
|
||||
.journal_date
|
||||
.as_deref(),
|
||||
Some(JOURNAL_DATE)
|
||||
);
|
||||
let original_edges = ("template-root", "template-branch");
|
||||
assert_eq!(
|
||||
mindmap_edges(&store.get_doc(&template).expect("template").snapshot),
|
||||
original_edges
|
||||
);
|
||||
let copies = [&page, &journal].map(|id| {
|
||||
let (root, branch) = mindmap_edges(&store.get_doc(id).expect("cloned doc").snapshot);
|
||||
assert_ne!(root, original_edges.0);
|
||||
assert_ne!(branch, original_edges.1);
|
||||
(root.to_owned(), branch.to_owned())
|
||||
});
|
||||
assert_ne!(copies[0], copies[1]);
|
||||
|
||||
let backup = store
|
||||
.export_workspace_backup(NOW + 5)
|
||||
.expect("export workspace");
|
||||
let nonce = try_random_client_id().expect("backup file ID");
|
||||
let path = std::env::temp_dir().join(format!("affine-mindmap-template-{nonce}.affine"));
|
||||
std::fs::write(&path, backup.bytes).expect("write backup");
|
||||
let (mut reopened, _) = DesktopDocStore::open_sqlite_file(&path).expect("open backup");
|
||||
for (id, expected) in [
|
||||
(&template, original_edges),
|
||||
(&page, (copies[0].0.as_str(), copies[0].1.as_str())),
|
||||
(&journal, (copies[1].0.as_str(), copies[1].1.as_str())),
|
||||
] {
|
||||
reopened
|
||||
.ensure_doc_hydrated(id)
|
||||
.expect("hydrate from backup");
|
||||
assert_eq!(
|
||||
mindmap_edges(&reopened.get_doc(id).expect("reopened doc").snapshot),
|
||||
expected
|
||||
);
|
||||
}
|
||||
drop(reopened);
|
||||
std::fs::remove_file(path).expect("remove backup");
|
||||
}
|
||||
@@ -60,13 +60,34 @@ async function fetchFont(url) {
|
||||
* `retryBlobWrites()`, or a `flush()` writes all of them in one transaction.
|
||||
*
|
||||
* @param {string[]} workspaceIds
|
||||
* @param {{ indexedDB?: IDBFactory, location?: Location, history?: History }} [env]
|
||||
* @param {{
|
||||
* indexedDB?: IDBFactory,
|
||||
* location?: Location,
|
||||
* history?: History,
|
||||
* localStorage?: Storage,
|
||||
* BroadcastChannel?: typeof BroadcastChannel,
|
||||
* now?: () => number,
|
||||
* setTimeout?: typeof setTimeout,
|
||||
* clearTimeout?: typeof clearTimeout,
|
||||
* }} [env]
|
||||
*/
|
||||
export async function openDesktopStore(workspaceIds, env = globalThis) {
|
||||
const indexedDB = env.indexedDB;
|
||||
if (!indexedDB || typeof indexedDB.open !== 'function') return null;
|
||||
/** @type {() => void} */
|
||||
let markSeeded = () => {};
|
||||
const createWorkspaceStorage = id =>
|
||||
createIdbWorkspaceStorage({
|
||||
flavour: 'local',
|
||||
type: 'workspace',
|
||||
id,
|
||||
indexedDB,
|
||||
BroadcastChannelImpl: env.BroadcastChannel,
|
||||
now: env.now,
|
||||
setTimeout: env.setTimeout,
|
||||
clearTimeout: env.clearTimeout,
|
||||
onDocWriteFailure: () => markSeeded(),
|
||||
});
|
||||
/** @type {Map<string, ReturnType<typeof createIdbWorkspaceStorage>>} */
|
||||
const storages = new Map();
|
||||
/** @type {Map<string, Map<string, Uint8Array[]>>} */
|
||||
@@ -75,13 +96,7 @@ export async function openDesktopStore(workspaceIds, env = globalThis) {
|
||||
const initialBlobs = new Map();
|
||||
try {
|
||||
for (const id of workspaceIds) {
|
||||
const storage = createIdbWorkspaceStorage({
|
||||
flavour: 'local',
|
||||
type: 'workspace',
|
||||
id,
|
||||
indexedDB,
|
||||
onDocWriteFailure: () => markSeeded(),
|
||||
});
|
||||
const storage = createWorkspaceStorage(id);
|
||||
storages.set(id, storage);
|
||||
await storage.open();
|
||||
const docs = await storage.getAllDocsRaw();
|
||||
@@ -150,6 +165,21 @@ export async function openDesktopStore(workspaceIds, env = globalThis) {
|
||||
changed(workspaceId);
|
||||
};
|
||||
|
||||
/** @type {Set<string>} */
|
||||
const explicitlyRegistered = new Set(workspaceIds);
|
||||
const isRegisteredWorkspace = id => {
|
||||
if (explicitlyRegistered.has(id)) return true;
|
||||
try {
|
||||
const raw = env.localStorage?.getItem('affine.desktop.workspaceRegistry');
|
||||
if (!raw) return false;
|
||||
const entries = JSON.parse(raw);
|
||||
return Array.isArray(entries) && entries.some(entry => entry?.id === id);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
/** @type {Map<string, Promise<ReturnType<typeof createIdbWorkspaceStorage>>>} */
|
||||
const opening = new Map();
|
||||
/**
|
||||
* Starts one transaction per workspace with its queued media and document
|
||||
* changes. With `retry`, it also writes the changes that a workspace keeps
|
||||
@@ -170,18 +200,41 @@ export async function openDesktopStore(workspaceIds, env = globalThis) {
|
||||
];
|
||||
pendingBlobs.delete(id);
|
||||
queued.delete(id);
|
||||
const storage = storages.get(id);
|
||||
if (!storage) {
|
||||
writeFailed(new Error(`Unknown desktop workspace ${id}`));
|
||||
continue;
|
||||
}
|
||||
let write;
|
||||
try {
|
||||
const sent = ops.length ? storage.writeDocOpsNow(ops) : null;
|
||||
const replay = retry ? storage.retryPausedWrites() : null;
|
||||
const openAndWrite = target => {
|
||||
const sent = ops.length ? target.writeDocOpsNow(ops) : null;
|
||||
const replay = retry ? target.retryPausedWrites() : null;
|
||||
// A paused workspace keeps `sent` for the replay and rejects it at once.
|
||||
if (replay && sent) void sent.catch(() => {});
|
||||
write = replay ?? sent;
|
||||
return replay ?? sent;
|
||||
};
|
||||
const storage = storages.get(id);
|
||||
let write;
|
||||
try {
|
||||
if (!storage) {
|
||||
if (!isRegisteredWorkspace(id)) {
|
||||
writeFailed(new Error(`Unknown desktop workspace ${id}`));
|
||||
continue;
|
||||
}
|
||||
let pendingOpen = opening.get(id);
|
||||
if (!pendingOpen) {
|
||||
const opened = createWorkspaceStorage(id);
|
||||
pendingOpen = opened.open().then(
|
||||
() => {
|
||||
storages.set(id, opened);
|
||||
opening.delete(id);
|
||||
return opened;
|
||||
},
|
||||
error => {
|
||||
opening.delete(id);
|
||||
throw error;
|
||||
}
|
||||
);
|
||||
opening.set(id, pendingOpen);
|
||||
}
|
||||
write = pendingOpen.then(opened => openAndWrite(opened));
|
||||
} else {
|
||||
write = openAndWrite(storage);
|
||||
}
|
||||
} catch (error) {
|
||||
write = Promise.reject(error);
|
||||
}
|
||||
@@ -226,6 +279,47 @@ export async function openDesktopStore(workspaceIds, env = globalThis) {
|
||||
frames.clear();
|
||||
initialBlobs.clear();
|
||||
},
|
||||
registerWorkspace(workspaceId) {
|
||||
if (typeof workspaceId === 'string' && workspaceId) {
|
||||
explicitlyRegistered.add(workspaceId);
|
||||
}
|
||||
},
|
||||
deleteWorkspace(workspaceId) {
|
||||
if (typeof workspaceId !== 'string' || !workspaceId) return;
|
||||
explicitlyRegistered.delete(workspaceId);
|
||||
ready.delete(workspaceId);
|
||||
pendingBlobs.delete(workspaceId);
|
||||
queued.delete(workspaceId);
|
||||
frames.delete(workspaceId);
|
||||
initialBlobs.delete(workspaceId);
|
||||
unseeded.delete(workspaceId);
|
||||
const active = storages.get(workspaceId);
|
||||
if (active) {
|
||||
storages.delete(workspaceId);
|
||||
active.close();
|
||||
}
|
||||
const inflightOpen = opening.get(workspaceId);
|
||||
if (inflightOpen) {
|
||||
opening.delete(workspaceId);
|
||||
void inflightOpen.then(
|
||||
opened => opened.close(),
|
||||
() => {}
|
||||
);
|
||||
}
|
||||
try {
|
||||
env.localStorage?.removeItem(`affine.desktop.tabs.${workspaceId}`);
|
||||
env.localStorage?.removeItem(
|
||||
`affine.desktop.explorerPrefs.${workspaceId}`
|
||||
);
|
||||
} catch {
|
||||
// Ignore unavailable localStorage when clearing deleted workspace state.
|
||||
}
|
||||
try {
|
||||
indexedDB.deleteDatabase?.(`local:workspace:${workspaceId}`);
|
||||
} catch {
|
||||
// Ignore IDB implementations without deleteDatabase.
|
||||
}
|
||||
},
|
||||
putBlob(workspaceId, blobId, bytes) {
|
||||
const blobs = pendingBlobs.get(workspaceId) ?? new Map();
|
||||
blobs.set(blobId, bytes);
|
||||
@@ -336,7 +430,7 @@ export async function startDesktop(
|
||||
search,
|
||||
prefersDark,
|
||||
preview,
|
||||
openStore = openDesktopStore,
|
||||
openStoreWithEnv = openDesktopStore,
|
||||
locks = globalThis.navigator?.locks,
|
||||
env = globalThis
|
||||
) {
|
||||
@@ -350,6 +444,7 @@ export async function startDesktop(
|
||||
}
|
||||
const params = new URLSearchParams(search);
|
||||
const split = params.get('split');
|
||||
const openStore = ids => openStoreWithEnv(ids, env);
|
||||
// Tabs of one origin read the stores and seed the empty workspaces one at a
|
||||
// time: a tab holds the lock until its seed writes commit or a write fails.
|
||||
// Later tabs can read any seed that committed. Without
|
||||
|
||||
@@ -1413,3 +1413,58 @@ void test('desktop group URLs round-trip with one target and drop document selec
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
void test('openDesktopStore rejects unregistered workspaces while lazily opening registered workspaces with env', async t => {
|
||||
const indexedDB = createMemoryIdbFactory();
|
||||
const storageMap = new Map();
|
||||
const openedNames = [];
|
||||
const trackedIdb = {
|
||||
open(name, version) {
|
||||
openedNames.push(name);
|
||||
return indexedDB.open(name, version);
|
||||
},
|
||||
};
|
||||
const errors = [];
|
||||
t.mock.method(console, 'error', (_msg, err) => {
|
||||
errors.push(err?.message ?? String(_msg));
|
||||
});
|
||||
const env = {
|
||||
indexedDB: trackedIdb,
|
||||
BroadcastChannel: createBroadcastBus(),
|
||||
localStorage: {
|
||||
getItem: key => storageMap.get(key) ?? null,
|
||||
setItem: (key, value) => storageMap.set(key, value),
|
||||
},
|
||||
};
|
||||
const store = await openDesktopStore(['ws-initial'], env);
|
||||
|
||||
store.pushUpdate('ws-unregistered', 'doc-1', Uint8Array.of(9));
|
||||
await store.flush();
|
||||
await store.seeded;
|
||||
assert.ok(
|
||||
errors.some(msg =>
|
||||
msg.includes('Unknown desktop workspace ws-unregistered')
|
||||
)
|
||||
);
|
||||
assert.ok(!openedNames.includes('local:workspace:ws-unregistered'));
|
||||
|
||||
storageMap.set(
|
||||
'affine.desktop.workspaceRegistry',
|
||||
JSON.stringify([{ id: 'ws-registry', name: 'Registry', cloud: false }])
|
||||
);
|
||||
store.pushUpdate('ws-registry', 'root', Uint8Array.of(1, 2));
|
||||
store.registerWorkspace('ws-explicit');
|
||||
store.pushUpdate('ws-explicit', 'root', Uint8Array.of(3, 4));
|
||||
await store.flush();
|
||||
|
||||
const cold = await openDesktopStore(
|
||||
['ws-initial', 'ws-registry', 'ws-explicit'],
|
||||
{ indexedDB }
|
||||
);
|
||||
assert.deepEqual(cold.docFrames('ws-registry', 'root'), [
|
||||
Uint8Array.of(1, 2),
|
||||
]);
|
||||
assert.deepEqual(cold.docFrames('ws-explicit', 'root'), [
|
||||
Uint8Array.of(3, 4),
|
||||
]);
|
||||
});
|
||||
Reference in new issue
Block a user