feat(core): hubs, tag pages and types, with ffi, history and import support

Hubs and templates are page kinds; tags are pages of kind tag linked by a TAGGED
edge; types are plain names on the page. Schema v5. Snapshots carry
synapse-kind/tags/types. Also adapts search, import and server tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-10-26 02:45:22 +01:00
1 parent 91a8276966
commit b800248d67
35 files changed
+7983 -141

No files matched your search

+111 -1
View File
@@ -14,6 +14,16 @@ pub struct PageDto {
pub origin_journal: Option<String>,
pub created_at: i64,
pub updated_at: i64,
/// The page is a hub (no blocks; members list instead of an outline).
pub is_hub: bool,
/// Hub description (empty for notes).
pub description: String,
/// Titles of the tag pages this page is filed under, in the order they were added.
pub tags: Vec<String>,
/// The page is a tag page (a topic that other pages are filed under).
pub is_tag: bool,
/// Type names ("persona", "lugar"...: plain names, not pages), in the order added.
pub types: Vec<String>,
}
impl From<&Page> for PageDto {
@@ -25,10 +35,25 @@ impl From<&Page> for PageDto {
origin_journal: p.origin_journal.map(journal_title),
created_at: p.created_at,
updated_at: p.updated_at,
is_hub: p.is_hub(),
description: p.description.clone(),
tags: p.tags.clone(),
is_tag: p.is_tag(),
types: p.types.clone(),
}
}
}
/// A tag or type of the vocabulary.
#[derive(Debug, Clone, PartialEq)]
pub struct TagDto {
pub name: String,
/// Pages using it.
pub count: u32,
/// One of the seeded suggestions.
pub suggested: bool,
}
/// One row of the outline, in pre-order.
#[derive(Debug, Clone, PartialEq)]
pub struct BlockDto {
@@ -95,6 +120,7 @@ pub struct PageBrief {
pub id: String,
pub title: String,
pub is_journal: bool,
pub is_hub: bool,
}
impl From<&Page> for PageBrief {
@@ -103,6 +129,7 @@ impl From<&Page> for PageBrief {
id: p.id.to_string(),
title: p.title.clone(),
is_journal: p.is_journal(),
is_hub: p.is_hub(),
}
}
}
@@ -181,6 +208,11 @@ pub mod edge_kind {
pub const MENTION: u8 = 5;
/// Hebbian association (undirected), weight = decayed synapse strength.
pub const SYNAPSE: u8 = 6;
/// Hub membership, hub → member (structural, weight 1).
pub const CONTAINS: u8 = 7;
/// A page filed under a tag page (page → tag page, weight 1). Unlike `TAG` (an inline
/// `#tag` in the text) it comes from the page's own `tags` list.
pub const TAGGED: u8 = 8;
}
#[derive(Debug, Clone, PartialEq)]
@@ -190,7 +222,8 @@ pub struct GraphNode {
pub journal_date: Option<String>,
pub origin_journal: Option<String>,
pub created_at: i64,
/// Distinct neighbours over structural edges (links, tags, properties, block refs).
/// Distinct neighbours over structural edges (links, tags, properties, block refs, hub
/// membership).
pub degree: u32,
/// Distinct pages referencing this one.
pub backlinks: u32,
@@ -198,6 +231,12 @@ pub struct GraphNode {
pub cluster: u32,
/// Node index of the tag this page uses most, if any.
pub primary_tag: Option<u32>,
/// The page is a hub (`PageKind::Hub`).
pub is_hub: bool,
/// Node index of the deepest hub containing this page (a hub: itself).
pub home_hub: Option<u32>,
/// Tag names of the page (see `PageDto::tags`), for grouping by tag.
pub tags: Vec<String>,
}
/// The whole page-level graph, edges as parallel arrays (cheap to move across the FFI).
@@ -223,3 +262,74 @@ pub struct LayoutFrame {
/// Remaining "temperature"; the layout is settled when it reaches 0.
pub alpha: f32,
}
/// A hub (folder-like page) with its members.
#[derive(Debug, Clone, PartialEq)]
pub struct HubDto {
pub id: String,
pub title: String,
pub description: String,
/// 0 for root hubs, one more per level of nesting.
pub depth: u32,
/// Sub-hubs first, then notes, each by title.
pub members: Vec<PageBrief>,
/// Ids of the members that are hubs themselves.
pub sub_hubs: Vec<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct HubsDto {
/// Sorted by title.
pub hubs: Vec<HubDto>,
/// Ids of the hubs that are not a member of any hub, by title.
pub roots: Vec<String>,
}
/// A level of a namespace (`A/B` under `A`); `id` is `None` when only deeper pages exist.
#[derive(Debug, Clone, PartialEq)]
pub struct NamespaceEntry {
pub title: String,
pub id: Option<String>,
}
/// Hub and namespace context of one page.
#[derive(Debug, Clone, PartialEq)]
pub struct PageStructure {
pub is_hub: bool,
/// Hub description (empty for notes).
pub description: String,
/// Empty unless the page is a hub; sub-hubs first, then notes.
pub members: Vec<PageBrief>,
/// Hubs the page belongs to (its own membership list), by title.
pub in_hubs: Vec<PageBrief>,
/// Ancestor namespaces from the root: `A`, `A/B` for `A/B/C` (they may not exist).
pub ns_path: Vec<NamespaceEntry>,
pub ns_children: Vec<NamespaceEntry>,
}
/// Defaults for the "convert to hub" dialog.
#[derive(Debug, Clone, PartialEq)]
pub struct HubPreviewDto {
/// Last namespace segment of the title.
pub suggested_title: String,
/// First prose block as plain text (<= 280 chars).
pub suggested_description: String,
/// Candidate members: pages the outline links or tags (outline order), then pages
/// referencing the note from properties or tags.
pub members: Vec<PageBrief>,
/// Blocks that are prose rather than links (what "keep the outline" would save).
pub prose_blocks: u32,
pub blocks: u32,
/// `"<suggested_title> (notes)"`, for the note receiving the outline.
pub suggested_note_title: String,
}
/// A page the legacy purge offers to delete.
#[derive(Debug, Clone, PartialEq)]
pub struct LegacyCandidate {
pub id: String,
pub title: String,
pub reason: String,
pub blocks: u32,
pub preselected: bool,
}
+3
View File
@@ -18,6 +18,8 @@ pub struct SynapseGraph {
graph: Arc<Mutex<Graph>>,
/// Page-level graph for the graph views, keyed by what invalidates it.
pub(crate) graph_cache: Mutex<Option<(super::graph_view::CacheKey, Arc<GraphData>)>>,
/// Hubs and home hubs, keyed by op-log sequence.
pub(crate) structure_cache: Mutex<Option<(i64, Arc<synapse_core::Structure>)>>,
}
impl SynapseGraph {
@@ -27,6 +29,7 @@ impl SynapseGraph {
Ok(SynapseGraph {
graph: Arc::new(Mutex::new(graph)),
graph_cache: Mutex::new(None),
structure_cache: Mutex::new(None),
})
}
+50
View File
@@ -78,9 +78,15 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
// Nodes.
let mut nodes = Vec::new();
let mut index: HashMap<String, u32> = HashMap::new();
let page_tags: HashMap<String, Vec<String>> = g
.all_page_tags()?
.into_iter()
.map(|(id, t)| (id.to_string(), t))
.collect();
{
let mut st = conn.prepare(
"SELECT id, title, journal_date, origin_journal, created_at FROM pages
WHERE kind != 'template'
ORDER BY journal_date IS NOT NULL, created_at",
)?;
let rows = st.query_map([], |r| {
@@ -94,6 +100,7 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
})?;
for row in rows {
let (id, title, journal_date, origin_journal, created_at) = row?;
let tags = page_tags.get(&id).cloned().unwrap_or_default();
index.insert(id.clone(), nodes.len() as u32);
nodes.push(GraphNode {
id,
@@ -105,6 +112,9 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
backlinks: 0,
cluster: 0,
primary_tag: None,
is_hub: false,
home_hub: None,
tags,
});
}
}
@@ -203,6 +213,22 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
}
}
// Hub membership (hub → member), cycles already broken by `structure()`.
let structure = g.structure()?;
for h in &structure.hubs {
let Some(&hi) = index.get(&h.page.to_string()) else {
continue;
};
nodes[hi as usize].is_hub = true;
for m in &h.members {
if let Some(&mi) = index.get(&m.to_string()) {
b.add(hi, mi, edge_kind::CONTAINS, 1.0);
}
}
}
tagged(g, &index, &by_key, &mut b)?;
// Stable edge order (sources, then targets, then kind).
let mut edges: Vec<((u32, u32, u8), f32)> = b.edges.into_iter().collect();
edges.sort_by_key(|&(k, _)| k);
@@ -234,6 +260,12 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
.map(|(&t, _)| t);
}
for (page, home) in &structure.home {
if let (Some(&i), Some(&h)) = (index.get(&page.to_string()), index.get(&home.to_string())) {
nodes[i as usize].home_hub = Some(h);
}
}
let mut out = GraphData {
nodes,
sources: Vec::with_capacity(edges.len()),
@@ -251,6 +283,24 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
Ok(out)
}
/// A page filed under a tag page gets one `TAGGED` edge to it.
fn tagged(
g: &Graph,
index: &HashMap<String, u32>,
by_key: &HashMap<String, u32>,
b: &mut Builder,
) -> Result<()> {
let mut st = g.conn().prepare("SELECT tag_key, page_id FROM page_tags")?;
let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
for row in rows {
let (tag, page) = row?;
if let (Some(&s), Some(&t)) = (index.get(&page), by_key.get(&tag)) {
b.add(s, t, edge_kind::TAGGED, 1.0);
}
}
Ok(())
}
/// Unlinked references: a non-journal page title (or alias) appearing as whole words in a
/// block of another page that does not already reference it. Titles are indexed by their
/// first word so each block is scanned once.
+4
View File
@@ -4,6 +4,8 @@
//! - `outline`: block editing (insert, update, move, indent/outdent, merge, delete).
//! - `search`: title/block lookup (stopgap until `synapse-search` is wired).
//! - `graph_view`: the whole page-level graph for the graph views (cached by op seq).
//! - `structure`: hubs (folder-like pages), namespaces and the legacy page purge.
//! - `tags`: free-form tags on pages (names, not pages) and their vocabulary.
//! - `layout`: Barnes-Hut force-directed layout, stepped from Dart off the UI thread.
//!
//! Extension points for Phase 2 (one module each, methods on `SynapseGraph` or their own
@@ -17,3 +19,5 @@ pub mod graph_view;
pub mod layout;
pub mod outline;
pub mod search;
pub mod structure;
pub mod tags;
+304
View File
@@ -0,0 +1,304 @@
//! Hubs (folder-like pages), namespaces and the legacy page purge. Rules and membership
//! live in `synapse_core::structure`; this module shapes them for the UI.
use super::dto::{
HubDto, HubPreviewDto, HubsDto, LegacyCandidate, NamespaceEntry, PageBrief, PageDto,
PageStructure,
};
use super::graph::{SynapseGraph, parse_id};
use anyhow::{Result, anyhow};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use synapse_core::{
Graph, HubConversion, PageId, Structure, is_legacy_page, namespace_parent, title_key,
};
impl SynapseGraph {
/// Every hub with its members, and the root hubs.
pub fn hubs(&self) -> Result<HubsDto> {
let g = self.lock();
let s = self.structure_of(&g)?;
let hub_ids: HashSet<PageId> = s.hubs.iter().map(|h| h.page).collect();
let member_of_hub: HashSet<PageId> = s
.hubs
.iter()
.flat_map(|h| h.members.iter().copied())
.collect();
let mut briefs: HashMap<PageId, PageBrief> = HashMap::new();
let mut hubs = Vec::with_capacity(s.hubs.len());
for h in &s.hubs {
let members = h
.members
.iter()
.map(|&m| brief(&g, &mut briefs, m))
.collect::<Result<Vec<_>>>()?;
hubs.push(HubDto {
id: h.page.to_string(),
title: h.title.clone(),
description: h.description.clone(),
depth: h.depth,
sub_hubs: h
.members
.iter()
.filter(|m| hub_ids.contains(m))
.map(|m| m.to_string())
.collect(),
members,
});
}
let roots = s
.hubs
.iter()
.filter(|h| !member_of_hub.contains(&h.page))
.map(|h| h.page.to_string())
.collect();
Ok(HubsDto { hubs, roots })
}
/// Hub and namespace context of a page.
pub fn page_structure(&self, page_id: String) -> Result<PageStructure> {
let g = self.lock();
let id = parse_id(&page_id)?;
let page = g
.get_page(id)?
.ok_or_else(|| anyhow!("page {page_id} not found"))?;
let mut briefs = HashMap::new();
let members = if page.is_hub() {
g.hub_members(id)?
.into_iter()
.map(|m| brief(&g, &mut briefs, m))
.collect::<Result<Vec<_>>>()?
} else {
Vec::new()
};
let in_hubs = g
.hubs_of(id)?
.into_iter()
.map(|h| brief(&g, &mut briefs, h))
.collect::<Result<Vec<_>>>()?;
let mut path = Vec::new();
let mut title = page.title.as_str();
while let Some(parent) = namespace_parent(title) {
path.push(parent);
title = parent;
}
let ns_path = path
.into_iter()
.rev()
.map(|t| entry(&g, t.to_string(), None))
.collect::<Result<Vec<_>>>()?;
let ns_children = g
.namespace_children(&page.title)?
.into_iter()
.map(|(t, id)| entry(&g, t, id))
.collect::<Result<Vec<_>>>()?;
Ok(PageStructure {
is_hub: page.is_hub(),
description: page.description.clone(),
members,
in_hubs,
ns_path,
ns_children,
})
}
/// Creates an empty hub. Fails when the title is taken.
pub fn create_hub(&self, title: String, description: String) -> Result<PageDto> {
Ok(PageDto::from(
&self.lock().create_hub(&title, &description)?,
))
}
/// Id of the hub's template page (created empty when missing). Open it like any note to
/// edit the outline new notes of the hub start from.
pub fn hub_template(&self, hub_id: String) -> Result<String> {
Ok(self.lock().hub_template(parse_id(&hub_id)?)?.to_string())
}
/// Creates a note in the hub, starting from a copy of the hub's template.
pub fn create_page_from_template(&self, hub_id: String, title: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(
&g.create_page_from_template(parse_id(&hub_id)?, &title)?,
))
}
pub fn set_hub_description(&self, hub_id: String, description: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(
&g.set_hub_description(parse_id(&hub_id)?, &description)?,
))
}
/// Puts a page in a hub (no-op when it already is). Fails for journals, non-hub targets,
/// the hub itself and memberships that would create a cycle.
pub fn add_to_hub(&self, page_id: String, hub_id: String) -> Result<()> {
self.lock()
.add_to_hub(parse_id(&page_id)?, parse_id(&hub_id)?)?;
Ok(())
}
/// Takes a page out of a hub (no-op when it is not in it).
pub fn remove_from_hub(&self, page_id: String, hub_id: String) -> Result<()> {
self.lock()
.remove_from_hub(parse_id(&page_id)?, parse_id(&hub_id)?)?;
Ok(())
}
/// Defaults for converting a note into a hub.
pub fn hub_conversion_preview(&self, page_id: String) -> Result<HubPreviewDto> {
let g = self.lock();
let p = g.hub_conversion_preview(parse_id(&page_id)?)?;
let mut briefs = HashMap::new();
let members = p
.members
.iter()
.map(|&m| brief(&g, &mut briefs, m))
.collect::<Result<Vec<_>>>()?;
Ok(HubPreviewDto {
suggested_note_title: format!("{} (notes)", p.suggested_title),
suggested_title: p.suggested_title,
suggested_description: p.suggested_description,
members,
prose_blocks: p.prose_blocks,
blocks: p.blocks,
})
}
/// Turns a note into a hub in one transaction: renames it to `title` (links rewritten),
/// moves its outline to a new note `keep_outline_as` (or deletes it when `None`; a blank title is an error), sets the
/// description and adds `member_ids` (invalid members are skipped).
pub fn convert_to_hub(
&self,
page_id: String,
title: String,
description: String,
member_ids: Vec<String>,
keep_outline_as: Option<String>,
) -> Result<PageDto> {
let members = member_ids
.iter()
.map(|i| parse_id(i))
.collect::<Result<Vec<_>>>()?;
if keep_outline_as
.as_ref()
.is_some_and(|t| t.trim().is_empty())
{
return Err(anyhow!("the note that keeps the outline needs a title"));
}
let c = HubConversion {
title,
description,
members,
keep_outline_as,
};
let g = self.lock();
Ok(PageDto::from(&g.convert_to_hub(parse_id(&page_id)?, &c)?))
}
/// Turns a hub back into a note: description, then one `[[Member]]` block per member.
pub fn convert_to_note(&self, page_id: String) -> Result<PageDto> {
Ok(PageDto::from(
&self.lock().convert_to_note(parse_id(&page_id)?)?,
))
}
/// Pages that are probably leftovers of Logseq: its built-ins and pages with
/// `type:: system`. Only the organisational files (`contents`, `card`, `favorites`,
/// `hls__*`) and empty pages are preselected, and never a hub: a built-in title such as
/// `todo` may hold real content.
pub fn legacy_candidates(&self) -> Result<Vec<LegacyCandidate>> {
let g = self.lock();
let mut out = Vec::new();
for p in g.list_pages(false, u32::MAX, 0)? {
let key = title_key(&p.title);
let reason = if is_legacy_page(&p.title) {
if key.starts_with("hls__") {
"Logseq PDF highlights"
} else {
"Logseq built-in"
}
} else if p.properties.get("type").and_then(|v| v.as_str()) == Some("system") {
"type:: system"
} else {
continue;
};
let blocks = g.page_tree(p.id)?.len() as u32;
let organisational = matches!(key.as_str(), "contents" | "card" | "favorites")
|| key.starts_with("hls__");
out.push(LegacyCandidate {
id: p.id.to_string(),
title: p.title.clone(),
reason: reason.into(),
blocks,
preselected: !p.is_hub() && (blocks == 0 || organisational),
});
}
out.sort_by_key(|c| title_key(&c.title));
Ok(out)
}
/// Deletes pages and their blocks in one transaction. Returns how many existed.
pub fn purge_pages(&self, ids: Vec<String>) -> Result<u32> {
let ids = ids
.iter()
.map(|i| parse_id(i))
.collect::<Result<Vec<_>>>()?;
let n = self.lock().transaction(|g| {
let mut n = 0;
for id in ids {
if g.get_page(id)?.is_some() {
g.delete_page(id)?;
n += 1;
}
}
Ok(n)
})?;
Ok(n)
}
/// Structure of the graph, cached until it changes.
fn structure_of(&self, g: &Graph) -> Result<Arc<Structure>> {
let seq = g.last_seq()?;
let mut cache = self
.structure_cache
.lock()
.unwrap_or_else(|e| e.into_inner());
if let Some((s, data)) = cache.as_ref()
&& *s == seq
{
return Ok(Arc::clone(data));
}
let data = Arc::new(g.structure()?);
*cache = Some((seq, Arc::clone(&data)));
Ok(data)
}
}
fn brief(g: &Graph, cache: &mut HashMap<PageId, PageBrief>, id: PageId) -> Result<PageBrief> {
if let Some(b) = cache.get(&id) {
return Ok(b.clone());
}
let p = g
.get_page(id)?
.ok_or_else(|| anyhow!("page {id} not found"))?;
let b = PageBrief::from(&p);
cache.insert(id, b.clone());
Ok(b)
}
/// Namespace level; looks the page up when the caller does not know it.
fn entry(g: &Graph, title: String, id: Option<PageId>) -> Result<NamespaceEntry> {
let id = match id {
Some(id) => Some(id),
None => g
.page_by_title(&title)?
.filter(|p| !p.is_journal())
.map(|p| p.id),
};
Ok(NamespaceEntry {
title,
id: id.map(|i| i.to_string()),
})
}
+87
View File
@@ -0,0 +1,87 @@
//! Tags (topic pages that notes are filed under) and types (plain names saying what a page
//! is). Rules live in `synapse_core::{tags, types}`; this module shapes them for the UI.
use super::dto::{PageBrief, PageDto, TagDto};
use super::graph::{SynapseGraph, parse_id};
use anyhow::Result;
impl SynapseGraph {
/// Replaces the tags of a page (each title gets a tag page if it has none). Journals,
/// templates and tag pages cannot be tagged.
pub fn set_page_tags(&self, page_id: String, tags: Vec<String>) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(&g.set_page_tags(parse_id(&page_id)?, tags)?))
}
pub fn add_page_tag(&self, page_id: String, tag: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(&g.add_page_tag(parse_id(&page_id)?, &tag)?))
}
pub fn remove_page_tag(&self, page_id: String, tag: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(
&g.remove_page_tag(parse_id(&page_id)?, &tag)?,
))
}
/// Every tag page with its number of pages, most used first.
pub fn tag_catalog(&self) -> Result<Vec<TagDto>> {
Ok(self
.lock()
.tag_catalog()?
.into_iter()
.map(|t| TagDto {
name: t.name,
count: t.count,
suggested: t.suggested,
})
.collect())
}
/// Pages carrying a tag, most recently updated first.
pub fn pages_with_tag(&self, tag: String) -> Result<Vec<PageBrief>> {
let g = self.lock();
let mut out = Vec::new();
for id in g.pages_with_tag(&tag)? {
if let Some(p) = g.get_page(id)? {
out.push(PageBrief::from(&p));
}
}
Ok(out)
}
/// Replaces the types of a page. Journals and templates cannot be typed.
pub fn set_page_types(&self, page_id: String, types: Vec<String>) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(
&g.set_page_types(parse_id(&page_id)?, types)?,
))
}
pub fn add_page_type(&self, page_id: String, ty: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(&g.add_page_type(parse_id(&page_id)?, &ty)?))
}
pub fn remove_page_type(&self, page_id: String, ty: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(
&g.remove_page_type(parse_id(&page_id)?, &ty)?,
))
}
/// Types in use (most used first) followed by the seeded suggestions not used yet.
pub fn type_catalog(&self) -> Result<Vec<TagDto>> {
Ok(self
.lock()
.type_catalog()?
.into_iter()
.map(|t| TagDto {
name: t.name,
count: t.count,
suggested: t.suggested,
})
.collect())
}
}
File diff suppressed because it is too large. Load diff
+278 -1
View File
@@ -1,4 +1,4 @@
use synapse_ffi::api::dto::{BlockDto, Place, PlaceKind};
use synapse_ffi::api::dto::{BlockDto, Place, PlaceKind, edge_kind};
use synapse_ffi::api::graph::SynapseGraph;
fn open() -> (tempfile::TempDir, SynapseGraph) {
@@ -185,3 +185,280 @@ fn assets_round_trip() {
assert_eq!(std::fs::read(path).unwrap(), b"png");
assert!(g.asset_path("zz".into()).is_none());
}
#[test]
fn hubs_structure_and_graph_nodes() {
let (_d, g) = open();
let media = g.create_hub("Media".into(), " All media ".into()).unwrap();
assert!(media.is_hub);
assert_eq!(media.description, "All media");
let media = media.id;
let books = g
.create_hub("Media/Books".into(), String::new())
.unwrap()
.id;
let (novel, _) = page_with(&g, "Novel", &["text"]);
let (film, _) = page_with(&g, "Film", &["text"]);
let (note, _) = page_with(&g, "Note", &["plain text"]);
g.add_to_hub(books.clone(), media.clone()).unwrap();
g.add_to_hub(film.clone(), media.clone()).unwrap();
g.add_to_hub(novel.clone(), books.clone()).unwrap();
g.add_to_hub(novel.clone(), books.clone()).unwrap(); // no-op
// Rules surface as readable errors.
let err = g.add_to_hub(media.clone(), books.clone()).unwrap_err();
assert!(err.to_string().contains("cycle"), "{err}");
assert!(
g.add_to_hub(note.clone(), film.clone()).is_err(),
"not a hub"
);
assert!(g.add_to_hub(media.clone(), media.clone()).is_err(), "self");
let today = g.open_page(g.today()).unwrap().page.id;
assert!(g.add_to_hub(today, media.clone()).is_err(), "journal");
let err = g
.insert_block(
media.clone(),
place(PlaceKind::LastChildOf, None),
"x".into(),
)
.unwrap_err();
assert!(err.to_string().contains("hubs have no blocks"), "{err}");
let hubs = g.hubs().unwrap();
let titles: Vec<&str> = hubs.hubs.iter().map(|h| h.title.as_str()).collect();
assert_eq!(titles, ["Media", "Media/Books"]);
assert_eq!(hubs.roots, std::slice::from_ref(&media));
let m = &hubs.hubs[0];
assert_eq!((m.depth, m.description.as_str()), (0, "All media"));
let names: Vec<&str> = m.members.iter().map(|p| p.title.as_str()).collect();
assert_eq!(names, ["Media/Books", "Film"], "sub-hubs first");
assert!(m.members[0].is_hub && !m.members[1].is_hub);
assert_eq!(m.sub_hubs, std::slice::from_ref(&books));
assert_eq!(hubs.hubs[1].depth, 1);
let s = g.page_structure(novel.clone()).unwrap();
assert!(!s.is_hub && s.members.is_empty());
let in_hubs: Vec<&str> = s.in_hubs.iter().map(|p| p.title.as_str()).collect();
assert_eq!(in_hubs, ["Media/Books"], "one hub per page");
let s = g.page_structure(books.clone()).unwrap();
assert!(s.is_hub);
assert_eq!(s.members.len(), 1);
assert_eq!(s.ns_path.len(), 1);
assert_eq!(s.ns_path[0].id.as_deref(), Some(media.as_str()));
let s = g.page_structure(media.clone()).unwrap();
assert_eq!(s.description, "All media");
assert_eq!(s.ns_children[0].id.as_deref(), Some(books.as_str()));
g.set_hub_description(books.clone(), "Reading".into())
.unwrap();
g.remove_from_hub(film.clone(), media.clone()).unwrap();
assert!(g.page_structure(film.clone()).unwrap().in_hubs.is_empty());
// Graph data: hub flags, home hubs and CONTAINS edges.
let data = g.graph_data().unwrap();
let idx = |id: &str| data.nodes.iter().position(|n| n.id == id).unwrap() as u32;
let node = |id: &str| &data.nodes[idx(id) as usize];
assert!(node(&media).is_hub && node(&books).is_hub && !node(&novel).is_hub);
assert_eq!(node(&books).home_hub, Some(idx(&books)));
assert_eq!(node(&novel).home_hub, Some(idx(&books)), "deepest hub");
assert_eq!(node(&note).home_hub, None);
let contains = |s: &str, t: &str| {
(0..data.kinds.len()).any(|e| {
data.kinds[e] == edge_kind::CONTAINS
&& data.sources[e] == idx(s)
&& data.targets[e] == idx(t)
})
};
assert!(contains(&media, &books) && contains(&books, &novel));
assert!(!contains(&media, &novel));
assert!(!contains(&media, &film));
assert_eq!(node(&novel).backlinks, 1, "membership is structural");
// Converting back to a note: description, then one link per member.
let n = g.convert_to_note(books.clone()).unwrap();
assert!(!n.is_hub);
let page = g.page(books.clone()).unwrap().unwrap();
let texts: Vec<&str> = page.blocks.iter().map(|b| b.content.as_str()).collect();
assert_eq!(texts, ["Reading", "[[Novel]]"]);
let in_hubs = g.page_structure(novel.clone()).unwrap().in_hubs;
assert!(in_hubs.is_empty(), "the old hub is gone from its members");
}
#[test]
fn convert_note_to_hub() {
let (_d, g) = open();
let (area, _) = page_with(
&g,
"Work/Area",
&[
"Everything about **my** area of [[Work]].",
"[[Alpha]]",
"[[Beta]] #Gamma",
],
);
let p = g.hub_conversion_preview(area.clone()).unwrap();
assert_eq!(p.suggested_title, "Area");
assert_eq!(p.suggested_note_title, "Area (notes)");
assert_eq!(p.suggested_description, "Everything about my area of Work.");
let names: Vec<&str> = p.members.iter().map(|m| m.title.as_str()).collect();
assert_eq!(names, ["Work", "Alpha", "Beta", "Gamma"]);
assert_eq!((p.prose_blocks, p.blocks), (1, 3));
let member_ids: Vec<String> = p.members.iter().skip(1).map(|m| m.id.clone()).collect();
let hub = g
.convert_to_hub(
area.clone(),
p.suggested_title.clone(),
p.suggested_description.clone(),
member_ids,
Some(p.suggested_note_title.clone()),
)
.unwrap();
assert!(hub.is_hub);
assert_eq!(
(hub.id.as_str(), hub.title.as_str()),
(area.as_str(), "Area")
);
assert!(g.page(area.clone()).unwrap().unwrap().blocks.is_empty());
let kept = g.page_by_title("Area (notes)".into()).unwrap().unwrap();
assert_eq!(kept.blocks.len(), 3);
let s = g.page_structure(area.clone()).unwrap();
let names: Vec<&str> = s.members.iter().map(|m| m.title.as_str()).collect();
assert_eq!(
names,
["Alpha", "Area (notes)", "Beta", "Gamma"],
"kept note is a member"
);
// A blank keep title is an error (never "delete the outline") and changes nothing.
let (blank, _) = page_with(&g, "Blank", &["keep me"]);
assert!(
g.convert_to_hub(
blank.clone(),
"Blank".into(),
String::new(),
vec![],
Some(" ".into())
)
.is_err()
);
assert!(!g.page(blank.clone()).unwrap().unwrap().page.is_hub);
assert_eq!(g.page(blank).unwrap().unwrap().blocks.len(), 1);
// A title clash is a readable error and changes nothing.
let (other, _) = page_with(&g, "Other", &["[[Alpha]]"]);
let err = g
.convert_to_hub(other.clone(), "Area".into(), String::new(), vec![], None)
.unwrap_err();
assert!(!err.to_string().is_empty());
assert!(!g.page(other.clone()).unwrap().unwrap().page.is_hub);
assert_eq!(g.page(other).unwrap().unwrap().blocks.len(), 1);
}
#[test]
fn legacy_candidates_and_purge() {
let (_d, g) = open();
let (todo, _) = page_with(&g, "TODO", &["a", "b"]);
let (hl, _) = page_with(&g, "hls__book", &[]);
let (sys, _) = page_with(&g, "Template", &["x"]);
let (keep, _) = page_with(&g, "Keep", &["x"]);
page_with(&g, "contents", &["- x"]);
page_with(&g, "now", &[]);
g.create_hub("later".into(), String::new()).unwrap();
{
let shared = g.shared();
let core = shared.lock().unwrap();
let mut props = synapse_core::Properties::new();
props.insert("type".into(), "system".into());
core.set_page_properties(sys.parse().unwrap(), props)
.unwrap();
}
let c = g.legacy_candidates().unwrap();
let by = |t: &str| c.iter().find(|x| x.title == t).unwrap();
assert_eq!(by("TODO").reason, "Logseq built-in");
assert!(
!by("TODO").preselected && by("TODO").blocks == 2,
"has content"
);
assert!(by("contents").preselected, "organisational page");
assert!(by("now").preselected, "empty built-in");
assert!(!by("later").preselected, "hubs are never preselected");
assert_eq!(by("hls__book").reason, "Logseq PDF highlights");
assert!(by("hls__book").preselected);
assert!(!by("Template").preselected);
assert_eq!(by("Template").reason, "type:: system");
assert!(c.iter().all(|x| x.title != "Keep"));
// A bad id rejects the call before anything is deleted.
assert!(g.purge_pages(vec![todo.clone(), "nope".into()]).is_err());
assert!(g.page(todo.clone()).unwrap().is_some());
assert_eq!(g.purge_pages(vec![todo.clone(), hl.clone()]).unwrap(), 2);
assert!(g.page(todo).unwrap().is_none() && g.page(hl).unwrap().is_none());
assert!(g.page(keep).unwrap().is_some());
}
#[test]
fn tags_are_pages_and_their_own_edge_kind() {
let (_d, g) = open();
let (a, _) = page_with(&g, "Rust", &["x"]);
let (b, _) = page_with(&g, "Go", &["y"]);
let (c, _) = page_with(&g, "Madrid", &["z"]);
for (p, tags) in [
(&a, vec!["tecnología", "idea"]),
(&b, vec!["Tecnología", "idea"]),
(&c, vec!["lugar"]),
] {
g.set_page_tags(p.clone(), tags.into_iter().map(String::from).collect())
.unwrap();
}
let data = g.graph_data().unwrap();
let idx = |id: &str| data.nodes.iter().position(|n| n.id == id).unwrap() as u32;
let title = |i: u32| data.nodes[i as usize].title.clone();
let mut tagged: Vec<(String, String)> = (0..data.kinds.len())
.filter(|&e| data.kinds[e] == edge_kind::TAGGED)
.map(|e| (title(data.sources[e]), title(data.targets[e])))
.collect();
tagged.sort();
let pair = |a: &str, b: &str| (a.to_string(), b.to_string());
assert_eq!(
tagged,
[
pair("Go", "idea"),
pair("Go", "tecnología"),
pair("Madrid", "lugar"),
pair("Rust", "idea"),
pair("Rust", "tecnología"),
],
"each page points at its tag pages"
);
// The tag page is a real node that counts backlinks, and the DTOs flag it.
let tp = &data.nodes[data
.nodes
.iter()
.position(|n| n.title == "tecnología")
.unwrap()];
assert_eq!(tp.backlinks, 2);
assert!(g.page(tp.id.clone()).unwrap().unwrap().page.is_tag);
assert_eq!(
idx(&a),
data.nodes.iter().position(|n| n.id == a).unwrap() as u32
);
let cat = g.tag_catalog().unwrap();
assert_eq!((cat[0].name.as_str(), cat[0].count), ("idea", 2));
}
#[test]
fn types_round_trip_through_the_api() {
let (_d, g) = open();
let (a, _) = page_with(&g, "Ana", &["x"]);
let p = g.add_page_type(a.clone(), "persona".into()).unwrap();
assert_eq!(p.types, ["persona"]);
assert!(g.type_catalog().unwrap().iter().any(|t| t.name == "lugar"));
assert!(
g.remove_page_type(a, "PERSONA".into())
.unwrap()
.types
.is_empty()
);
}