From 206b62d4ab16707a76558775316cb2fd4c15311c Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 06:33:33 +0100 Subject: [PATCH 01/11] feat(core): type definitions with an emoji icon, synced as PutTypeDef Schema v8 adds type_defs (name, icon, tombstone, hlc). create_type, set_type_icon, remove_type and rename_type; rename_tag moves the icon and type_catalog lists icons and defined-but-unused types. Co-Authored-By: Claude Opus 5.5 --- crates/synapse-core/src/lib.rs | 2 +- crates/synapse-core/src/model.rs | 43 ++++- crates/synapse-core/src/schema.rs | 12 +- crates/synapse-core/src/store.rs | 29 +++ crates/synapse-core/src/tags.rs | 7 +- crates/synapse-core/src/types.rs | 238 ++++++++++++++++++++++++- crates/synapse-core/tests/structure.rs | 154 +++++++++++++++- crates/synapse-search/src/lib.rs | 2 +- 8 files changed, 471 insertions(+), 16 deletions(-) diff --git a/crates/synapse-core/src/lib.rs b/crates/synapse-core/src/lib.rs index d877e03..77d1947 100644 --- a/crates/synapse-core/src/lib.rs +++ b/crates/synapse-core/src/lib.rs @@ -25,4 +25,4 @@ pub use structure::{ HubConversion, HubInfo, HubPreview, Structure, is_legacy_page, namespace_parent, }; pub use tags::{MAX_TAG_CHARS, TagInfo, normalize_tag}; -pub use types::SUGGESTED_TYPES; +pub use types::{MAX_ICON_CHARS, SUGGESTED_TYPES, normalize_icon}; diff --git a/crates/synapse-core/src/model.rs b/crates/synapse-core/src/model.rs index 7b72ddc..e3aab4b 100644 --- a/crates/synapse-core/src/model.rs +++ b/crates/synapse-core/src/model.rs @@ -183,12 +183,43 @@ pub struct OpRecord { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum Op { - UpsertPage { page: Page }, - DeletePage { id: PageId }, - UpsertBlock { block: Block }, - DeleteBlock { id: BlockId }, - PutAsset { asset: Asset }, - SetAlias { alias: String, page: Option }, + UpsertPage { + page: Page, + }, + DeletePage { + id: PageId, + }, + UpsertBlock { + block: Block, + }, + DeleteBlock { + id: BlockId, + }, + PutAsset { + asset: Asset, + }, + SetAlias { + alias: String, + page: Option, + }, + /// Metadata of a type name (its icon), last writer wins per [`title_key`] of the name. + PutTypeDef { + def: TypeDef, + }, +} + +/// Graph-wide metadata of a type name: types are names, not pages, so this is where their +/// icon lives (`type_defs` table, synced by [`Op::PutTypeDef`]). A definition also keeps a +/// type in the vocabulary while no page uses it. `removed` is a tombstone: the type was +/// deleted (it also hides a seeded suggestion of that name). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct TypeDef { + pub name: String, + /// An emoji (a short string) shown next to the names of pages of this type. + #[serde(default)] + pub icon: Option, + #[serde(default)] + pub removed: bool, } /// Fields for creating a page; defaults come from the graph clock. diff --git a/crates/synapse-core/src/schema.rs b/crates/synapse-core/src/schema.rs index c794ac6..9caee63 100644 --- a/crates/synapse-core/src/schema.rs +++ b/crates/synapse-core/src/schema.rs @@ -1,6 +1,6 @@ use rusqlite::OptionalExtension; -pub const VERSION: i64 = 7; +pub const VERSION: i64 = 8; pub const SCHEMA: &str = r#" CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); @@ -107,6 +107,15 @@ CREATE TABLE IF NOT EXISTS assets ( created_at INTEGER NOT NULL ); +-- v8: type metadata (icon), one row per type name key; `removed` rows are tombstones. +CREATE TABLE IF NOT EXISTS type_defs ( + type_key TEXT PRIMARY KEY, + name TEXT NOT NULL, + icon TEXT, + removed INTEGER NOT NULL DEFAULT 0, + hlc TEXT NOT NULL +); + CREATE TABLE IF NOT EXISTS tombstones (id TEXT PRIMARY KEY, hlc TEXT NOT NULL); CREATE TABLE IF NOT EXISTS ops ( @@ -272,6 +281,7 @@ pub fn migrate(conn: &rusqlite::Connection) -> rusqlite::Result<()> { // v7: a page's hub title is an implicit tag, so the index changes. rebuild_page_tags(conn)?; } + // v8: `type_defs` (type icons) is created empty by `SCHEMA`; nothing to convert. conn.execute( "INSERT OR REPLACE INTO meta(key, value) VALUES ('schema', ?1)", [VERSION.to_string()], diff --git a/crates/synapse-core/src/store.rs b/crates/synapse-core/src/store.rs index bbb5b07..269e7cc 100644 --- a/crates/synapse-core/src/store.rs +++ b/crates/synapse-core/src/store.rs @@ -1161,6 +1161,19 @@ impl Graph { true } } + Op::PutTypeDef { def } => { + let local: Option = self + .row( + "SELECT hlc FROM type_defs WHERE type_key=?1", + [title_key(&def.name)], + |r| r.get(0), + ) + .optional()?; + local.is_none_or(|l| hlc > l.as_str()) && { + self.write_type_def_row(def, hlc)?; + true + } + } }; if applied { self.log(hlc, op)?; @@ -1404,6 +1417,22 @@ impl Graph { Ok(()) } + /// Stores a type definition row (no op logged), keyed by the name's [`title_key`]. + pub(crate) fn write_type_def_row(&self, def: &TypeDef, hlc: &str) -> Result<()> { + self.exec( + "INSERT OR REPLACE INTO type_defs(type_key, name, icon, removed, hlc) + VALUES (?1, ?2, ?3, ?4, ?5)", + params![ + title_key(&def.name), + def.name.trim(), + def.icon, + def.removed, + hlc + ], + )?; + Ok(()) + } + /// Page whose own title (not alias) matches, case-insensitively. fn page_by_exact_title(&self, title: &str) -> Result> { Ok(self diff --git a/crates/synapse-core/src/tags.rs b/crates/synapse-core/src/tags.rs index 4183c36..3df79b6 100644 --- a/crates/synapse-core/src/tags.rs +++ b/crates/synapse-core/src/tags.rs @@ -23,6 +23,8 @@ pub struct TagInfo { pub count: u32, /// Part of the seeded suggestions (types only). pub suggested: bool, + /// Emoji of the type ([`crate::TypeDef::icon`]; types only). + pub icon: Option, } /// Cleans a tag name: leading `#` dropped, whitespace collapsed. `None` when nothing is left. @@ -153,6 +155,7 @@ impl Graph { name, count, suggested: false, + icon: None, }) .collect(); out.sort_by(|a, b| { @@ -165,7 +168,8 @@ impl Graph { /// Renames a tag everywhere: in the `tags` and `types` of every page carrying it (one /// transaction; each page is rewritten and logged, so it syncs). When a page already lists - /// `new`, the two merge. Returns the number of pages changed. A hub's implicit tag is never renamed (the hub page + /// `new`, the two merge. A type's definition (its icon) moves to the new name, keeping the + /// icon `new` already had. Returns the number of pages changed. A hub's implicit tag is never renamed (the hub page /// is not touched): only explicit tags and types change. pub fn rename_tag(&self, old: &str, new: &str) -> Result { let new = normalize_tag(new).ok_or_else(|| Error::Invalid("empty tag name".into()))?; @@ -191,6 +195,7 @@ impl Graph { changed += 1; } } + self.rename_type_def(&key, &new)?; tx.commit()?; Ok(changed) } diff --git a/crates/synapse-core/src/types.rs b/crates/synapse-core/src/types.rs index a4d047e..f35f83c 100644 --- a/crates/synapse-core/src/types.rs +++ b/crates/synapse-core/src/types.rs @@ -3,11 +3,17 @@ //! Types are plain names from a small vocabulary, not pages: a page carries its own //! ([`Page::types`], at most one name, kept as a list for compatibility; synced with the page, last writer wins). Topics are a different //! mechanism: see `tags`. +//! +//! Graph-wide metadata of a type (its emoji icon) is a [`TypeDef`] in the `type_defs` table, +//! keyed by [`title_key`] and synced with its own op ([`Op::PutTypeDef`], last writer wins per +//! name). A definition also keeps an unused type in the vocabulary; a removed one is a +//! tombstone that hides the type (even a seeded suggestion). use crate::error::{Error, Result}; -use crate::model::{Page, PageId, title_key}; +use crate::model::{Op, Page, PageId, TypeDef, title_key}; use crate::store::Graph; use crate::tags::{MAX_TAG_CHARS, TagInfo, normalize_tag}; +use rusqlite::OptionalExtension; use std::collections::HashMap; /// Types offered in pickers before they are used anywhere (the seed of the vocabulary). @@ -16,6 +22,36 @@ pub const SUGGESTED_TYPES: [&str; 10] = [ "receta", ]; +/// Longest icon, in characters (emoji sequences such as families or flags take several). +pub const MAX_ICON_CHARS: usize = 16; + +/// Cleans a type icon: trimmed; `None` when empty. Refused when longer than +/// [`MAX_ICON_CHARS`], when it contains whitespace or control characters, or when it is plain +/// ASCII (an icon is an emoji or symbol, not a word). +pub fn normalize_icon(raw: &str) -> Result> { + let t = raw.trim(); + if t.is_empty() { + return Ok(None); + } + if t.chars().count() > MAX_ICON_CHARS + || t.chars().any(|c| c.is_whitespace() || c.is_control()) + || t.is_ascii() + { + return Err(Error::Invalid(format!("{t:?} is not an emoji icon"))); + } + Ok(Some(t.to_string())) +} + +fn checked_type_name(name: &str) -> Result { + let n = normalize_tag(name).ok_or_else(|| Error::Invalid("empty type name".into()))?; + if n.chars().count() > MAX_TAG_CHARS { + return Err(Error::Invalid(format!( + "type {n:?} is longer than {MAX_TAG_CHARS} characters" + ))); + } + Ok(n) +} + impl Graph { /// Sets the single type of `page` (name cleaned), or clears it with `None`. Journals and /// templates cannot be typed. The type is stored as a list of zero or one name. @@ -51,9 +87,11 @@ impl Graph { Ok(p) } - /// The vocabulary: every type in use (spelling of its first page) plus the suggestions not - /// used yet. Used types first by count then name, then unused suggestions in seed order. + /// The vocabulary: every type in use (spelling of its first page), then types defined but + /// unused (by name), then the suggestions not used yet in seed order (unless removed). + /// Used types are sorted by count then name. Each carries its icon. pub fn type_catalog(&self) -> Result> { + let defs = self.type_defs()?; let mut st = self.conn().prepare_cached( "SELECT types FROM pages WHERE types != '[]' ORDER BY created_at, id", )?; @@ -66,12 +104,18 @@ impl Graph { } } let suggested = |k: &str| SUGGESTED_TYPES.iter().any(|s| title_key(s) == k); + let live_icon = |k: &str| { + defs.get(k) + .filter(|d| !d.removed) + .and_then(|d| d.icon.clone()) + }; let mut out: Vec = used .iter() .map(|(k, (name, count))| TagInfo { name: name.clone(), count: *count, suggested: suggested(k), + icon: live_icon(k), }) .collect(); out.sort_by(|a, b| { @@ -79,15 +123,199 @@ impl Graph { .cmp(&a.count) .then_with(|| title_key(&a.name).cmp(&title_key(&b.name))) }); + // Defined but unused types (created explicitly, or given an icon), by name. + let mut unused: Vec<&TypeDef> = defs + .iter() + .filter(|(k, d)| !d.removed && !used.contains_key(*k) && !suggested(k)) + .map(|(_, d)| d) + .collect(); + unused.sort_by_cached_key(|d| title_key(&d.name)); + out.extend(unused.into_iter().map(|d| TagInfo { + name: d.name.clone(), + count: 0, + suggested: false, + icon: d.icon.clone(), + })); for s in SUGGESTED_TYPES { - if !used.contains_key(&title_key(s)) { + let k = title_key(s); + let def = defs.get(&k); + if !used.contains_key(&k) && !def.is_some_and(|d| d.removed) { out.push(TagInfo { - name: s.to_string(), + name: def.map_or_else(|| s.to_string(), |d| d.name.clone()), count: 0, suggested: true, + icon: def.and_then(|d| d.icon.clone()), }); } } Ok(out) } + + /// Every stored type definition (removed ones included), by name key. + pub fn type_defs(&self) -> Result> { + let mut st = self + .conn() + .prepare_cached("SELECT type_key, name, icon, removed FROM type_defs")?; + let rows = st.query_map([], |r| { + Ok(( + r.get::<_, String>(0)?, + TypeDef { + name: r.get(1)?, + icon: r.get(2)?, + removed: r.get(3)?, + }, + )) + })?; + Ok(rows.collect::>()?) + } + + /// The definition of one type name (case-insensitive), removed ones included. + pub fn type_def(&self, name: &str) -> Result> { + Ok(self + .row( + "SELECT name, icon, removed FROM type_defs WHERE type_key=?1", + [title_key(name)], + |r| { + Ok(TypeDef { + name: r.get(0)?, + icon: r.get(1)?, + removed: r.get(2)?, + }) + }, + ) + .optional()?) + } + + /// Writes and logs a type definition (synced as [`Op::PutTypeDef`]). + fn put_type_def(&self, def: TypeDef) -> Result<()> { + let hlc = self.tick(); + self.write_type_def_row(&def, &hlc)?; + self.log(&hlc, &Op::PutTypeDef { def }) + } + + /// How a type name is spelled: its definition, else its first page, else `name`. + fn type_spelling(&self, name: &str) -> Result { + if let Some(d) = self.type_def(name)?.filter(|d| !d.removed) { + return Ok(d.name); + } + let key = title_key(name); + Ok(self + .type_catalog()? + .into_iter() + .find(|t| t.count > 0 && title_key(&t.name) == key) + .map_or_else(|| name.to_string(), |t| t.name)) + } + + /// Adds a type to the vocabulary even if no page uses it (no-op when it is already + /// defined). Returns its name as spelled in the graph. + pub fn create_type(&self, name: &str) -> Result { + let name = checked_type_name(name)?; + let tx = self.tx()?; + if let Some(d) = self.type_def(&name)?.filter(|d| !d.removed) { + tx.commit()?; + return Ok(d.name); + } + let name = self.type_spelling(&name)?; + self.put_type_def(TypeDef { + name: name.clone(), + icon: None, + removed: false, + })?; + tx.commit()?; + Ok(name) + } + + /// Sets (or with `None` clears) the emoji of a type, defining the type if needed (see + /// [`normalize_icon`] for what an icon may be). + pub fn set_type_icon(&self, name: &str, icon: Option<&str>) -> Result<()> { + let name = checked_type_name(name)?; + let icon = match icon { + Some(i) => normalize_icon(i)?, + None => None, + }; + let tx = self.tx()?; + let current = self.type_def(&name)?.filter(|d| !d.removed); + if current.as_ref().is_some_and(|d| d.icon == icon) { + tx.commit()?; + return Ok(()); + } + let name = self.type_spelling(&name)?; + self.put_type_def(TypeDef { + name, + icon, + removed: false, + })?; + tx.commit() + } + + /// Deletes a type: pages of that type lose it (their explicit tags stay) and its + /// definition becomes a tombstone (icon dropped; a seeded suggestion of that name is + /// hidden too). Returns the number of pages changed. + pub fn remove_type(&self, name: &str) -> Result { + let name = checked_type_name(name)?; + let key = title_key(&name); + let tx = self.tx()?; + let mut changed = 0; + for id in self.pages_with_tag(&name)? { + let Some(mut p) = self.get_page(id)? else { + continue; + }; + if p.page_type().is_some_and(|t| title_key(t) == key) { + p.types.clear(); + p.updated_at = self.now_ms(); + self.write_page(&p, &self.tick())?; + changed += 1; + } + } + let name = self.type_def(&name)?.map_or(name, |d| d.name); + self.put_type_def(TypeDef { + name, + icon: None, + removed: true, + })?; + tx.commit()?; + Ok(changed) + } + + /// Renames a type: like [`Graph::rename_tag`] (pages' types and same-name tags, merging + /// duplicates), and the type stays in the vocabulary under `new` with its icon even when + /// no page uses it (e.g. an unused suggestion). Returns the number of pages changed. + pub fn rename_type(&self, old: &str, new: &str) -> Result { + checked_type_name(new)?; + let tx = self.tx()?; + self.create_type(old)?; + let n = self.rename_tag(old, new)?; + tx.commit()?; + Ok(n) + } + + /// Moves the definition of type `old_key` to `new` (used by `rename_tag`): `new` keeps its + /// own icon if it has one, else takes the old one; the old name becomes a tombstone (only + /// the spelling changes when the keys match). No-op when `old_key` has no live definition. + pub(crate) fn rename_type_def(&self, old_key: &str, new: &str) -> Result<()> { + let Some(old) = self.type_def(old_key)?.filter(|d| !d.removed) else { + return Ok(()); + }; + if title_key(new) == old_key { + if old.name != new { + self.put_type_def(TypeDef { + name: new.to_string(), + ..old + })?; + } + return Ok(()); + } + let target = self.type_def(new)?.filter(|d| !d.removed); + let icon = target.and_then(|d| d.icon).or(old.icon); + self.put_type_def(TypeDef { + name: new.to_string(), + icon, + removed: false, + })?; + self.put_type_def(TypeDef { + name: old.name, + icon: None, + removed: true, + }) + } } diff --git a/crates/synapse-core/tests/structure.rs b/crates/synapse-core/tests/structure.rs index 35f5586..fdc2e38 100644 --- a/crates/synapse-core/tests/structure.rs +++ b/crates/synapse-core/tests/structure.rs @@ -506,7 +506,7 @@ fn old_ops_and_v2_databases_load() { r.get(0) }) .unwrap(); - assert_eq!(schema, "7"); + assert_eq!(schema, "8"); let p = g.get_page(id).unwrap().unwrap(); assert_eq!((p.kind, p.title.as_str()), (PageKind::Note, "Legacy")); let h = g.create_hub("New hub", "").unwrap(); @@ -996,3 +996,155 @@ fn v6_databases_gain_hub_tags() { let g = Graph::open(dir.path()).unwrap(); assert_eq!(g.pages_with_tag("anime").unwrap(), [a]); } + +fn type_row(g: &Graph, name: &str) -> Option<(String, u32, Option)> { + g.type_catalog() + .unwrap() + .into_iter() + .find(|t| synapse_core::title_key(&t.name) == synapse_core::title_key(name)) + .map(|t| (t.name, t.count, t.icon)) +} + +#[test] +fn types_carry_an_icon_and_can_exist_without_pages() { + let (_d, g) = graph(); + let p = page(&g, "Ada", &["x"]); + g.set_page_type(p, Some("persona")).unwrap(); + g.set_type_icon("Persona", Some(" 🧑 ")).unwrap(); + assert_eq!( + type_row(&g, "persona"), + Some(("persona".into(), 1, Some("🧑".into()))) + ); + // Unused suggestions keep listing (e.g. "sueño"), and can get an icon. + assert_eq!(type_row(&g, "sueño"), Some(("sueño".into(), 0, None))); + g.set_type_icon("sueño", Some("💭")).unwrap(); + assert_eq!( + type_row(&g, "sueño"), + Some(("sueño".into(), 0, Some("💭".into()))) + ); + // A type created explicitly lists with no pages. + assert_eq!(g.create_type(" Libro ").unwrap(), "Libro"); + assert_eq!(type_row(&g, "libro"), Some(("Libro".into(), 0, None))); + assert_eq!(g.create_type("LIBRO").unwrap(), "Libro"); + // Icons are short emoji, not words; clearing works. + assert!(invalid(g.set_type_icon("Libro", Some("ab")))); + assert!(invalid(g.set_type_icon("Libro", Some("📕 📗")))); + assert!(invalid(g.set_type_icon("Libro", Some(&"📕".repeat(17))))); + g.set_type_icon("Libro", Some("👨‍👩‍👧‍👦")).unwrap(); + g.set_type_icon("Libro", None).unwrap(); + assert_eq!(type_row(&g, "libro"), Some(("Libro".into(), 0, None))); + assert!(invalid(g.create_type(" "))); +} + +#[test] +fn renaming_a_type_keeps_its_icon_and_removing_drops_it() { + let (_d, g) = graph(); + let a = page(&g, "A", &["x"]); + let b = page(&g, "B", &["x"]); + g.set_page_type(a, Some("persona")).unwrap(); + g.set_page_type(b, Some("persona")).unwrap(); + g.add_page_tag(b, "persona").unwrap(); + g.set_type_icon("persona", Some("🧑")).unwrap(); + assert_eq!(g.rename_tag("persona", "Gente").unwrap(), 2); + assert_eq!( + type_row(&g, "gente"), + Some(("Gente".into(), 2, Some("🧑".into()))) + ); + // The old name is gone; a seeded suggestion of that name is not offered again. + assert_eq!(type_row(&g, "persona"), None); + // Merging into a type with its own icon keeps that icon. + g.set_type_icon("humano", Some("🙂")).unwrap(); + g.rename_tag("gente", "humano").unwrap(); + assert_eq!( + type_row(&g, "humano"), + Some(("humano".into(), 2, Some("🙂".into()))) + ); + // Renaming an unused suggestion through rename_type keeps it listed. + g.set_type_icon("sueño", Some("💭")).unwrap(); + assert_eq!(g.rename_type("sueño", "Sueños").unwrap(), 0); + assert_eq!( + type_row(&g, "sueños"), + Some(("Sueños".into(), 0, Some("💭".into()))) + ); + assert_eq!(type_row(&g, "sueño"), None); + // Case-only renames keep the definition. + g.rename_type("Sueños", "sueños").unwrap(); + assert_eq!( + type_row(&g, "sueños"), + Some(("sueños".into(), 0, Some("💭".into()))) + ); + + // Removing a type clears it from its pages (explicit tags stay) and drops the icon. + assert_eq!(g.remove_type("Humano").unwrap(), 2); + assert!(g.get_page(a).unwrap().unwrap().types.is_empty()); + assert_eq!(g.get_page(b).unwrap().unwrap().tags, ["humano"]); + assert_eq!(type_row(&g, "humano"), None); + // Defining it again starts without an icon. + g.create_type("humano").unwrap(); + assert_eq!(type_row(&g, "humano"), Some(("humano".into(), 0, None))); + // A removed suggestion stays hidden until used again. + g.remove_type("lugar").unwrap(); + assert_eq!(type_row(&g, "lugar"), None); + g.set_page_type(a, Some("lugar")).unwrap(); + assert_eq!(type_row(&g, "lugar"), Some(("lugar".into(), 1, None))); +} + +#[test] +fn type_definitions_sync_last_writer_wins() { + let (_a, a) = graph(); + let (_b, b) = graph(); + a.set_type_icon("persona", Some("🧑")).unwrap(); + a.create_type("Libro").unwrap(); + assert_eq!(ship(&a, &a, 0), 0, "own ops are not re-applied"); + ship(&a, &b, 0); + assert_eq!(type_row(&b, "persona").unwrap().2.as_deref(), Some("🧑")); + assert_eq!(type_row(&b, "libro"), Some(("Libro".into(), 0, None))); + let (seq_a, seq_b) = (a.last_seq().unwrap(), b.last_seq().unwrap()); + // Concurrent edits: both replicas end with the same icon. + a.set_type_icon("persona", Some("👤")).unwrap(); + b.set_type_icon("persona", Some("🙋")).unwrap(); + ship(&a, &b, seq_a); + ship(&b, &a, seq_b); + assert_eq!( + type_row(&a, "persona").unwrap().2, + type_row(&b, "persona").unwrap().2 + ); + // Removal travels as a tombstone. + let seq_a = a.last_seq().unwrap(); + a.remove_type("libro").unwrap(); + ship(&a, &b, seq_a); + assert_eq!(type_row(&b, "libro"), None); + // The op round-trips through JSON; missing fields default. + for r in a.ops_since(0, 1000).unwrap() { + let s = serde_json::to_string(&r.op).unwrap(); + assert_eq!(serde_json::from_str::(&s).unwrap(), r.op); + } + let op: Op = + serde_json::from_value(json!({"type": "put_type_def", "def": {"name": "x"}})).unwrap(); + assert!(matches!(op, Op::PutTypeDef { def } if def.icon.is_none() && !def.removed)); +} + +#[test] +fn v7_databases_gain_type_definitions() { + let dir = tempfile::tempdir().unwrap(); + { + let g = Graph::open(dir.path()).unwrap(); + let p = page(&g, "A", &["x"]); + g.set_page_type(p, Some("persona")).unwrap(); + g.conn().execute("DROP TABLE type_defs", []).unwrap(); + g.conn() + .execute("UPDATE meta SET value='7' WHERE key='schema'", []) + .unwrap(); + } + let g = Graph::open(dir.path()).unwrap(); + let schema: String = g + .conn() + .query_row("SELECT value FROM meta WHERE key='schema'", [], |r| { + r.get(0) + }) + .unwrap(); + assert_eq!(schema, "8"); + assert_eq!(type_row(&g, "persona"), Some(("persona".into(), 1, None))); + g.set_type_icon("persona", Some("🧑")).unwrap(); + assert_eq!(type_row(&g, "persona").unwrap().2.as_deref(), Some("🧑")); +} diff --git a/crates/synapse-search/src/lib.rs b/crates/synapse-search/src/lib.rs index 637907f..a8e9eb9 100644 --- a/crates/synapse-search/src/lib.rs +++ b/crates/synapse-search/src/lib.rs @@ -256,7 +256,7 @@ impl Search { } // The previous owner of an alias is not in the op, so refresh all pages. Op::SetAlias { .. } => all_pages = true, - Op::PutAsset { .. } => {} + Op::PutAsset { .. } | Op::PutTypeDef { .. } => {} } } stats.ops_processed += ops.len(); From 2b079a8d741d0529146472d806ae35f4089da47a Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 06:33:33 +0100 Subject: [PATCH 02/11] feat(history): export and restore type icons in types.json Co-Authored-By: Claude Opus 5.5 --- crates/synapse-history/src/export.rs | 33 ++++++++++++++++++++++++- crates/synapse-history/src/history.rs | 26 +++++++++++++++---- crates/synapse-history/src/restore.rs | 25 +++++++++++++++++++ crates/synapse-history/tests/history.rs | 32 ++++++++++++++++++++++++ 4 files changed, 110 insertions(+), 6 deletions(-) diff --git a/crates/synapse-history/src/export.rs b/crates/synapse-history/src/export.rs index 34cd397..1f28aa6 100644 --- a/crates/synapse-history/src/export.rs +++ b/crates/synapse-history/src/export.rs @@ -1,6 +1,6 @@ //! Deterministic Markdown export of pages. //! -//! Layout: `pages/.md`, `journals/YYYY_MM_DD.md`, `assets.json`. +//! Layout: `pages/.md`, `journals/YYYY_MM_DD.md`, `assets.json`, `types.json`. //! A page file starts with page properties (`key:: value`, aliases as `alias:: a, b`), //! then one `- ` bullet per block, nested with tabs. Block properties follow the content; //! blocks referenced by `((uuid))` carry an `id::` property. Hubs carry `synapse-kind:: hub` @@ -16,6 +16,8 @@ use synapse_core::{Block, BlockId, Graph, Page, Properties}; pub const PAGES_DIR: &str = "pages"; pub const JOURNALS_DIR: &str = "journals"; pub const MANIFEST: &str = "assets.json"; +/// Type definitions (names with their emoji icon), see [`render_types`]. +pub const TYPES_FILE: &str = "types.json"; /// Page property marking a hub or tag page (`synapse-kind:: hub|tag`); notes omit it. pub const KIND_PROP: &str = "synapse-kind"; /// Page property holding a hub's description. @@ -242,6 +244,35 @@ pub fn referenced_blocks(conn: &Connection) -> Result> { Ok(set) } +/// One entry of [`TYPES_FILE`]. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct TypeEntry { + pub name: String, + #[serde(default)] + pub icon: Option, +} + +/// Type definitions (`types.json`): the live ones (not removed), sorted by name key, so it is +/// deterministic. `None` when there are none (the file is left out). +pub fn render_types(graph: &Graph) -> Result> { + let defs: std::collections::BTreeMap = + graph.type_defs()?.into_iter().collect(); + let list: Vec = defs + .into_values() + .filter(|d| !d.removed) + .map(|d| TypeEntry { + name: d.name, + icon: d.icon, + }) + .collect(); + if list.is_empty() { + return Ok(None); + } + let mut s = serde_json::to_string_pretty(&list).map_err(Error::from)?; + s.push('\n'); + Ok(Some(s)) +} + /// Asset manifest (`assets.json`): sorted by hash, so it is deterministic. pub fn render_manifest(conn: &Connection) -> Result { let mut st = diff --git a/crates/synapse-history/src/history.rs b/crates/synapse-history/src/history.rs index a1e45ca..9c2e172 100644 --- a/crates/synapse-history/src/history.rs +++ b/crates/synapse-history/src/history.rs @@ -2,7 +2,7 @@ use crate::Result; use crate::error::Error; -use crate::export::{self, JOURNALS_DIR, MANIFEST, PAGES_DIR}; +use crate::export::{self, JOURNALS_DIR, MANIFEST, PAGES_DIR, TYPES_FILE}; use crate::repo::{CommitInfo, Files, Repo}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeSet, HashMap, HashSet}; @@ -202,7 +202,7 @@ impl History { Op::DeletePage { id } => touched.extend(graph.hub_members(id)?), // Deletions and moves do not say which page lost a block; those // pages are caught by the `updated_at` scan below. - Op::DeleteBlock { .. } | Op::PutAsset { .. } => {} + Op::DeleteBlock { .. } | Op::PutAsset { .. } | Op::PutTypeDef { .. } => {} // The previous owner of an alias is unknown. Op::SetAlias { .. } => everything = true, } @@ -270,6 +270,22 @@ impl History { .write_blob(export::render_manifest(graph.conn())?.as_bytes())?; let assets_changed = old_files.get(MANIFEST) != Some(&manifest); files.insert(MANIFEST.to_string(), manifest); + let types = match export::render_types(graph)? { + Some(text) => Some(self.repo.write_blob(text.as_bytes())?), + None => None, + }; + let types_changed = old_files.get(TYPES_FILE) != types.as_ref(); + match types { + Some(oid) => files.insert(TYPES_FILE.to_string(), oid), + None => files.remove(TYPES_FILE), + }; + let other = if assets_changed { + Some("assets updated") + } else if types_changed { + Some("types updated") + } else { + None + }; if self.opts.include_blobs { self.add_blobs(graph, &mut files)?; } @@ -284,7 +300,7 @@ impl History { self.save_state(&new_state)?; return Ok(None); } - let message = commit_message(&created, &edited, &deleted, assets_changed, seq_now); + let message = commit_message(&created, &edited, &deleted, other, seq_now); let id = self.repo.commit(&files, &message, now_ms / 1000)?; self.save_state(&new_state)?; Ok(Some(self.repo.commit_info(id)?.into())) @@ -430,7 +446,7 @@ fn commit_message( created: &BTreeSet, edited: &BTreeSet, deleted: &BTreeSet, - assets: bool, + other: Option<&str>, seq: i64, ) -> String { let plural = |n: usize| if n == 1 { "page" } else { "pages" }; @@ -445,7 +461,7 @@ fn commit_message( parts.push(format!("{} deleted", deleted.len())); } if parts.is_empty() { - parts.push(if assets { "assets updated" } else { "snapshot" }.to_string()); + parts.push(other.unwrap_or("snapshot").to_string()); } let mut titles: Vec<&String> = edited.iter().chain(created).chain(deleted).collect(); titles.sort(); diff --git a/crates/synapse-history/src/restore.rs b/crates/synapse-history/src/restore.rs index 353ffe2..8a040ae 100644 --- a/crates/synapse-history/src/restore.rs +++ b/crates/synapse-history/src/restore.rs @@ -20,6 +20,30 @@ pub struct RestoreReport { pub safety_snapshot: Option, } +/// Brings type definitions back to the snapshot's `types.json` (missing file: none). Types +/// defined now but not in the snapshot lose their icon and stay defined (a tombstone would +/// also hide a seeded suggestion of that name). Bad entries are skipped. +fn restore_types(graph: &Graph, history: &History, files: &crate::repo::Files) -> Result<()> { + let wanted: Vec = match files.get(export::TYPES_FILE) { + Some(oid) => serde_json::from_str(&history.read_blob(*oid)?).unwrap_or_default(), + None => Vec::new(), + }; + let mut keep: HashSet = HashSet::new(); + for t in &wanted { + if skip_invalid(graph.create_type(&t.name))?.is_some() + && skip_invalid(graph.set_type_icon(&t.name, t.icon.as_deref()))?.is_some() + { + keep.insert(synapse_core::title_key(&t.name)); + } + } + for (key, def) in graph.type_defs()? { + if !def.removed && def.icon.is_some() && !keep.contains(&key) { + graph.set_type_icon(&def.name, None)?; + } + } + Ok(()) +} + /// Test hook: fail after this many block writes/deletes. type Fault<'a> = &'a Cell>; @@ -436,6 +460,7 @@ impl History { report.removed += 1; } } + restore_types(graph, this, &files)?; Ok(()) })?; Ok(report) diff --git a/crates/synapse-history/tests/history.rs b/crates/synapse-history/tests/history.rs index c923140..645dd87 100644 --- a/crates/synapse-history/tests/history.rs +++ b/crates/synapse-history/tests/history.rs @@ -371,6 +371,38 @@ fn tags_round_trip_through_snapshots() { assert_eq!(g.pages_with_tag("idea").unwrap(), [note.id]); } +#[test] +fn type_icons_round_trip_through_snapshots() { + let (_d, g, mut h) = setup(); + let note = add(&g, "Ada", &["body"]); + g.set_page_type(note.id, Some("persona")).unwrap(); + let s0 = h.snapshot(&g, T0 + 100).unwrap().unwrap(); + assert!(h.file(&s0.id, export::TYPES_FILE).unwrap().is_none()); + + at(&g, T0 + 200); + g.set_type_icon("persona", Some("🧑")).unwrap(); + g.create_type("Libro").unwrap(); + let s1 = h.snapshot(&g, T0 + 500).unwrap().unwrap(); + assert_eq!(s1.summary, "types updated"); + let json = h.file(&s1.id, export::TYPES_FILE).unwrap().unwrap(); + assert!(json.contains("\"Libro\"") && json.contains("🧑"), "{json}"); + + at(&g, T0 + 1000); + g.set_type_icon("persona", Some("👤")).unwrap(); + g.set_type_icon("lugar", Some("📍")).unwrap(); + h.restore_graph(&g, &s1.id, T0 + 2000).unwrap(); + let icon = |name: &str| { + g.type_catalog() + .unwrap() + .into_iter() + .find(|t| t.name == name) + .and_then(|t| t.icon) + }; + assert_eq!(icon("persona").as_deref(), Some("🧑")); + assert_eq!(icon("lugar"), None); + assert!(g.type_catalog().unwrap().iter().any(|t| t.name == "Libro")); +} + #[test] fn hubs_round_trip_kind_description_and_memberships() { let (_d, g, mut h) = setup(); From 4fb3b39c03be7af8c817521bc7d35dfb8ebacacd Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 06:34:23 +0100 Subject: [PATCH 03/11] feat(core): tag catalog counts explicit, type and hub sources per tag Co-Authored-By: Claude Opus 5.5 --- crates/synapse-core/src/tags.rs | 30 +++++++++++++++----------- crates/synapse-core/src/types.rs | 3 +++ crates/synapse-core/tests/structure.rs | 24 +++++++++++++++++++++ 3 files changed, 45 insertions(+), 12 deletions(-) diff --git a/crates/synapse-core/src/tags.rs b/crates/synapse-core/src/tags.rs index 3df79b6..ebf4aa9 100644 --- a/crates/synapse-core/src/tags.rs +++ b/crates/synapse-core/src/tags.rs @@ -17,7 +17,7 @@ use std::collections::{HashMap, HashSet}; pub const MAX_TAG_CHARS: usize = 48; /// A tag with the number of pages filed under it (explicitly or through a type). -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct TagInfo { pub name: String, pub count: u32, @@ -25,6 +25,12 @@ pub struct TagInfo { pub suggested: bool, /// Emoji of the type ([`crate::TypeDef::icon`]; types only). pub icon: Option, + /// Pages listing it among their explicit tags (`tag_catalog` only). + pub explicit: u32, + /// Pages having it as their type (`tag_catalog` only). + pub typed: u32, + /// Pages carrying it because their hub has this title (`tag_catalog` only). + pub from_hub: u32, } /// Cleans a tag name: leading `#` dropped, whitespace collapsed. `None` when nothing is left. @@ -137,7 +143,7 @@ impl Graph { /// Every tag in use (listed, implied by a type or by the page's hub): spelling of its first /// page, with its page count. Most used first, then by name. pub fn tag_catalog(&self) -> Result> { - let mut used: HashMap = HashMap::new(); + let mut used: HashMap = HashMap::new(); let mut sources = schema::tag_sources(self.conn(), None)?; sources.sort_by(|a, b| a.id.cmp(&b.id)); for src in sources { @@ -145,19 +151,19 @@ impl Graph { for t in src.names() { let key = title_key(t); if seen.insert(key.clone()) { - used.entry(key).or_insert((t.clone(), 0)).1 += 1; + let info = used.entry(key.clone()).or_insert_with(|| TagInfo { + name: t.clone(), + ..Default::default() + }); + info.count += 1; + let is = |n: &String| title_key(n) == key; + info.explicit += u32::from(src.tags.iter().any(is)); + info.typed += u32::from(src.types.iter().take(1).any(is)); + info.from_hub += u32::from(src.hub.iter().any(is)); } } } - let mut out: Vec = used - .into_values() - .map(|(name, count)| TagInfo { - name, - count, - suggested: false, - icon: None, - }) - .collect(); + let mut out: Vec = used.into_values().collect(); out.sort_by(|a, b| { b.count .cmp(&a.count) diff --git a/crates/synapse-core/src/types.rs b/crates/synapse-core/src/types.rs index f35f83c..d54c5c4 100644 --- a/crates/synapse-core/src/types.rs +++ b/crates/synapse-core/src/types.rs @@ -116,6 +116,7 @@ impl Graph { count: *count, suggested: suggested(k), icon: live_icon(k), + ..Default::default() }) .collect(); out.sort_by(|a, b| { @@ -135,6 +136,7 @@ impl Graph { count: 0, suggested: false, icon: d.icon.clone(), + ..Default::default() })); for s in SUGGESTED_TYPES { let k = title_key(s); @@ -145,6 +147,7 @@ impl Graph { count: 0, suggested: true, icon: def.and_then(|d| d.icon.clone()), + ..Default::default() }); } } diff --git a/crates/synapse-core/tests/structure.rs b/crates/synapse-core/tests/structure.rs index fdc2e38..2d3b2b0 100644 --- a/crates/synapse-core/tests/structure.rs +++ b/crates/synapse-core/tests/structure.rs @@ -1089,6 +1089,30 @@ fn renaming_a_type_keeps_its_icon_and_removing_drops_it() { assert_eq!(type_row(&g, "lugar"), Some(("lugar".into(), 1, None))); } +#[test] +fn tag_catalog_says_where_each_tag_comes_from() { + let (_d, g) = graph(); + let h = hub(&g, "Anime"); + let a = page(&g, "A", &["x"]); + let b = page(&g, "B", &["x"]); + g.add_to_hub(a, h).unwrap(); + g.add_page_tag(a, "idea").unwrap(); + g.set_page_type(b, Some("Idea")).unwrap(); + g.add_page_tag(b, "idea").unwrap(); + let cat = g.tag_catalog().unwrap(); + let get = |n: &str| cat.iter().find(|t| t.name.eq_ignore_ascii_case(n)).unwrap(); + let idea = get("idea"); + assert_eq!( + (idea.count, idea.explicit, idea.typed, idea.from_hub), + (2, 2, 1, 0) + ); + let anime = get("anime"); + assert_eq!( + (anime.count, anime.explicit, anime.typed, anime.from_hub), + (1, 0, 0, 1) + ); +} + #[test] fn type_definitions_sync_last_writer_wins() { let (_a, a) = graph(); From 381e9044c4cf520009ca06f8d06d9395365dc14b Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 06:37:33 +0100 Subject: [PATCH 04/11] feat(ffi): type icon API and page types in list DTOs create_type, set_type_icon, rename_type and remove_type; TagDto carries the icon and tag sources; PageBrief, TitleHit, BacklinkGroup and GraphNode carry the page type. Bindings regenerated; MemoryBackend mirrors the core. Co-Authored-By: Claude Opus 5.5 --- app/lib/src/backend/graph_backend.dart | 25 +- app/lib/src/rust/api/dto.dart | 72 ++++- app/lib/src/rust/api/graph.dart | 15 +- app/lib/src/rust/frb_generated.dart | 361 ++++++++++++++++++---- app/test/support/memory_backend.dart | 174 ++++++++++- crates/synapse-core/src/types.rs | 17 ++ crates/synapse-ffi/src/api/dto.rs | 31 ++ crates/synapse-ffi/src/api/graph.rs | 26 +- crates/synapse-ffi/src/api/graph_view.rs | 8 + crates/synapse-ffi/src/api/search.rs | 7 +- crates/synapse-ffi/src/api/tags.rs | 35 ++- crates/synapse-ffi/src/frb_generated.rs | 374 ++++++++++++++++++++--- crates/synapse-ffi/tests/api.rs | 46 +++ 13 files changed, 1038 insertions(+), 153 deletions(-) diff --git a/app/lib/src/backend/graph_backend.dart b/app/lib/src/backend/graph_backend.dart index 32cb78e..4dfd49e 100644 --- a/app/lib/src/backend/graph_backend.dart +++ b/app/lib/src/backend/graph_backend.dart @@ -70,9 +70,22 @@ abstract class GraphBackend { Future setPageType(String pageId, String? type); - /// Types in use (most used first), then the seeded suggestions not used yet. + /// Types in use (most used first), then types defined but unused, then the seeded + /// suggestions not used yet; each with its emoji icon (`TagDto.icon`). Future> typeCatalog(); + /// Adds a type to the vocabulary even with no pages; returns its spelling. + Future createType(String name); + + /// Sets (or with `null` clears) the emoji of a type. Synced with the graph. + Future setTypeIcon(String name, String? icon); + + /// Renames a type (and same-name tags), keeping its icon; returns the pages changed. + Future renameType(String old, String new_); + + /// Deletes a type: its pages lose it and its icon goes; returns the pages changed. + Future removeType(String name); + /// Every tag in use (listed or implied by a type), most used first. Future> tagCatalog(); @@ -270,6 +283,16 @@ class FfiGraphBackend implements GraphBackend { Future removeTag(String name) => _g.removeTag(name: name); @override Future> typeCatalog() => _g.typeCatalog(); + @override + Future createType(String name) => _g.createType(name: name); + @override + Future setTypeIcon(String name, String? icon) => + _g.setTypeIcon(name: name, icon: icon); + @override + Future renameType(String old, String new_) => + _g.renameType(old: old, new_: new_); + @override + Future removeType(String name) => _g.removeType(name: name); @override Future> tagCatalog() => _g.tagCatalog(); diff --git a/app/lib/src/rust/api/dto.dart b/app/lib/src/rust/api/dto.dart index b8a7f2d..17dfdcd 100644 --- a/app/lib/src/rust/api/dto.dart +++ b/app/lib/src/rust/api/dto.dart @@ -8,7 +8,7 @@ import '../frb_generated.dart'; import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; // These functions are ignored because they are not marked as `pub`: `new` -// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `assert_fields_are_eq`, `assert_fields_are_eq`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `from` +// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `assert_fields_are_eq`, `assert_fields_are_eq`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `from`, `from` class AssetDto { final String hash; @@ -43,12 +43,16 @@ class BacklinkGroup { final String pageId; final String pageTitle; final bool isJournal; + + /// Type of the referencing page (for its icon). + final String? pageType; final List blocks; const BacklinkGroup({ required this.pageId, required this.pageTitle, required this.isJournal, + this.pageType, required this.blocks, }); @@ -57,6 +61,7 @@ class BacklinkGroup { pageId.hashCode ^ pageTitle.hashCode ^ isJournal.hashCode ^ + pageType.hashCode ^ blocks.hashCode; @override @@ -67,6 +72,7 @@ class BacklinkGroup { pageId == other.pageId && pageTitle == other.pageTitle && isJournal == other.isJournal && + pageType == other.pageType && blocks == other.blocks; } @@ -266,6 +272,9 @@ class GraphNode { /// display name, `degree` the number of pages carrying the tag. final bool isTag; + /// The page's type (tree labels show its icon; the network view does not). + final String? pageType; + const GraphNode({ required this.id, required this.title, @@ -280,6 +289,7 @@ class GraphNode { this.homeHub, required this.tags, required this.isTag, + this.pageType, }); @override @@ -296,7 +306,8 @@ class GraphNode { isHub.hashCode ^ homeHub.hashCode ^ tags.hashCode ^ - isTag.hashCode; + isTag.hashCode ^ + pageType.hashCode; @override bool operator ==(Object other) => @@ -315,7 +326,8 @@ class GraphNode { isHub == other.isHub && homeHub == other.homeHub && tags == other.tags && - isTag == other.isTag; + isTag == other.isTag && + pageType == other.pageType; } /// A hub (folder-like page) with its members. @@ -518,16 +530,24 @@ class PageBrief { final bool isJournal; final bool isHub; + /// The page's type (the UI shows its icon next to the title). + final String? pageType; + const PageBrief({ required this.id, required this.title, required this.isJournal, required this.isHub, + this.pageType, }); @override int get hashCode => - id.hashCode ^ title.hashCode ^ isJournal.hashCode ^ isHub.hashCode; + id.hashCode ^ + title.hashCode ^ + isJournal.hashCode ^ + isHub.hashCode ^ + pageType.hashCode; @override bool operator ==(Object other) => @@ -537,7 +557,8 @@ class PageBrief { id == other.id && title == other.title && isJournal == other.isJournal && - isHub == other.isHub; + isHub == other.isHub && + pageType == other.pageType; } /// Everything the page view needs in one call. @@ -753,14 +774,37 @@ class TagDto { /// One of the seeded suggestions. final bool suggested; + /// Emoji of a type (types only). + final String? icon; + + /// Pages listing it as an explicit tag (tags only). + final int explicit; + + /// Pages having it as their type (tags only). + final int typed; + + /// Pages carrying it through their hub (tags only; hub tags cannot be renamed or removed). + final int fromHub; + const TagDto({ required this.name, required this.count, required this.suggested, + this.icon, + required this.explicit, + required this.typed, + required this.fromHub, }); @override - int get hashCode => name.hashCode ^ count.hashCode ^ suggested.hashCode; + int get hashCode => + name.hashCode ^ + count.hashCode ^ + suggested.hashCode ^ + icon.hashCode ^ + explicit.hashCode ^ + typed.hashCode ^ + fromHub.hashCode; @override bool operator ==(Object other) => @@ -769,7 +813,11 @@ class TagDto { runtimeType == other.runtimeType && name == other.name && count == other.count && - suggested == other.suggested; + suggested == other.suggested && + icon == other.icon && + explicit == other.explicit && + typed == other.typed && + fromHub == other.fromHub; } class TimelineDayDto { @@ -831,14 +879,19 @@ class TitleHit { final String title; final bool isAlias; + /// Type of the page (for its icon). + final String? pageType; + const TitleHit({ required this.pageId, required this.title, required this.isAlias, + this.pageType, }); @override - int get hashCode => pageId.hashCode ^ title.hashCode ^ isAlias.hashCode; + int get hashCode => + pageId.hashCode ^ title.hashCode ^ isAlias.hashCode ^ pageType.hashCode; @override bool operator ==(Object other) => @@ -847,5 +900,6 @@ class TitleHit { runtimeType == other.runtimeType && pageId == other.pageId && title == other.title && - isAlias == other.isAlias; + isAlias == other.isAlias && + pageType == other.pageType; } diff --git a/app/lib/src/rust/api/graph.dart b/app/lib/src/rust/api/graph.dart index 3c49ca1..b646ff8 100644 --- a/app/lib/src/rust/api/graph.dart +++ b/app/lib/src/rust/api/graph.dart @@ -58,6 +58,9 @@ abstract class SynapseGraph implements RustOpaqueInterface { required String title, }); + /// Adds a type to the vocabulary even if no page uses it; returns its spelling. + Future createType({required String name}); + /// Deletes a block and its subtree. Future> deleteBlock({required String id}); @@ -183,12 +186,18 @@ abstract class SynapseGraph implements RustOpaqueInterface { /// of pages changed. Future removeTag({required String name}); + /// Deletes a type: its pages lose it and its icon is dropped; returns the pages changed. + Future removeType({required String name}); + Future renamePage({required String id, required String newTitle}); /// Renames a tag in the `tags` and `types` of every page carrying it; returns the number of /// pages changed. Future renameTag({required String old, required String new_}); + /// Renames a type (and same-name tags), keeping its icon; returns the pages changed. + Future renameType({required String old, required String new_}); + /// Blocks whose text contains `query` (for `((` autocomplete), most recent first. Future> searchBlocks({ required String query, @@ -220,6 +229,9 @@ abstract class SynapseGraph implements RustOpaqueInterface { /// typed. Future setPageType({required String pageId, String? pageType}); + /// Sets (or with `None` clears) the emoji of a type, defining the type if needed. + Future setTypeIcon({required String name, String? icon}); + /// Every tag in use (listed or implied by a type) with its number of pages, most used first. Future> tagCatalog(); @@ -229,7 +241,8 @@ abstract class SynapseGraph implements RustOpaqueInterface { /// Today's date (graph clock) as `YYYY-MM-DD`. String today(); - /// Types in use (most used first) followed by the seeded suggestions not used yet. + /// Types in use (most used first), then defined unused types, then the seeded suggestions + /// not used yet; each with its icon. Future> typeCatalog(); /// Replaces a block's Markdown (the debounced save while typing). diff --git a/app/lib/src/rust/frb_generated.dart b/app/lib/src/rust/frb_generated.dart index f605c8a..62cd249 100644 --- a/app/lib/src/rust/frb_generated.dart +++ b/app/lib/src/rust/frb_generated.dart @@ -69,7 +69,7 @@ class RustLib extends BaseEntrypoint { String get codegenVersion => '2.13.0'; @override - int get rustContentHash => -1472342481; + int get rustContentHash => 272705018; static const kDefaultExternalLibraryLoaderConfig = ExternalLibraryLoaderConfig( @@ -175,6 +175,11 @@ abstract class RustLibApi extends BaseApi { required String title, }); + Future crateApiGraphSynapseGraphCreateType({ + required SynapseGraph that, + required String name, + }); + Future> crateApiGraphSynapseGraphDeleteBlock({ required SynapseGraph that, required String id, @@ -344,6 +349,11 @@ abstract class RustLibApi extends BaseApi { required String name, }); + Future crateApiGraphSynapseGraphRemoveType({ + required SynapseGraph that, + required String name, + }); + Future crateApiGraphSynapseGraphRenamePage({ required SynapseGraph that, required String id, @@ -356,6 +366,12 @@ abstract class RustLibApi extends BaseApi { required String new_, }); + Future crateApiGraphSynapseGraphRenameType({ + required SynapseGraph that, + required String old, + required String new_, + }); + Future> crateApiGraphSynapseGraphSearchBlocks({ required SynapseGraph that, required String query, @@ -392,6 +408,12 @@ abstract class RustLibApi extends BaseApi { String? pageType, }); + Future crateApiGraphSynapseGraphSetTypeIcon({ + required SynapseGraph that, + required String name, + String? icon, + }); + Future> crateApiGraphSynapseGraphTagCatalog({ required SynapseGraph that, }); @@ -1070,6 +1092,44 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["that", "hubId", "title"], ); + @override + Future crateApiGraphSynapseGraphCreateType({ + required SynapseGraph that, + required String name, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(name, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 17, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_String, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphCreateTypeConstMeta, + argValues: [that, name], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphCreateTypeConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_create_type", + argNames: ["that", "name"], + ); + @override Future> crateApiGraphSynapseGraphDeleteBlock({ required SynapseGraph that, @@ -1087,7 +1147,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 17, + funcId: 18, port: port_, ); }, @@ -1125,7 +1185,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 18, + funcId: 19, port: port_, ); }, @@ -1156,7 +1216,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 19)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 20)!; }, codec: SseCodec( decodeSuccessData: sse_decode_String, @@ -1187,7 +1247,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 20, + funcId: 21, port: port_, ); }, @@ -1225,7 +1285,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 21, + funcId: 22, port: port_, ); }, @@ -1263,7 +1323,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 22, + funcId: 23, port: port_, ); }, @@ -1297,7 +1357,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 23, + funcId: 24, port: port_, ); }, @@ -1332,7 +1392,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 24, + funcId: 25, port: port_, ); }, @@ -1374,7 +1434,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 25, + funcId: 26, port: port_, ); }, @@ -1412,7 +1472,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 26, + funcId: 27, port: port_, ); }, @@ -1450,7 +1510,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 27, + funcId: 28, port: port_, ); }, @@ -1490,7 +1550,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 28, + funcId: 29, port: port_, ); }, @@ -1526,7 +1586,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 29, + funcId: 30, port: port_, ); }, @@ -1568,7 +1628,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 30, + funcId: 31, port: port_, ); }, @@ -1608,7 +1668,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 31, + funcId: 32, port: port_, ); }, @@ -1650,7 +1710,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 32, + funcId: 33, port: port_, ); }, @@ -1681,7 +1741,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 33, + funcId: 34, port: port_, ); }, @@ -1717,7 +1777,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 34, + funcId: 35, port: port_, ); }, @@ -1755,7 +1815,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 35, + funcId: 36, port: port_, ); }, @@ -1793,7 +1853,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 36, + funcId: 37, port: port_, ); }, @@ -1831,7 +1891,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 37, + funcId: 38, port: port_, ); }, @@ -1869,7 +1929,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 38, + funcId: 39, port: port_, ); }, @@ -1907,7 +1967,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 39, + funcId: 40, port: port_, ); }, @@ -1945,7 +2005,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 40, + funcId: 41, port: port_, ); }, @@ -1983,7 +2043,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 41, + funcId: 42, port: port_, ); }, @@ -2025,7 +2085,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 42, + funcId: 43, port: port_, ); }, @@ -2065,7 +2125,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 43, + funcId: 44, port: port_, ); }, @@ -2105,7 +2165,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 44, + funcId: 45, port: port_, ); }, @@ -2145,7 +2205,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 45, + funcId: 46, port: port_, ); }, @@ -2183,7 +2243,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 46, + funcId: 47, port: port_, ); }, @@ -2223,7 +2283,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 47, + funcId: 48, port: port_, ); }, @@ -2263,7 +2323,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 48, + funcId: 49, port: port_, ); }, @@ -2301,7 +2361,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 49, + funcId: 50, port: port_, ); }, @@ -2322,6 +2382,44 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["that", "name"], ); + @override + Future crateApiGraphSynapseGraphRemoveType({ + required SynapseGraph that, + required String name, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(name, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 51, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_u_32, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphRemoveTypeConstMeta, + argValues: [that, name], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphRemoveTypeConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_remove_type", + argNames: ["that", "name"], + ); + @override Future crateApiGraphSynapseGraphRenamePage({ required SynapseGraph that, @@ -2341,7 +2439,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 50, + funcId: 52, port: port_, ); }, @@ -2381,7 +2479,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 51, + funcId: 53, port: port_, ); }, @@ -2402,6 +2500,46 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["that", "old", "new_"], ); + @override + Future crateApiGraphSynapseGraphRenameType({ + required SynapseGraph that, + required String old, + required String new_, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(old, serializer); + sse_encode_String(new_, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 54, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_u_32, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphRenameTypeConstMeta, + argValues: [that, old, new_], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphRenameTypeConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_rename_type", + argNames: ["that", "old", "new_"], + ); + @override Future> crateApiGraphSynapseGraphSearchBlocks({ required SynapseGraph that, @@ -2421,7 +2559,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 52, + funcId: 55, port: port_, ); }, @@ -2461,7 +2599,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 53, + funcId: 56, port: port_, ); }, @@ -2501,7 +2639,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 54, + funcId: 57, port: port_, ); }, @@ -2541,7 +2679,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 55, + funcId: 58, port: port_, ); }, @@ -2581,7 +2719,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 56, + funcId: 59, port: port_, ); }, @@ -2621,7 +2759,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 57, + funcId: 60, port: port_, ); }, @@ -2642,6 +2780,46 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["that", "pageId", "pageType"], ); + @override + Future crateApiGraphSynapseGraphSetTypeIcon({ + required SynapseGraph that, + required String name, + String? icon, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(name, serializer); + sse_encode_opt_String(icon, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 61, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_unit, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphSetTypeIconConstMeta, + argValues: [that, name, icon], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphSetTypeIconConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_set_type_icon", + argNames: ["that", "name", "icon"], + ); + @override Future> crateApiGraphSynapseGraphTagCatalog({ required SynapseGraph that, @@ -2657,7 +2835,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 58, + funcId: 62, port: port_, ); }, @@ -2697,7 +2875,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 59, + funcId: 63, port: port_, ); }, @@ -2728,7 +2906,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 60)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 64)!; }, codec: SseCodec( decodeSuccessData: sse_decode_String, @@ -2759,7 +2937,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 61, + funcId: 65, port: port_, ); }, @@ -2799,7 +2977,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 62, + funcId: 66, port: port_, ); }, @@ -2920,13 +3098,14 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { BacklinkGroup dco_decode_backlink_group(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs final arr = raw as List; - if (arr.length != 4) - throw Exception('unexpected arr length: expect 4 but see ${arr.length}'); + if (arr.length != 5) + throw Exception('unexpected arr length: expect 5 but see ${arr.length}'); return BacklinkGroup( pageId: dco_decode_String(arr[0]), pageTitle: dco_decode_String(arr[1]), isJournal: dco_decode_bool(arr[2]), - blocks: dco_decode_list_block_dto(arr[3]), + pageType: dco_decode_opt_String(arr[3]), + blocks: dco_decode_list_block_dto(arr[4]), ); } @@ -3042,8 +3221,8 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { GraphNode dco_decode_graph_node(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs final arr = raw as List; - if (arr.length != 13) - throw Exception('unexpected arr length: expect 13 but see ${arr.length}'); + if (arr.length != 14) + throw Exception('unexpected arr length: expect 14 but see ${arr.length}'); return GraphNode( id: dco_decode_String(arr[0]), title: dco_decode_String(arr[1]), @@ -3058,6 +3237,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { homeHub: dco_decode_opt_box_autoadd_u_32(arr[10]), tags: dco_decode_list_String(arr[11]), isTag: dco_decode_bool(arr[12]), + pageType: dco_decode_opt_String(arr[13]), ); } @@ -3322,13 +3502,14 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { PageBrief dco_decode_page_brief(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs final arr = raw as List; - if (arr.length != 4) - throw Exception('unexpected arr length: expect 4 but see ${arr.length}'); + if (arr.length != 5) + throw Exception('unexpected arr length: expect 5 but see ${arr.length}'); return PageBrief( id: dco_decode_String(arr[0]), title: dco_decode_String(arr[1]), isJournal: dco_decode_bool(arr[2]), isHub: dco_decode_bool(arr[3]), + pageType: dco_decode_opt_String(arr[4]), ); } @@ -3427,12 +3608,16 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { TagDto dco_decode_tag_dto(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs final arr = raw as List; - if (arr.length != 3) - throw Exception('unexpected arr length: expect 3 but see ${arr.length}'); + if (arr.length != 7) + throw Exception('unexpected arr length: expect 7 but see ${arr.length}'); return TagDto( name: dco_decode_String(arr[0]), count: dco_decode_u_32(arr[1]), suggested: dco_decode_bool(arr[2]), + icon: dco_decode_opt_String(arr[3]), + explicit: dco_decode_u_32(arr[4]), + typed: dco_decode_u_32(arr[5]), + fromHub: dco_decode_u_32(arr[6]), ); } @@ -3466,12 +3651,13 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { TitleHit dco_decode_title_hit(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs final arr = raw as List; - if (arr.length != 3) - throw Exception('unexpected arr length: expect 3 but see ${arr.length}'); + if (arr.length != 4) + throw Exception('unexpected arr length: expect 4 but see ${arr.length}'); return TitleHit( pageId: dco_decode_String(arr[0]), title: dco_decode_String(arr[1]), isAlias: dco_decode_bool(arr[2]), + pageType: dco_decode_opt_String(arr[3]), ); } @@ -3612,11 +3798,13 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { var var_pageId = sse_decode_String(deserializer); var var_pageTitle = sse_decode_String(deserializer); var var_isJournal = sse_decode_bool(deserializer); + var var_pageType = sse_decode_opt_String(deserializer); var var_blocks = sse_decode_list_block_dto(deserializer); return BacklinkGroup( pageId: var_pageId, pageTitle: var_pageTitle, isJournal: var_isJournal, + pageType: var_pageType, blocks: var_blocks, ); } @@ -3751,6 +3939,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { var var_homeHub = sse_decode_opt_box_autoadd_u_32(deserializer); var var_tags = sse_decode_list_String(deserializer); var var_isTag = sse_decode_bool(deserializer); + var var_pageType = sse_decode_opt_String(deserializer); return GraphNode( id: var_id, title: var_title, @@ -3765,6 +3954,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { homeHub: var_homeHub, tags: var_tags, isTag: var_isTag, + pageType: var_pageType, ); } @@ -4167,11 +4357,13 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { var var_title = sse_decode_String(deserializer); var var_isJournal = sse_decode_bool(deserializer); var var_isHub = sse_decode_bool(deserializer); + var var_pageType = sse_decode_opt_String(deserializer); return PageBrief( id: var_id, title: var_title, isJournal: var_isJournal, isHub: var_isHub, + pageType: var_pageType, ); } @@ -4277,7 +4469,19 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { var var_name = sse_decode_String(deserializer); var var_count = sse_decode_u_32(deserializer); var var_suggested = sse_decode_bool(deserializer); - return TagDto(name: var_name, count: var_count, suggested: var_suggested); + var var_icon = sse_decode_opt_String(deserializer); + var var_explicit = sse_decode_u_32(deserializer); + var var_typed = sse_decode_u_32(deserializer); + var var_fromHub = sse_decode_u_32(deserializer); + return TagDto( + name: var_name, + count: var_count, + suggested: var_suggested, + icon: var_icon, + explicit: var_explicit, + typed: var_typed, + fromHub: var_fromHub, + ); } @protected @@ -4309,7 +4513,13 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { var var_pageId = sse_decode_String(deserializer); var var_title = sse_decode_String(deserializer); var var_isAlias = sse_decode_bool(deserializer); - return TitleHit(pageId: var_pageId, title: var_title, isAlias: var_isAlias); + var var_pageType = sse_decode_opt_String(deserializer); + return TitleHit( + pageId: var_pageId, + title: var_title, + isAlias: var_isAlias, + pageType: var_pageType, + ); } @protected @@ -4449,6 +4659,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_String(self.pageId, serializer); sse_encode_String(self.pageTitle, serializer); sse_encode_bool(self.isJournal, serializer); + sse_encode_opt_String(self.pageType, serializer); sse_encode_list_block_dto(self.blocks, serializer); } @@ -4557,6 +4768,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_opt_box_autoadd_u_32(self.homeHub, serializer); sse_encode_list_String(self.tags, serializer); sse_encode_bool(self.isTag, serializer); + sse_encode_opt_String(self.pageType, serializer); } @protected @@ -4942,6 +5154,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_String(self.title, serializer); sse_encode_bool(self.isJournal, serializer); sse_encode_bool(self.isHub, serializer); + sse_encode_opt_String(self.pageType, serializer); } @protected @@ -5016,6 +5229,10 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_String(self.name, serializer); sse_encode_u_32(self.count, serializer); sse_encode_bool(self.suggested, serializer); + sse_encode_opt_String(self.icon, serializer); + sse_encode_u_32(self.explicit, serializer); + sse_encode_u_32(self.typed, serializer); + sse_encode_u_32(self.fromHub, serializer); } @protected @@ -5043,6 +5260,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_String(self.pageId, serializer); sse_encode_String(self.title, serializer); sse_encode_bool(self.isAlias, serializer); + sse_encode_opt_String(self.pageType, serializer); } @protected @@ -5222,6 +5440,10 @@ class SynapseGraphImpl extends RustOpaque implements SynapseGraph { title: title, ); + /// Adds a type to the vocabulary even if no page uses it; returns its spelling. + Future createType({required String name}) => RustLib.instance.api + .crateApiGraphSynapseGraphCreateType(that: this, name: name); + /// Deletes a block and its subtree. Future> deleteBlock({required String id}) => RustLib .instance @@ -5436,6 +5658,10 @@ class SynapseGraphImpl extends RustOpaque implements SynapseGraph { Future removeTag({required String name}) => RustLib.instance.api .crateApiGraphSynapseGraphRemoveTag(that: this, name: name); + /// Deletes a type: its pages lose it and its icon is dropped; returns the pages changed. + Future removeType({required String name}) => RustLib.instance.api + .crateApiGraphSynapseGraphRemoveType(that: this, name: name); + Future renamePage({required String id, required String newTitle}) => RustLib.instance.api.crateApiGraphSynapseGraphRenamePage( that: this, @@ -5450,6 +5676,12 @@ class SynapseGraphImpl extends RustOpaque implements SynapseGraph { .api .crateApiGraphSynapseGraphRenameTag(that: this, old: old, new_: new_); + /// Renames a type (and same-name tags), keeping its icon; returns the pages changed. + Future renameType({required String old, required String new_}) => RustLib + .instance + .api + .crateApiGraphSynapseGraphRenameType(that: this, old: old, new_: new_); + /// Blocks whose text contains `query` (for `((` autocomplete), most recent first. Future> searchBlocks({ required String query, @@ -5507,6 +5739,12 @@ class SynapseGraphImpl extends RustOpaque implements SynapseGraph { pageType: pageType, ); + /// Sets (or with `None` clears) the emoji of a type, defining the type if needed. + Future setTypeIcon({required String name, String? icon}) => RustLib + .instance + .api + .crateApiGraphSynapseGraphSetTypeIcon(that: this, name: name, icon: icon); + /// Every tag in use (listed or implied by a type) with its number of pages, most used first. Future> tagCatalog() => RustLib.instance.api.crateApiGraphSynapseGraphTagCatalog(that: this); @@ -5523,7 +5761,8 @@ class SynapseGraphImpl extends RustOpaque implements SynapseGraph { String today() => RustLib.instance.api.crateApiGraphSynapseGraphToday(that: this); - /// Types in use (most used first) followed by the seeded suggestions not used yet. + /// Types in use (most used first), then defined unused types, then the seeded suggestions + /// not used yet; each with its icon. Future> typeCatalog() => RustLib.instance.api.crateApiGraphSynapseGraphTypeCatalog(that: this); diff --git a/app/test/support/memory_backend.dart b/app/test/support/memory_backend.dart index eae55ea..7d98713 100644 --- a/app/test/support/memory_backend.dart +++ b/app/test/support/memory_backend.dart @@ -267,7 +267,11 @@ class MemoryBackend implements GraphBackend { Future> outline(String pageId) async => _dto(pageId); @override - Future> backlinks(String pageId) async => []; + Future> backlinks(String pageId) async => + backlinkGroups[pageId] ?? []; + + /// Linked references returned by `backlinks`, by target page id (tests fill it). + final backlinkGroups = >{}; @override Future> related(String pageId, {int limit = 12}) async => []; @override @@ -286,7 +290,14 @@ class MemoryBackend implements GraphBackend { (p) => p.journalDate == null && p.title.toLowerCase().contains(q), ) .take(limit) - .map((p) => TitleHit(pageId: p.id, title: p.title, isAlias: false)) + .map( + (p) => TitleHit( + pageId: p.id, + title: p.title, + isAlias: false, + pageType: p.pageType, + ), + ) .toList(); } @@ -335,6 +346,7 @@ class MemoryBackend implements GraphBackend { title: p.title, isJournal: p.journalDate != null, isHub: p.isHub, + pageType: p.pageType, ); void _put( @@ -499,29 +511,160 @@ class MemoryBackend implements GraphBackend { return pages[pageId]!; } + /// Type definitions like the core's `type_defs`: key -> (name, icon, removed). + final typeDefs = {}; + + ({String name, String? icon, bool removed})? _liveDef(String name) { + final d = typeDefs[_tagKey(name)]; + return d == null || d.removed ? null : d; + } + @override Future> typeCatalog() async { final used = {}; for (final p in pages.values) { for (final t in [if (p.pageType != null) p.pageType!]) { final k = _tagKey(t); - used[k] = TagDto( - name: used[k]?.name ?? t, - count: (used[k]?.count ?? 0) + 1, + used[k] = _tag( + used[k]?.name ?? t, + (used[k]?.count ?? 0) + 1, suggested: suggestedTypes.contains(k), + icon: _liveDef(k)?.icon, ); } } final out = used.values.toList() - ..sort((a, b) => b.count.compareTo(a.count)); + ..sort((a, b) { + final c = b.count.compareTo(a.count); + return c != 0 ? c : _tagKey(a.name).compareTo(_tagKey(b.name)); + }); + final unused = + typeDefs.entries + .where( + (e) => + !e.value.removed && + !used.containsKey(e.key) && + !suggestedTypes.contains(e.key), + ) + .map((e) => e.value) + .toList() + ..sort((a, b) => _tagKey(a.name).compareTo(_tagKey(b.name))); + out.addAll(unused.map((d) => _tag(d.name, 0, icon: d.icon))); for (final s in suggestedTypes) { - if (!used.containsKey(s)) { - out.add(TagDto(name: s, count: 0, suggested: true)); + final d = typeDefs[s]; + if (!used.containsKey(s) && !(d?.removed ?? false)) { + out.add(_tag(d?.name ?? s, 0, suggested: true, icon: d?.icon)); } } return out; } + TagDto _tag( + String name, + int count, { + bool suggested = false, + String? icon, + int explicit = 0, + int typed = 0, + int fromHub = 0, + }) => TagDto( + name: name, + count: count, + suggested: suggested, + icon: icon, + explicit: explicit, + typed: typed, + fromHub: fromHub, + ); + + String _typeName(String raw) { + final n = _normTag(raw); + if (n.isEmpty) throw Exception('Empty type name'); + return n; + } + + /// Spelling of a type: its definition, else a page using it, else [name]. + String _typeSpelling(String name) { + final d = _liveDef(name); + if (d != null) return d.name; + for (final p in pages.values) { + if (p.pageType != null && _tagKey(p.pageType!) == _tagKey(name)) { + return p.pageType!; + } + } + return name; + } + + @override + Future createType(String name) async { + final n = _typeName(name); + final d = _liveDef(n); + if (d != null) return d.name; + final spelled = _typeSpelling(n); + typeDefs[_tagKey(n)] = (name: spelled, icon: null, removed: false); + return spelled; + } + + @override + Future setTypeIcon(String name, String? icon) async { + final n = _typeName(name); + final i = icon?.trim(); + if (i != null && + i.isNotEmpty && + (i.runes.length > 16 || + i.contains(RegExp(r'\s')) || + i.runes.every((r) => r < 128))) { + throw Exception('Not an emoji icon'); + } + typeDefs[_tagKey(n)] = ( + name: _typeSpelling(n), + icon: (i == null || i.isEmpty) ? null : i, + removed: false, + ); + } + + @override + Future renameType(String old, String new_) async { + _typeName(new_); + await createType(old); + return renameTag(old, new_); + } + + /// Moves a live type definition to [name] (`renameTag`, like the core). + void _renameTypeDef(String old, String name) { + final d = _liveDef(old); + if (d == null) return; + if (_tagKey(old) == _tagKey(name)) { + typeDefs[_tagKey(name)] = (name: name, icon: d.icon, removed: false); + return; + } + final target = _liveDef(name); + typeDefs[_tagKey(name)] = ( + name: name, + icon: target?.icon ?? d.icon, + removed: false, + ); + typeDefs[_tagKey(old)] = (name: d.name, icon: null, removed: true); + } + + @override + Future removeType(String name) async { + final n = _typeName(name); + var count = 0; + for (final p in pages.values.toList()) { + if (p.pageType != null && _tagKey(p.pageType!) == _tagKey(n)) { + _put(p, clearType: true); + count++; + } + } + typeDefs[_tagKey(n)] = ( + name: typeDefs[_tagKey(n)]?.name ?? n, + icon: null, + removed: true, + ); + return count; + } + @override Future addPageTag(String pageId, String tag) => setPageTags(pageId, [...pages[pageId]!.tags, tag]); @@ -537,12 +680,17 @@ class MemoryBackend implements GraphBackend { Future> tagCatalog() async { final used = {}; for (final p in pages.values) { + final hub = _hubTag(p); for (final t in allTags(p)) { final k = _tagKey(t); - used[k] = TagDto( - name: used[k]?.name ?? t, - count: (used[k]?.count ?? 0) + 1, - suggested: false, + final prev = used[k]; + bool isK(String? x) => x != null && _tagKey(x) == k; + used[k] = _tag( + prev?.name ?? t, + (prev?.count ?? 0) + 1, + explicit: (prev?.explicit ?? 0) + (p.tags.any(isK) ? 1 : 0), + typed: (prev?.typed ?? 0) + (isK(p.pageType) ? 1 : 0), + fromHub: (prev?.fromHub ?? 0) + (isK(hub) ? 1 : 0), ); } } @@ -581,6 +729,7 @@ class MemoryBackend implements GraphBackend { _put(p, tags: tags, pageType: hasType ? name : null); n++; } + _renameTypeDef(old, name); return n; } @@ -985,6 +1134,7 @@ class MemoryBackend implements GraphBackend { homeHub: home[ids[i]] == null ? null : index[home[ids[i]]!], tags: allTags(pages[ids[i]]!), isTag: false, + pageType: pages[ids[i]]!.pageType, ), for (var j = 0; j < tagKeys.length; j++) GraphNode( diff --git a/crates/synapse-core/src/types.rs b/crates/synapse-core/src/types.rs index d54c5c4..d504f65 100644 --- a/crates/synapse-core/src/types.rs +++ b/crates/synapse-core/src/types.rs @@ -154,6 +154,23 @@ impl Graph { Ok(out) } + /// The type of every typed page. + pub fn all_page_types(&self) -> Result> { + let mut st = self + .conn() + .prepare_cached("SELECT id, types FROM pages WHERE types != '[]'")?; + let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?; + let mut out = HashMap::new(); + for row in rows { + let (id, types) = row?; + let types: Vec = serde_json::from_str(&types).unwrap_or_default(); + if let Some(t) = types.into_iter().next() { + out.insert(crate::store::parse_id(&id)?, t); + } + } + Ok(out) + } + /// Every stored type definition (removed ones included), by name key. pub fn type_defs(&self) -> Result> { let mut st = self diff --git a/crates/synapse-ffi/src/api/dto.rs b/crates/synapse-ffi/src/api/dto.rs index 4732f3e..44927e0 100644 --- a/crates/synapse-ffi/src/api/dto.rs +++ b/crates/synapse-ffi/src/api/dto.rs @@ -50,6 +50,28 @@ pub struct TagDto { pub count: u32, /// One of the seeded suggestions. pub suggested: bool, + /// Emoji of a type (types only). + pub icon: Option, + /// Pages listing it as an explicit tag (tags only). + pub explicit: u32, + /// Pages having it as their type (tags only). + pub typed: u32, + /// Pages carrying it through their hub (tags only; hub tags cannot be renamed or removed). + pub from_hub: u32, +} + +impl From for TagDto { + fn from(t: synapse_core::TagInfo) -> Self { + Self { + name: t.name, + count: t.count, + suggested: t.suggested, + icon: t.icon, + explicit: t.explicit, + typed: t.typed, + from_hub: t.from_hub, + } + } } /// One row of the outline, in pre-order. @@ -110,6 +132,8 @@ pub struct BacklinkGroup { pub page_id: String, pub page_title: String, pub is_journal: bool, + /// Type of the referencing page (for its icon). + pub page_type: Option, pub blocks: Vec, } @@ -119,6 +143,8 @@ pub struct PageBrief { pub title: String, pub is_journal: bool, pub is_hub: bool, + /// The page's type (the UI shows its icon next to the title). + pub page_type: Option, } impl From<&Page> for PageBrief { @@ -128,6 +154,7 @@ impl From<&Page> for PageBrief { title: p.title.clone(), is_journal: p.is_journal(), is_hub: p.is_hub(), + page_type: p.page_type().map(String::from), } } } @@ -185,6 +212,8 @@ pub struct TitleHit { /// The matched title or alias. pub title: String, pub is_alias: bool, + /// Type of the page (for its icon). + pub page_type: Option, } /// A block matching a search (`((` autocomplete, quick switcher content results). @@ -240,6 +269,8 @@ pub struct GraphNode { /// A virtual tag node (not a page, no outline): `id` is `tag:`, `title` the /// display name, `degree` the number of pages carrying the tag. pub is_tag: bool, + /// The page's type (tree labels show its icon; the network view does not). + pub page_type: Option, } /// The whole page-level graph, edges as parallel arrays (cheap to move across the FFI). diff --git a/crates/synapse-ffi/src/api/graph.rs b/crates/synapse-ffi/src/api/graph.rs index b0c457f..28e2bf0 100644 --- a/crates/synapse-ffi/src/api/graph.rs +++ b/crates/synapse-ffi/src/api/graph.rs @@ -209,15 +209,23 @@ impl SynapseGraph { if !seen.insert(bl.block.id) { continue; } - let i = *index.entry(bl.block.page_id).or_insert_with(|| { - groups.push(BacklinkGroup { - page_id: bl.block.page_id.to_string(), - page_title: bl.page_title.clone(), - is_journal: parse_day(&bl.page_title).is_some(), - blocks: Vec::new(), - }); - groups.len() - 1 - }); + let i = match index.get(&bl.block.page_id) { + Some(&i) => i, + None => { + let page_type = g + .get_page(bl.block.page_id)? + .and_then(|p| p.page_type().map(String::from)); + groups.push(BacklinkGroup { + page_id: bl.block.page_id.to_string(), + page_title: bl.page_title.clone(), + is_journal: parse_day(&bl.page_title).is_some(), + page_type, + blocks: Vec::new(), + }); + index.insert(bl.block.page_id, groups.len() - 1); + groups.len() - 1 + } + }; groups[i].blocks.push(BlockDto::new(0, &bl.block, false)); } Ok(groups) diff --git a/crates/synapse-ffi/src/api/graph_view.rs b/crates/synapse-ffi/src/api/graph_view.rs index e7647b8..5abae7b 100644 --- a/crates/synapse-ffi/src/api/graph_view.rs +++ b/crates/synapse-ffi/src/api/graph_view.rs @@ -83,6 +83,11 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result { .into_iter() .map(|(id, t)| (id.to_string(), t)) .collect(); + let mut page_types: HashMap = g + .all_page_types()? + .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 @@ -100,6 +105,7 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result { })?; for row in rows { let (id, title, journal_date, origin_journal, created_at) = row?; + let page_type = page_types.remove(&id); let tags = page_tags.get(&id).cloned().unwrap_or_default(); index.insert(id.clone(), nodes.len() as u32); nodes.push(GraphNode { @@ -116,6 +122,7 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result { home_hub: None, tags, is_tag: false, + page_type, }); } } @@ -328,6 +335,7 @@ fn tagged( home_hub: None, tags: Vec::new(), is_tag: true, + page_type: None, }); nodes.len() as u32 - 1 }); diff --git a/crates/synapse-ffi/src/api/search.rs b/crates/synapse-ffi/src/api/search.rs index 3bf8d34..669a5e9 100644 --- a/crates/synapse-ffi/src/api/search.rs +++ b/crates/synapse-ffi/src/api/search.rs @@ -23,6 +23,7 @@ impl SynapseGraph { page_id: p.id.to_string(), title: p.title.clone(), is_alias: false, + page_type: p.page_type().map(String::from), }) .collect()); } @@ -52,13 +53,15 @@ impl SynapseGraph { hits.truncate(limit as usize); let mut out = Vec::with_capacity(hits.len()); for (_, _, title, id) in hits { - let is_alias = g - .get_page(id)? + let page = g.get_page(id)?; + let is_alias = page + .as_ref() .is_some_and(|p| title_key(&p.title) != title_key(&title)); out.push(TitleHit { page_id: id.to_string(), title, is_alias, + page_type: page.and_then(|p| p.page_type().map(String::from)), }); } Ok(out) diff --git a/crates/synapse-ffi/src/api/tags.rs b/crates/synapse-ffi/src/api/tags.rs index 571d6c0..fcfcbf3 100644 --- a/crates/synapse-ffi/src/api/tags.rs +++ b/crates/synapse-ffi/src/api/tags.rs @@ -42,11 +42,7 @@ impl SynapseGraph { .lock() .tag_catalog()? .into_iter() - .map(|t| TagDto { - name: t.name, - count: t.count, - suggested: t.suggested, - }) + .map(TagDto::from) .collect()) } @@ -72,17 +68,34 @@ impl SynapseGraph { )?)) } - /// Types in use (most used first) followed by the seeded suggestions not used yet. + /// Adds a type to the vocabulary even if no page uses it; returns its spelling. + pub fn create_type(&self, name: String) -> Result { + Ok(self.lock().create_type(&name)?) + } + + /// Sets (or with `None` clears) the emoji of a type, defining the type if needed. + pub fn set_type_icon(&self, name: String, icon: Option) -> Result<()> { + Ok(self.lock().set_type_icon(&name, icon.as_deref())?) + } + + /// Renames a type (and same-name tags), keeping its icon; returns the pages changed. + pub fn rename_type(&self, old: String, new: String) -> Result { + Ok(self.lock().rename_type(&old, &new)? as u32) + } + + /// Deletes a type: its pages lose it and its icon is dropped; returns the pages changed. + pub fn remove_type(&self, name: String) -> Result { + Ok(self.lock().remove_type(&name)? as u32) + } + + /// Types in use (most used first), then defined unused types, then the seeded suggestions + /// not used yet; each with its icon. pub fn type_catalog(&self) -> Result> { Ok(self .lock() .type_catalog()? .into_iter() - .map(|t| TagDto { - name: t.name, - count: t.count, - suggested: t.suggested, - }) + .map(TagDto::from) .collect()) } } diff --git a/crates/synapse-ffi/src/frb_generated.rs b/crates/synapse-ffi/src/frb_generated.rs index d9ecec6..da2e78d 100644 --- a/crates/synapse-ffi/src/frb_generated.rs +++ b/crates/synapse-ffi/src/frb_generated.rs @@ -41,7 +41,7 @@ flutter_rust_bridge::frb_generated_boilerplate!( default_rust_auto_opaque = RustAutoOpaqueMoi, ); pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.13.0"; -pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = -1472342481; +pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = 272705018; // Section: executor @@ -921,6 +921,61 @@ fn wire__crate__api__graph__SynapseGraph_create_page_from_template_impl( }, ) } +fn wire__crate__api__graph__SynapseGraph_create_type_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_create_type", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_name = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::create_type( + &*api_that_guard, + api_name, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} fn wire__crate__api__graph__SynapseGraph_delete_block_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, @@ -2722,6 +2777,61 @@ fn wire__crate__api__graph__SynapseGraph_remove_tag_impl( }, ) } +fn wire__crate__api__graph__SynapseGraph_remove_type_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_remove_type", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_name = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::remove_type( + &*api_that_guard, + api_name, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} fn wire__crate__api__graph__SynapseGraph_rename_page_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, @@ -2836,6 +2946,63 @@ fn wire__crate__api__graph__SynapseGraph_rename_tag_impl( }, ) } +fn wire__crate__api__graph__SynapseGraph_rename_type_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_rename_type", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_old = ::sse_decode(&mut deserializer); + let api_new = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::rename_type( + &*api_that_guard, + api_old, + api_new, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} fn wire__crate__api__graph__SynapseGraph_search_blocks_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, @@ -3178,6 +3345,63 @@ fn wire__crate__api__graph__SynapseGraph_set_page_type_impl( }, ) } +fn wire__crate__api__graph__SynapseGraph_set_type_icon_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_set_type_icon", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_name = ::sse_decode(&mut deserializer); + let api_icon = >::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::set_type_icon( + &*api_that_guard, + api_name, + api_icon, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} fn wire__crate__api__graph__SynapseGraph_tag_catalog_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, @@ -3533,11 +3757,13 @@ impl SseDecode for crate::api::dto::BacklinkGroup { let mut var_pageId = ::sse_decode(deserializer); let mut var_pageTitle = ::sse_decode(deserializer); let mut var_isJournal = ::sse_decode(deserializer); + let mut var_pageType = >::sse_decode(deserializer); let mut var_blocks = >::sse_decode(deserializer); return crate::api::dto::BacklinkGroup { page_id: var_pageId, page_title: var_pageTitle, is_journal: var_isJournal, + page_type: var_pageType, blocks: var_blocks, }; } @@ -3657,6 +3883,7 @@ impl SseDecode for crate::api::dto::GraphNode { let mut var_homeHub = >::sse_decode(deserializer); let mut var_tags = >::sse_decode(deserializer); let mut var_isTag = ::sse_decode(deserializer); + let mut var_pageType = >::sse_decode(deserializer); return crate::api::dto::GraphNode { id: var_id, title: var_title, @@ -3671,6 +3898,7 @@ impl SseDecode for crate::api::dto::GraphNode { home_hub: var_homeHub, tags: var_tags, is_tag: var_isTag, + page_type: var_pageType, }; } } @@ -4073,11 +4301,13 @@ impl SseDecode for crate::api::dto::PageBrief { let mut var_title = ::sse_decode(deserializer); let mut var_isJournal = ::sse_decode(deserializer); let mut var_isHub = ::sse_decode(deserializer); + let mut var_pageType = >::sse_decode(deserializer); return crate::api::dto::PageBrief { id: var_id, title: var_title, is_journal: var_isJournal, is_hub: var_isHub, + page_type: var_pageType, }; } } @@ -4201,10 +4431,18 @@ impl SseDecode for crate::api::dto::TagDto { let mut var_name = ::sse_decode(deserializer); let mut var_count = ::sse_decode(deserializer); let mut var_suggested = ::sse_decode(deserializer); + let mut var_icon = >::sse_decode(deserializer); + let mut var_explicit = ::sse_decode(deserializer); + let mut var_typed = ::sse_decode(deserializer); + let mut var_fromHub = ::sse_decode(deserializer); return crate::api::dto::TagDto { name: var_name, count: var_count, suggested: var_suggested, + icon: var_icon, + explicit: var_explicit, + typed: var_typed, + from_hub: var_fromHub, }; } } @@ -4243,10 +4481,12 @@ impl SseDecode for crate::api::dto::TitleHit { let mut var_pageId = ::sse_decode(deserializer); let mut var_title = ::sse_decode(deserializer); let mut var_isAlias = ::sse_decode(deserializer); + let mut var_pageType = >::sse_decode(deserializer); return crate::api::dto::TitleHit { page_id: var_pageId, title: var_title, is_alias: var_isAlias, + page_type: var_pageType, }; } } @@ -4337,211 +4577,235 @@ fn pde_ffi_dispatcher_primary_impl( rust_vec_len, data_len, ), - 17 => wire__crate__api__graph__SynapseGraph_delete_block_impl( + 17 => wire__crate__api__graph__SynapseGraph_create_type_impl( port, ptr, rust_vec_len, data_len, ), - 18 => wire__crate__api__graph__SynapseGraph_delete_page_impl( + 18 => wire__crate__api__graph__SynapseGraph_delete_block_impl( port, ptr, rust_vec_len, data_len, ), - 20 => { + 19 => wire__crate__api__graph__SynapseGraph_delete_page_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 21 => { wire__crate__api__graph__SynapseGraph_graph_data_impl(port, ptr, rust_vec_len, data_len) } - 21 => wire__crate__api__graph__SynapseGraph_hub_conversion_preview_impl( + 22 => wire__crate__api__graph__SynapseGraph_hub_conversion_preview_impl( port, ptr, rust_vec_len, data_len, ), - 22 => wire__crate__api__graph__SynapseGraph_hub_template_impl( + 23 => wire__crate__api__graph__SynapseGraph_hub_template_impl( port, ptr, rust_vec_len, data_len, ), - 23 => wire__crate__api__graph__SynapseGraph_hubs_impl(port, ptr, rust_vec_len, data_len), - 24 => wire__crate__api__graph__SynapseGraph_indent_block_impl( + 24 => wire__crate__api__graph__SynapseGraph_hubs_impl(port, ptr, rust_vec_len, data_len), + 25 => wire__crate__api__graph__SynapseGraph_indent_block_impl( port, ptr, rust_vec_len, data_len, ), - 25 => wire__crate__api__graph__SynapseGraph_insert_block_impl( + 26 => wire__crate__api__graph__SynapseGraph_insert_block_impl( port, ptr, rust_vec_len, data_len, ), - 26 => wire__crate__api__graph__SynapseGraph_journal_impl(port, ptr, rust_vec_len, data_len), - 27 => wire__crate__api__graph__SynapseGraph_journal_neighbors_impl( + 27 => wire__crate__api__graph__SynapseGraph_journal_impl(port, ptr, rust_vec_len, data_len), + 28 => wire__crate__api__graph__SynapseGraph_journal_neighbors_impl( port, ptr, rust_vec_len, data_len, ), - 28 => { + 29 => { wire__crate__api__graph__SynapseGraph_journals_impl(port, ptr, rust_vec_len, data_len) } - 29 => wire__crate__api__graph__SynapseGraph_legacy_candidates_impl( + 30 => wire__crate__api__graph__SynapseGraph_legacy_candidates_impl( port, ptr, rust_vec_len, data_len, ), - 30 => { + 31 => { wire__crate__api__graph__SynapseGraph_list_pages_impl(port, ptr, rust_vec_len, data_len) } - 31 => wire__crate__api__graph__SynapseGraph_merge_block_impl( + 32 => wire__crate__api__graph__SynapseGraph_merge_block_impl( port, ptr, rust_vec_len, data_len, ), - 32 => { + 33 => { wire__crate__api__graph__SynapseGraph_move_block_impl(port, ptr, rust_vec_len, data_len) } - 33 => wire__crate__api__graph__SynapseGraph_open_impl(port, ptr, rust_vec_len, data_len), - 34 => { + 34 => wire__crate__api__graph__SynapseGraph_open_impl(port, ptr, rust_vec_len, data_len), + 35 => { wire__crate__api__graph__SynapseGraph_open_page_impl(port, ptr, rust_vec_len, data_len) } - 35 => wire__crate__api__graph__SynapseGraph_outdent_block_impl( + 36 => wire__crate__api__graph__SynapseGraph_outdent_block_impl( port, ptr, rust_vec_len, data_len, ), - 36 => wire__crate__api__graph__SynapseGraph_outline_impl(port, ptr, rust_vec_len, data_len), - 37 => wire__crate__api__graph__SynapseGraph_page_impl(port, ptr, rust_vec_len, data_len), - 38 => wire__crate__api__graph__SynapseGraph_page_by_title_impl( + 37 => wire__crate__api__graph__SynapseGraph_outline_impl(port, ptr, rust_vec_len, data_len), + 38 => wire__crate__api__graph__SynapseGraph_page_impl(port, ptr, rust_vec_len, data_len), + 39 => wire__crate__api__graph__SynapseGraph_page_by_title_impl( port, ptr, rust_vec_len, data_len, ), - 39 => wire__crate__api__graph__SynapseGraph_page_structure_impl( + 40 => wire__crate__api__graph__SynapseGraph_page_structure_impl( port, ptr, rust_vec_len, data_len, ), - 40 => wire__crate__api__graph__SynapseGraph_pages_with_tag_impl( + 41 => wire__crate__api__graph__SynapseGraph_pages_with_tag_impl( port, ptr, rust_vec_len, data_len, ), - 41 => wire__crate__api__graph__SynapseGraph_purge_pages_impl( + 42 => wire__crate__api__graph__SynapseGraph_purge_pages_impl( port, ptr, rust_vec_len, data_len, ), - 42 => wire__crate__api__graph__SynapseGraph_put_asset_bytes_impl( + 43 => wire__crate__api__graph__SynapseGraph_put_asset_bytes_impl( port, ptr, rust_vec_len, data_len, ), - 43 => wire__crate__api__graph__SynapseGraph_put_asset_file_impl( + 44 => wire__crate__api__graph__SynapseGraph_put_asset_file_impl( port, ptr, rust_vec_len, data_len, ), - 44 => wire__crate__api__graph__SynapseGraph_record_visit_impl( + 45 => wire__crate__api__graph__SynapseGraph_record_visit_impl( port, ptr, rust_vec_len, data_len, ), - 45 => wire__crate__api__graph__SynapseGraph_related_impl(port, ptr, rust_vec_len, data_len), - 46 => wire__crate__api__graph__SynapseGraph_remove_alias_impl( + 46 => wire__crate__api__graph__SynapseGraph_related_impl(port, ptr, rust_vec_len, data_len), + 47 => wire__crate__api__graph__SynapseGraph_remove_alias_impl( port, ptr, rust_vec_len, data_len, ), - 47 => wire__crate__api__graph__SynapseGraph_remove_from_hub_impl( + 48 => wire__crate__api__graph__SynapseGraph_remove_from_hub_impl( port, ptr, rust_vec_len, data_len, ), - 48 => wire__crate__api__graph__SynapseGraph_remove_page_tag_impl( + 49 => wire__crate__api__graph__SynapseGraph_remove_page_tag_impl( port, ptr, rust_vec_len, data_len, ), - 49 => { + 50 => { wire__crate__api__graph__SynapseGraph_remove_tag_impl(port, ptr, rust_vec_len, data_len) } - 50 => wire__crate__api__graph__SynapseGraph_rename_page_impl( + 51 => wire__crate__api__graph__SynapseGraph_remove_type_impl( port, ptr, rust_vec_len, data_len, ), - 51 => { + 52 => wire__crate__api__graph__SynapseGraph_rename_page_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 53 => { wire__crate__api__graph__SynapseGraph_rename_tag_impl(port, ptr, rust_vec_len, data_len) } - 52 => wire__crate__api__graph__SynapseGraph_search_blocks_impl( + 54 => wire__crate__api__graph__SynapseGraph_rename_type_impl( port, ptr, rust_vec_len, data_len, ), - 53 => wire__crate__api__graph__SynapseGraph_search_titles_impl( + 55 => wire__crate__api__graph__SynapseGraph_search_blocks_impl( port, ptr, rust_vec_len, data_len, ), - 54 => wire__crate__api__graph__SynapseGraph_set_collapsed_impl( + 56 => wire__crate__api__graph__SynapseGraph_search_titles_impl( port, ptr, rust_vec_len, data_len, ), - 55 => wire__crate__api__graph__SynapseGraph_set_hub_description_impl( + 57 => wire__crate__api__graph__SynapseGraph_set_collapsed_impl( port, ptr, rust_vec_len, data_len, ), - 56 => wire__crate__api__graph__SynapseGraph_set_page_tags_impl( + 58 => wire__crate__api__graph__SynapseGraph_set_hub_description_impl( port, ptr, rust_vec_len, data_len, ), - 57 => wire__crate__api__graph__SynapseGraph_set_page_type_impl( + 59 => wire__crate__api__graph__SynapseGraph_set_page_tags_impl( port, ptr, rust_vec_len, data_len, ), - 58 => wire__crate__api__graph__SynapseGraph_tag_catalog_impl( + 60 => wire__crate__api__graph__SynapseGraph_set_page_type_impl( port, ptr, rust_vec_len, data_len, ), - 59 => { + 61 => wire__crate__api__graph__SynapseGraph_set_type_icon_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 62 => wire__crate__api__graph__SynapseGraph_tag_catalog_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 63 => { wire__crate__api__graph__SynapseGraph_timeline_impl(port, ptr, rust_vec_len, data_len) } - 61 => wire__crate__api__graph__SynapseGraph_type_catalog_impl( + 65 => wire__crate__api__graph__SynapseGraph_type_catalog_impl( port, ptr, rust_vec_len, data_len, ), - 62 => wire__crate__api__graph__SynapseGraph_update_block_impl( + 66 => wire__crate__api__graph__SynapseGraph_update_block_impl( port, ptr, rust_vec_len, @@ -4561,8 +4825,8 @@ fn pde_ffi_dispatcher_sync_impl( match func_id { 1 => wire__crate__api__layout__ForceLayout_new_impl(ptr, rust_vec_len, data_len), 10 => wire__crate__api__graph__SynapseGraph_asset_path_impl(ptr, rust_vec_len, data_len), - 19 => wire__crate__api__graph__SynapseGraph_dir_impl(ptr, rust_vec_len, data_len), - 60 => wire__crate__api__graph__SynapseGraph_today_impl(ptr, rust_vec_len, data_len), + 20 => wire__crate__api__graph__SynapseGraph_dir_impl(ptr, rust_vec_len, data_len), + 64 => wire__crate__api__graph__SynapseGraph_today_impl(ptr, rust_vec_len, data_len), _ => unreachable!(), } } @@ -4624,6 +4888,7 @@ impl flutter_rust_bridge::IntoDart for crate::api::dto::BacklinkGroup { self.page_id.into_into_dart().into_dart(), self.page_title.into_into_dart().into_dart(), self.is_journal.into_into_dart().into_dart(), + self.page_type.into_into_dart().into_dart(), self.blocks.into_into_dart().into_dart(), ] .into_dart() @@ -4751,6 +5016,7 @@ impl flutter_rust_bridge::IntoDart for crate::api::dto::GraphNode { self.home_hub.into_into_dart().into_dart(), self.tags.into_into_dart().into_dart(), self.is_tag.into_into_dart().into_dart(), + self.page_type.into_into_dart().into_dart(), ] .into_dart() } @@ -4893,6 +5159,7 @@ impl flutter_rust_bridge::IntoDart for crate::api::dto::PageBrief { self.title.into_into_dart().into_dart(), self.is_journal.into_into_dart().into_dart(), self.is_hub.into_into_dart().into_dart(), + self.page_type.into_into_dart().into_dart(), ] .into_dart() } @@ -5030,6 +5297,10 @@ impl flutter_rust_bridge::IntoDart for crate::api::dto::TagDto { self.name.into_into_dart().into_dart(), self.count.into_into_dart().into_dart(), self.suggested.into_into_dart().into_dart(), + self.icon.into_into_dart().into_dart(), + self.explicit.into_into_dart().into_dart(), + self.typed.into_into_dart().into_dart(), + self.from_hub.into_into_dart().into_dart(), ] .into_dart() } @@ -5088,6 +5359,7 @@ impl flutter_rust_bridge::IntoDart for crate::api::dto::TitleHit { self.page_id.into_into_dart().into_dart(), self.title.into_into_dart().into_dart(), self.is_alias.into_into_dart().into_dart(), + self.page_type.into_into_dart().into_dart(), ] .into_dart() } @@ -5165,6 +5437,7 @@ impl SseEncode for crate::api::dto::BacklinkGroup { ::sse_encode(self.page_id, serializer); ::sse_encode(self.page_title, serializer); ::sse_encode(self.is_journal, serializer); + >::sse_encode(self.page_type, serializer); >::sse_encode(self.blocks, serializer); } } @@ -5251,6 +5524,7 @@ impl SseEncode for crate::api::dto::GraphNode { >::sse_encode(self.home_hub, serializer); >::sse_encode(self.tags, serializer); ::sse_encode(self.is_tag, serializer); + >::sse_encode(self.page_type, serializer); } } @@ -5574,6 +5848,7 @@ impl SseEncode for crate::api::dto::PageBrief { ::sse_encode(self.title, serializer); ::sse_encode(self.is_journal, serializer); ::sse_encode(self.is_hub, serializer); + >::sse_encode(self.page_type, serializer); } } @@ -5664,6 +5939,10 @@ impl SseEncode for crate::api::dto::TagDto { ::sse_encode(self.name, serializer); ::sse_encode(self.count, serializer); ::sse_encode(self.suggested, serializer); + >::sse_encode(self.icon, serializer); + ::sse_encode(self.explicit, serializer); + ::sse_encode(self.typed, serializer); + ::sse_encode(self.from_hub, serializer); } } @@ -5691,6 +5970,7 @@ impl SseEncode for crate::api::dto::TitleHit { ::sse_encode(self.page_id, serializer); ::sse_encode(self.title, serializer); ::sse_encode(self.is_alias, serializer); + >::sse_encode(self.page_type, serializer); } } diff --git a/crates/synapse-ffi/tests/api.rs b/crates/synapse-ffi/tests/api.rs index 7225d39..9f679cf 100644 --- a/crates/synapse-ffi/tests/api.rs +++ b/crates/synapse-ffi/tests/api.rs @@ -506,6 +506,52 @@ fn page_type_and_tag_renaming_round_trip_through_the_api() { assert!(g.set_page_type(a, None).unwrap().page_type.is_none()); } +#[test] +fn type_icons_and_page_types_reach_the_ui_dtos() { + let (_d, g) = open(); + let (a, _) = page_with(&g, "Ana", &["x"]); + let (b, _) = page_with(&g, "Notes", &["about [[Ana]]"]); + g.set_page_type(a.clone(), Some("persona".into())).unwrap(); + g.set_page_type(b.clone(), Some("idea".into())).unwrap(); + g.set_type_icon("persona".into(), Some("🧑".into())) + .unwrap(); + assert!( + g.set_type_icon("persona".into(), Some("xy".into())) + .is_err() + ); + assert_eq!(g.create_type(" Libro ".into()).unwrap(), "Libro"); + let cat = g.type_catalog().unwrap(); + let persona = cat.iter().find(|t| t.name == "persona").unwrap(); + assert_eq!((persona.count, persona.icon.as_deref()), (1, Some("🧑"))); + assert!(cat.iter().any(|t| t.name == "Libro" && t.count == 0)); + assert!(cat.iter().any(|t| t.name == "sueño" && t.count == 0)); + + // Lists of pages carry the page type, so the UI can look up its icon. + let hits = g.search_titles("Ana".into(), 5).unwrap(); + assert_eq!(hits[0].page_type.as_deref(), Some("persona")); + let bl = g.backlinks(a.clone()).unwrap(); + assert_eq!(bl[0].page_type.as_deref(), Some("idea")); + let briefs = g.pages_with_tag("persona".into()).unwrap(); + assert_eq!(briefs[0].page_type.as_deref(), Some("persona")); + let data = g.graph_data().unwrap(); + let node = data.nodes.iter().find(|n| n.id == a).unwrap(); + assert_eq!(node.page_type.as_deref(), Some("persona")); + + // Rename keeps the icon; remove drops the type from its pages. + assert_eq!(g.rename_type("persona".into(), "Gente".into()).unwrap(), 1); + let cat = g.type_catalog().unwrap(); + let gente = cat.iter().find(|t| t.name == "Gente").unwrap(); + assert_eq!(gente.icon.as_deref(), Some("🧑")); + assert_eq!(g.remove_type("Gente".into()).unwrap(), 1); + assert!(g.page(a).unwrap().unwrap().page.page_type.is_none()); + + // The tag catalog says where tags come from. + g.add_page_tag(b.clone(), "idea".into()).unwrap(); + let tags = g.tag_catalog().unwrap(); + let idea = tags.iter().find(|t| t.name == "idea").unwrap(); + assert_eq!((idea.explicit, idea.typed, idea.from_hub), (1, 1, 0)); +} + #[test] fn a_hub_tag_and_a_same_name_type_need_no_tag_node_beside_the_hub() { let (_d, g) = open(); From a5bee501905c738a6a01a22fa08cf2edce1ea606 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 06:44:35 +0100 Subject: [PATCH 05/11] feat(app): Tags & types view with an emoji picker for types Sidebar entry and tab route. Types: emoji, count, create, rename, delete. Tags: count and sources; explicit tags can be renamed or deleted, hub and type tags are locked with an explanation. AppState caches type icons. Co-Authored-By: Claude Opus 5.5 --- app/lib/src/app.dart | 8 +- app/lib/src/state/app_state.dart | 48 ++- app/lib/src/views/shell.dart | 16 + app/lib/src/views/tags_types_view.dart | 394 +++++++++++++++++++++++++ app/lib/src/widgets/emoji_picker.dart | 327 ++++++++++++++++++++ app/lib/src/widgets/pickers.dart | 6 +- app/lib/src/widgets/type_icon.dart | 34 +++ 7 files changed, 827 insertions(+), 6 deletions(-) create mode 100644 app/lib/src/views/tags_types_view.dart create mode 100644 app/lib/src/widgets/emoji_picker.dart create mode 100644 app/lib/src/widgets/type_icon.dart diff --git a/app/lib/src/app.dart b/app/lib/src/app.dart index aa6636c..894833a 100644 --- a/app/lib/src/app.dart +++ b/app/lib/src/app.dart @@ -16,10 +16,10 @@ class SynapseApp extends StatefulWidget { } class _SynapseAppState extends State { - late final AppState _state = AppState( - widget.backend, - settings: widget.settings, - )..loadRecent(); + late final AppState _state = + AppState(widget.backend, settings: widget.settings) + ..loadRecent() + ..loadTypeIcons(); @override void dispose() { diff --git a/app/lib/src/state/app_state.dart b/app/lib/src/state/app_state.dart index 22b0593..0729fc9 100644 --- a/app/lib/src/state/app_state.dart +++ b/app/lib/src/state/app_state.dart @@ -31,6 +31,11 @@ class SettingsRoute extends AppRoute { const SettingsRoute(); } +/// Manage the vocabulary: types (with their emoji) and tags. +class TagsTypesRoute extends AppRoute { + const TagsTypesRoute(); +} + enum GraphMode { network('Network', Icons.hub_outlined), brain('Synapses', Icons.bolt_outlined), @@ -81,6 +86,9 @@ class AppTab { /// Title of a page route (the route only has an id); set once the page is shown. String? label; + /// Type of the page shown (for its emoji next to [title]); set with [label]. + String? pageType; + /// Stable identity for widget keys (reordering, closing). final int uid = _nextUid++; static int _nextUid = 0; @@ -90,6 +98,7 @@ class AppTab { TimelineRoute() => 'Timeline', AllPagesRoute() => 'All pages', SettingsRoute() => 'Settings', + TagsTypesRoute() => 'Tags & types', TagRoute(:final name) => '#$name', GraphRoute() => 'Graph', PageTarget(:final title) => label ?? title ?? 'Page', @@ -100,6 +109,7 @@ class AppTab { TimelineRoute() => Icons.timeline_rounded, AllPagesRoute() => Icons.description_outlined, SettingsRoute() => Icons.settings_outlined, + TagsTypesRoute() => Icons.style_outlined, TagRoute() => Icons.sell_outlined, GraphRoute() => Icons.hub_outlined, PageTarget() => Icons.article_outlined, @@ -116,6 +126,7 @@ Map? routeToJson(AppRoute r, {String? label}) => switch (r) { TimelineRoute() => {'t': 'timeline'}, AllPagesRoute() => {'t': 'all'}, SettingsRoute() => {'t': 'settings'}, + TagsTypesRoute() => {'t': 'tags-types'}, TagRoute() => {'t': 'tag', 'name': r.name}, GraphRoute() => { 't': 'graph', @@ -142,6 +153,8 @@ AppRoute? routeFromJson(Object? j) { return const AllPagesRoute(); case 'settings': return const SettingsRoute(); + case 'tags-types': + return const TagsTypesRoute(); case 'tag': final name = j['name']; return name is String && name.isNotEmpty ? TagRoute(name) : null; @@ -338,6 +351,29 @@ class AppState extends ChangeNotifier { /// Bumped to make the current view reload from the core (failed writes, renames). int generation = 0; + /// Emoji of each type, by lower-cased type name (types are names; see [typeIcon]). + final Map typeIcons = {}; + + /// The emoji of a page type, if it has one. + String? typeIcon(String? type) => + type == null ? null : typeIcons[type.trim().toLowerCase()]; + + /// The type emoji of the page a tab shows (null for other routes). + String? tabTypeIcon(AppTab t) => + t.route is PageTarget ? typeIcon(t.pageType) : null; + + /// Reloads [typeIcons] from the type catalogue (at start and after type edits). + Future loadTypeIcons() async { + final types = await backend.typeCatalog(); + typeIcons + ..clear() + ..addAll({ + for (final t in types) + if (t.icon != null) t.name.toLowerCase(): t.icon!, + }); + notifyListeners(); + } + /// Hubs expanded in the sidebar tree (kept here so it survives sidebar rebuilds). final expandedHubs = {}; @@ -380,6 +416,7 @@ class AppState extends ChangeNotifier { t.forward.clear(); t.route = r; t.label = null; + t.pageType = null; _saveSettings(); notifyListeners(); } @@ -548,6 +585,7 @@ class AppState extends ChangeNotifier { tab.label = label; _saveSettings(); } + tab.pageType = page.pageType; } recent.removeWhere((p) => p.id == page.id); // Hubs are folders, not pages: they never show up in recents. @@ -559,6 +597,7 @@ class AppState extends ChangeNotifier { title: page.title, isJournal: page.journalDate != null, isHub: false, + pageType: page.pageType, ), ); if (recent.length > 12) recent.removeLast(); @@ -572,7 +611,13 @@ class AppState extends ChangeNotifier { for (final p in pages) { if (!p.isHub && !recent.any((r) => r.id == p.id)) { recent.add( - PageBrief(id: p.id, title: p.title, isJournal: false, isHub: p.isHub), + PageBrief( + id: p.id, + title: p.title, + isJournal: false, + isHub: p.isHub, + pageType: p.pageType, + ), ); } } @@ -591,6 +636,7 @@ class AppState extends ChangeNotifier { title: title, isJournal: recent[i].isJournal, isHub: recent[i].isHub, + pageType: recent[i].pageType, ); } notifyListeners(); diff --git a/app/lib/src/views/shell.dart b/app/lib/src/views/shell.dart index a69eab0..25c16ef 100644 --- a/app/lib/src/views/shell.dart +++ b/app/lib/src/views/shell.dart @@ -16,6 +16,8 @@ import 'graph_view.dart'; import 'settings_view.dart'; import 'tab_strip.dart'; import 'tag_view.dart'; +import 'tags_types_view.dart'; +import '../widgets/type_icon.dart'; /// App frame: sidebar (navigation, hubs, recents), top bar (history, search, theme, /// settings) and the current view. @@ -132,6 +134,7 @@ class _ShellState extends State { ), AllPagesRoute() => const AllPagesView(), SettingsRoute() => const SettingsView(), + TagsTypesRoute() => const TagsTypesView(), TagRoute() => TagView(name: route.name), PageTarget() => PageScreen(target: route), }, @@ -323,6 +326,13 @@ class _Sidebar extends StatelessWidget { onTap: () => go(const AllPagesRoute()), onMiddle: () => newTab(const AllPagesRoute()), ), + _NavItem( + icon: Icons.style_outlined, + label: 'Tags & types', + selected: route is TagsTypesRoute, + onTap: () => go(const TagsTypesRoute()), + onMiddle: () => newTab(const TagsTypesRoute()), + ), const SizedBox(height: 22), Expanded( child: ListView( @@ -342,6 +352,7 @@ class _Sidebar extends StatelessWidget { for (final p in app.recent) _NavItem( label: p.isJournal ? longDate(p.title) : p.title, + leading: TypeIcon(p.pageType), selected: route is PageTarget && route.id == p.id, dense: true, onTap: () => go(PageTarget(id: p.id)), @@ -360,6 +371,7 @@ class _Sidebar extends StatelessWidget { class _NavItem extends StatefulWidget { const _NavItem({ this.icon, + this.leading, required this.label, required this.selected, required this.onTap, @@ -367,6 +379,9 @@ class _NavItem extends StatefulWidget { this.dense = false, }); final IconData? icon; + + /// Shown before the label (a page's type emoji). + final Widget? leading; final String label; final bool selected; final VoidCallback onTap; @@ -417,6 +432,7 @@ class _NavItemState extends State<_NavItem> { ), const SizedBox(width: 10), ], + ?widget.leading, Expanded( child: Text( widget.label, diff --git a/app/lib/src/views/tags_types_view.dart b/app/lib/src/views/tags_types_view.dart new file mode 100644 index 0000000..6cfe703 --- /dev/null +++ b/app/lib/src/views/tags_types_view.dart @@ -0,0 +1,394 @@ +import 'package:flutter/material.dart'; + +import '../backend/graph_backend.dart'; +import '../state/app_state.dart'; +import '../theme/theme.dart'; +import '../widgets/common.dart'; +import '../widgets/emoji_picker.dart'; +import '../widgets/pickers.dart'; + +/// Manages the vocabulary. Types: emoji (shown before the names of their pages), name and +/// page count; create, rename, delete. Tags: name, page count and where they come from +/// (listed on pages, a type, a hub); explicit ones can be renamed or removed. Tapping a name +/// opens its tag view. +class TagsTypesView extends StatefulWidget { + const TagsTypesView({super.key}); + + @override + State createState() => _TagsTypesViewState(); +} + +class _TagsTypesViewState extends State { + bool _tags = false; + late Future<(List, List)> _data = _load(); + + Future<(List, List)> _load() async { + final backend = AppScope.read(context).backend; + return (await backend.typeCatalog(), await backend.tagCatalog()); + } + + void _reload() { + AppScope.read(context).loadTypeIcons().ignore(); + setState(() { + _data = _load(); + }); + } + + /// Runs a write through the queue (errors become a snack bar), then reloads the lists. + Future _run(Future Function(GraphBackend b) op) async { + final app = AppScope.read(context); + final messenger = ScaffoldMessenger.of(context); + try { + await app.queue.run(() => op(app.backend), report: false); + } catch (e) { + messenger.showSnackBar(SnackBar(content: Text(errorText(e)))); + } finally { + if (mounted) _reload(); + } + } + + Future _newType() async { + final app = AppScope.read(context); + await showNameDialog( + context, + heading: 'New type', + confirm: 'Create', + hint: 'Type name', + submit: (name) => + app.queue.run(() => app.backend.createType(name), report: false), + ); + if (mounted) _reload(); + } + + Future _pickIcon(TagDto t) async { + final picked = await showEmojiPicker( + context, + title: 'Emoji for ${t.name}', + current: t.icon, + ); + if (picked == null || picked.emoji == t.icon) return; + await _run((b) => b.setTypeIcon(t.name, picked.emoji)); + } + + Future _renameType(TagDto t) async { + final app = AppScope.read(context); + await showNameDialog( + context, + heading: 'Rename type', + confirm: 'Rename', + hint: 'Type name', + initial: t.name, + submit: (name) => app.queue.run( + () => app.backend.renameType(t.name, name), + report: false, + ), + ); + if (mounted) _reload(); + } + + Future _deleteType(TagDto t) async { + final ok = await _confirm( + title: 'Delete type “${t.name}”?', + body: t.count == 0 + ? 'No page has this type. Its emoji is removed too.' + : '${_pages(t.count)} lose this type (their tags stay). ' + 'Its emoji is removed too.', + action: 'Delete', + ); + if (ok) await _run((b) => b.removeType(t.name)); + } + + Future _renameTag(TagDto t) async { + final app = AppScope.read(context); + await showNameDialog( + context, + heading: 'Rename tag', + confirm: 'Rename', + hint: 'Tag name', + initial: t.name, + submit: (name) => app.queue.run( + () => app.backend.renameTag(t.name, name), + report: false, + ), + ); + if (mounted) _reload(); + } + + Future _deleteTag(TagDto t) async { + final ok = await _confirm( + title: 'Delete tag #${t.name}?', + body: + 'It is removed from the ${_pages(t.explicit)} that list it.' + '${t.typed > 0 ? ' Pages with the type “${t.name}” keep it.' : ''}' + '${t.fromHub > 0 ? ' Members of the hub “${t.name}” keep it.' : ''}', + action: 'Delete', + ); + if (ok) await _run((b) => b.removeTag(t.name)); + } + + Future _confirm({ + required String title, + required String body, + required String action, + }) async => + await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: Text(title), + content: Text(body), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx, false), + child: const Text('Cancel'), + ), + TextButton( + key: const ValueKey('tt-confirm'), + onPressed: () => Navigator.pop(ctx, true), + child: Text(action), + ), + ], + ), + ) ?? + false; + + @override + Widget build(BuildContext context) { + final colors = context.colors; + return FutureBuilder<(List, List)>( + future: _data, + builder: (context, snap) { + final data = snap.data; + return LayoutBuilder( + builder: (context, box) => ListView( + padding: EdgeInsets.fromLTRB( + sidePadding(box.maxWidth), + 36, + sidePadding(box.maxWidth), + 80, + ), + children: [ + Text( + 'Tags & types', + style: Theme.of(context).textTheme.headlineLarge, + ), + const SizedBox(height: 6), + Text( + 'A type says what a page is (one per page) and shows its emoji ' + 'before the page’s name. Tags file pages under topics.', + style: TextStyle(fontSize: 12.5, color: colors.faint), + ), + const SizedBox(height: 16), + Row( + children: [ + SegmentedButton( + showSelectedIcon: false, + segments: [ + ButtonSegment( + value: false, + label: Text( + 'Types', + key: const ValueKey('tt-tab-types'), + ), + ), + ButtonSegment( + value: true, + label: Text('Tags', key: const ValueKey('tt-tab-tags')), + ), + ], + selected: {_tags}, + onSelectionChanged: (s) => setState(() => _tags = s.first), + ), + const Spacer(), + if (!_tags) + TextButton.icon( + key: const ValueKey('new-type'), + onPressed: _newType, + icon: const Icon(Icons.add_rounded, size: 18), + label: const Text('New type'), + ), + ], + ), + const SizedBox(height: 12), + if (data == null) + const SizedBox.shrink() + else if (_tags) + ..._tagRows(data.$2) + else + ..._typeRows(data.$1), + ], + ), + ); + }, + ); + } + + Iterable _typeRows(List types) sync* { + final colors = context.colors; + final app = AppScope.read(context); + if (types.isEmpty) { + yield Text('No types yet.', style: TextStyle(color: colors.muted)); + } + for (final t in types) { + yield _Row( + key: ValueKey('type-row-${t.name}'), + leading: Tooltip( + message: t.icon == null ? 'Choose an emoji' : 'Change the emoji', + child: InkWell( + key: ValueKey('type-icon-btn-${t.name}'), + borderRadius: BorderRadius.circular(8), + onTap: () => _pickIcon(t), + child: Container( + width: 34, + height: 34, + alignment: Alignment.center, + decoration: BoxDecoration( + color: colors.surface, + border: Border.all(color: colors.line), + borderRadius: BorderRadius.circular(8), + ), + child: t.icon == null + ? Icon( + Icons.add_reaction_outlined, + size: 17, + color: colors.faint, + ) + : Text(t.icon!, style: const TextStyle(fontSize: 18)), + ), + ), + ), + name: t.name, + detail: t.count == 0 + ? (t.suggested ? 'suggested · no pages' : 'no pages') + : _pages(t.count), + onOpen: () => app.navigate(TagRoute(t.name)), + menu: PopupMenuButton( + key: ValueKey('type-menu-${t.name}'), + tooltip: 'Type actions', + icon: Icon(Icons.more_horiz_rounded, color: colors.muted, size: 20), + onSelected: (v) => switch (v) { + 'icon' => _pickIcon(t), + 'rename' => _renameType(t), + _ => _deleteType(t), + }, + itemBuilder: (_) => const [ + PopupMenuItem(value: 'icon', child: Text('Emoji…')), + PopupMenuItem(value: 'rename', child: Text('Rename…')), + PopupMenuItem(value: 'delete', child: Text('Delete…')), + ], + ), + ); + } + } + + Iterable _tagRows(List tags) sync* { + final colors = context.colors; + final app = AppScope.read(context); + if (tags.isEmpty) { + yield Text('No tags yet.', style: TextStyle(color: colors.muted)); + } + for (final t in tags) { + final sources = [ + if (t.explicit > 0) 'listed on ${t.explicit}', + if (t.typed > 0) 'type', + if (t.fromHub > 0) 'hub', + ]; + final String? locked = t.explicit > 0 + ? null + : t.fromHub > 0 + ? 'Comes from the hub “${t.name}”: rename or delete the hub instead.' + : 'Comes from the type “${t.name}”: manage it under Types.'; + yield _Row( + key: ValueKey('tag-row-${t.name}'), + leading: Icon(Icons.sell_outlined, size: 17, color: colors.faint), + name: '#${t.name}', + detail: '${_pages(t.count)} · ${sources.join(', ')}', + onOpen: () => app.navigate(TagRoute(t.name)), + menu: locked != null + ? Tooltip( + key: ValueKey('tag-locked-${t.name}'), + message: locked, + child: Padding( + padding: const EdgeInsets.all(12), + child: Icon( + Icons.lock_outline_rounded, + size: 17, + color: colors.faint, + ), + ), + ) + : PopupMenuButton( + key: ValueKey('tag-menu-${t.name}'), + tooltip: 'Tag actions', + icon: Icon( + Icons.more_horiz_rounded, + color: colors.muted, + size: 20, + ), + onSelected: (v) => + v == 'rename' ? _renameTag(t) : _deleteTag(t), + itemBuilder: (_) => const [ + PopupMenuItem(value: 'rename', child: Text('Rename…')), + PopupMenuItem(value: 'delete', child: Text('Delete…')), + ], + ), + ); + } + } +} + +String _pages(int n) => '$n ${n == 1 ? 'page' : 'pages'}'; + +class _Row extends StatelessWidget { + const _Row({ + super.key, + required this.leading, + required this.name, + required this.detail, + required this.onOpen, + required this.menu, + }); + final Widget leading; + final String name; + final String detail; + final VoidCallback onOpen; + final Widget menu; + + @override + Widget build(BuildContext context) { + final colors = context.colors; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 3), + child: Row( + children: [ + leading, + const SizedBox(width: 12), + Expanded( + child: InkWell( + borderRadius: BorderRadius.circular(6), + onTap: onOpen, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 6), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 14.5, color: colors.ink), + ), + Text( + detail, + style: TextStyle(fontSize: 12, color: colors.faint), + ), + ], + ), + ), + ), + ), + menu, + ], + ), + ); + } +} diff --git a/app/lib/src/widgets/emoji_picker.dart b/app/lib/src/widgets/emoji_picker.dart new file mode 100644 index 0000000..26150fe --- /dev/null +++ b/app/lib/src/widgets/emoji_picker.dart @@ -0,0 +1,327 @@ +import 'package:flutter/material.dart'; + +import '../theme/theme.dart'; + +/// Curated emoji, grouped (no emoji package: a short list covers the usual types, and any +/// other emoji can be pasted). +const emojiGroups = <(String, List)>[ + ( + 'People', + [ + '🧑', + '👤', + '👥', + '👩', + '👨', + '🧒', + '👪', + '🧑‍💼', + '🧑‍🔬', + '🧑‍🎨', + '🧑‍🏫', + '🧑‍💻', + '🧑‍⚕️', + '🤝', + '💬', + '🫂', + ], + ), + ( + 'Places', + [ + '📍', + '🏠', + '🏢', + '🏛️', + '🏙️', + '🏞️', + '🗺️', + '🌍', + '✈️', + '🏫', + '🏥', + '🏪', + '⛪', + '🏰', + '🏖️', + '⛰️', + ], + ), + ( + 'Things', + [ + '📕', + '📚', + '📄', + '📝', + '📎', + '💻', + '📱', + '🖥️', + '⚙️', + '🔧', + '🧰', + '💡', + '🔑', + '📦', + '🎁', + '🗂️', + ], + ), + ( + 'Ideas', + [ + '💭', + '🧠', + '💡', + '❓', + '❗', + '🎯', + '🧩', + '🔬', + '🧪', + '📐', + '📊', + '📈', + '🔍', + '✨', + '🌀', + '♾️', + ], + ), + ( + 'Nature', + [ + '🌱', + '🌿', + '🌳', + '🌸', + '🍄', + '🌊', + '🔥', + '⭐', + '🌙', + '☀️', + '⚡', + '❄️', + '🐱', + '🐶', + '🐦', + '🦋', + ], + ), + ( + 'Food', + [ + '🍳', + '🥗', + '🍝', + '🍕', + '🍰', + '🍎', + '🥖', + '🧀', + '☕', + '🍵', + '🍷', + '🍺', + '🥘', + '🌮', + '🍣', + '🥕', + ], + ), + ( + 'Activities', + [ + '📅', + '🎉', + '🎵', + '🎬', + '🎮', + '🎨', + '📷', + '⚽', + '🏃', + '🧘', + '✍️', + '🎤', + '🎓', + '💼', + '🛠️', + '🧳', + ], + ), + ( + 'Symbols', + [ + '❤️', + '⭐', + '✅', + '⚠️', + '🔖', + '🏷️', + '📌', + '🔗', + '💰', + '⏳', + '🔒', + '🚩', + '🔴', + '🟢', + '🔵', + '🟣', + ], + ), +]; + +/// True when [s] (trimmed) is one emoji: a single user-perceived character that is not plain +/// ASCII (so letters, digits and punctuation are refused). +bool isSingleEmoji(String s) { + final t = s.trim(); + return t.isNotEmpty && + t.characters.length == 1 && + t.runes.any((r) => r > 0x7f) && + !t.contains(RegExp(r'\s')); +} + +/// What the picker returned: an emoji, or `null` to clear the icon. +class EmojiChoice { + const EmojiChoice(this.emoji); + final String? emoji; +} + +/// Lets the user pick an emoji from [emojiGroups], paste any other one, or clear it. +/// Returns `null` when cancelled. +Future showEmojiPicker( + BuildContext context, { + required String title, + String? current, +}) => showDialog( + context: context, + builder: (_) => _EmojiPicker(title: title, current: current), +); + +class _EmojiPicker extends StatefulWidget { + const _EmojiPicker({required this.title, this.current}); + final String title; + final String? current; + + @override + State<_EmojiPicker> createState() => _EmojiPickerState(); +} + +class _EmojiPickerState extends State<_EmojiPicker> { + final _text = TextEditingController(); + String? _error; + + @override + void dispose() { + _text.dispose(); + super.dispose(); + } + + void _usePasted() { + final t = _text.text.trim(); + if (t.isEmpty) return; + if (!isSingleEmoji(t)) { + setState(() => _error = 'Enter a single emoji'); + return; + } + Navigator.pop(context, EmojiChoice(t)); + } + + @override + Widget build(BuildContext context) { + final colors = context.colors; + return AlertDialog( + title: Text(widget.title), + content: SizedBox( + width: 420, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + TextField( + key: const ValueKey('emoji-input'), + controller: _text, + decoration: InputDecoration( + hintText: 'Paste any emoji', + errorText: _error, + suffixIcon: IconButton( + key: const ValueKey('emoji-use'), + tooltip: 'Use this emoji', + icon: const Icon(Icons.check_rounded), + onPressed: _usePasted, + ), + ), + onChanged: (_) { + if (_error != null) setState(() => _error = null); + }, + onSubmitted: (_) => _usePasted(), + ), + const SizedBox(height: 12), + Flexible( + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final (group, list) in emojiGroups) ...[ + Padding( + padding: const EdgeInsets.only(top: 8, bottom: 4), + child: Text( + group.toUpperCase(), + style: Theme.of(context).textTheme.labelSmall, + ), + ), + Wrap( + spacing: 2, + runSpacing: 2, + children: [ + for (final e in list) + InkWell( + key: ValueKey('emoji-$group-$e'), + borderRadius: BorderRadius.circular(6), + onTap: () => + Navigator.pop(context, EmojiChoice(e)), + child: Container( + width: 38, + height: 38, + alignment: Alignment.center, + decoration: BoxDecoration( + color: e == widget.current + ? colors.accentSoft + : null, + borderRadius: BorderRadius.circular(6), + ), + child: Text( + e, + style: const TextStyle(fontSize: 20), + ), + ), + ), + ], + ), + ], + ], + ), + ), + ), + ], + ), + ), + actions: [ + if (widget.current != null) + TextButton( + key: const ValueKey('emoji-clear'), + onPressed: () => Navigator.pop(context, const EmojiChoice(null)), + child: const Text('Remove emoji'), + ), + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + ], + ); + } +} diff --git a/app/lib/src/widgets/pickers.dart b/app/lib/src/widgets/pickers.dart index 891624f..4be376a 100644 --- a/app/lib/src/widgets/pickers.dart +++ b/app/lib/src/widgets/pickers.dart @@ -161,6 +161,7 @@ Future showNameDialog( required String confirm, required Future Function(String name) submit, String hint = 'Title', + String initial = '', }) => showDialog( context: context, builder: (_) => _NameDialog( @@ -168,6 +169,7 @@ Future showNameDialog( confirm: confirm, submit: submit, hint: hint, + initial: initial, ), ); @@ -177,8 +179,10 @@ class _NameDialog extends StatefulWidget { required this.confirm, required this.submit, required this.hint, + this.initial = '', }); final String heading; + final String initial; final String confirm; final String hint; final Future Function(String) submit; @@ -188,7 +192,7 @@ class _NameDialog extends StatefulWidget { } class _NameDialogState extends State<_NameDialog> { - final _text = TextEditingController(); + late final _text = TextEditingController(text: widget.initial); String? _error; bool _busy = false; diff --git a/app/lib/src/widgets/type_icon.dart b/app/lib/src/widgets/type_icon.dart new file mode 100644 index 0000000..b742c4d --- /dev/null +++ b/app/lib/src/widgets/type_icon.dart @@ -0,0 +1,34 @@ +import 'package:flutter/material.dart'; + +import '../state/app_state.dart'; + +/// The emoji of a page's type, drawn just left of the page's name (titles, lists, tabs, the +/// tree view; never in the network graph). Nothing when the type has no emoji. Icons come +/// from [AppState.typeIcons], so lists only need the page's type. +class TypeIcon extends StatelessWidget { + const TypeIcon(this.pageType, {super.key, this.size = 13, this.gap = 5}); + + final String? pageType; + final double size; + + /// Space between the emoji and the name. + final double gap; + + @override + Widget build(BuildContext context) { + final icon = AppScope.of(context).typeIcon(pageType); + if (icon == null) return const SizedBox.shrink(); + return Padding( + padding: EdgeInsets.only(right: gap), + child: Text( + icon, + key: const ValueKey('type-icon'), + style: TextStyle(fontSize: size, height: 1.15), + ), + ); + } +} + +/// [title] prefixed with [icon] (for places that only take a string: canvas labels). +String withTypeIcon(String? icon, String title) => + icon == null ? title : '$icon $title'; From 00a64401e0310c99275c2a5fd398fa7a5e10fbb8 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 06:44:35 +0100 Subject: [PATCH 06/11] feat(app): show the type emoji before page names Page header, All pages, quick switcher, recents, tabs, hub members, tag view, linked references, related pages, type pill and the tree view; not the network graph. Co-Authored-By: Claude Opus 5.5 --- app/lib/src/graph/tree_canvas.dart | 37 +++- app/lib/src/views/all_pages_view.dart | 2 + app/lib/src/views/graph_view.dart | 1 + app/lib/src/views/hub_screen.dart | 2 + app/lib/src/views/page_screen.dart | 59 ++++-- app/lib/src/views/quick_switcher.dart | 23 +- app/lib/src/views/tab_strip.dart | 25 ++- app/lib/src/views/tag_view.dart | 17 +- app/lib/src/widgets/tags.dart | 22 +- app/test/tags_types_test.dart | 288 ++++++++++++++++++++++++++ 10 files changed, 430 insertions(+), 46 deletions(-) create mode 100644 app/test/tags_types_test.dart diff --git a/app/lib/src/graph/tree_canvas.dart b/app/lib/src/graph/tree_canvas.dart index 9649c16..bee4391 100644 --- a/app/lib/src/graph/tree_canvas.dart +++ b/app/lib/src/graph/tree_canvas.dart @@ -8,13 +8,17 @@ import 'package:flutter/scheduler.dart'; import '../state/app_state.dart'; import '../theme/theme.dart'; +import '../widgets/type_icon.dart'; import 'graph_model.dart'; /// A node of the hub / namespace / tag tree. class TreeItem { - TreeItem(this.label, {this.global, this.isHub = false}); + TreeItem(this.label, {this.global, this.isHub = false, this.icon}); final String label; + /// Emoji of the page's type, drawn before [label] (the network view never shows it). + String? icon; + /// Drawn with the folder look. final bool isHub; @@ -51,8 +55,13 @@ class TreeItem { /// split on `/`, straight off the centre) for pages in no hub, then the remaining notes /// (orphans included) straight off the centre. Journals and tags are left out. Nothing is /// capped: large branches are collapsed in the canvas instead. -TreeItem buildNamespaceTree(GraphModel g, {String name = 'Graph'}) { +TreeItem buildNamespaceTree( + GraphModel g, { + String name = 'Graph', + String? Function(String? type)? typeIcon, +}) { final root = TreeItem(name); + String? icon(int i) => typeIcon?.call(g.node(i).pageType); final placed = {}; bool page(int i) => !g.isJournal(i) && !g.isTag(i); @@ -61,14 +70,19 @@ TreeItem buildNamespaceTree(GraphModel g, {String name = 'Graph'}) { final nested = {for (final m in members.values) ...m}; TreeItem? build(int hub) { if (!placed.add(hub)) return null; - final item = TreeItem(g.node(hub).title, global: hub, isHub: true); + final item = TreeItem( + g.node(hub).title, + global: hub, + isHub: true, + icon: icon(hub), + ); for (final m in members[hub] ?? const {}) { if (!page(m)) continue; if (g.isHub(m)) { final sub = build(m); if (sub != null) item.children.add(sub); } else if (placed.add(m)) { - item.children.add(TreeItem(g.node(m).title, global: m)); + item.children.add(TreeItem(g.node(m).title, global: m, icon: icon(m))); } } return item; @@ -101,6 +115,7 @@ TreeItem buildNamespaceTree(GraphModel g, {String name = 'Graph'}) { final p = byTitle[parts.sublist(0, k + 1).join('/').toLowerCase()]; if (p != null && !placed.contains(p)) { at.global = p; + at.icon = icon(p); placed.add(p); } } @@ -110,7 +125,7 @@ TreeItem buildNamespaceTree(GraphModel g, {String name = 'Graph'}) { // Everything else hangs straight off the centre. for (var i = 0; i < g.nodeCount; i++) { if (page(i) && !g.isHub(i) && placed.add(i)) { - root.children.add(TreeItem(g.node(i).title, global: i)); + root.children.add(TreeItem(g.node(i).title, global: i, icon: icon(i))); } } _measure(root, 0, null); @@ -241,9 +256,13 @@ class TreeCanvas extends StatefulWidget { required this.model, required this.onTap, this.name = 'Graph', + this.typeIcon, }); final GraphModel model; + /// Emoji of a page type, shown before page labels. + final String? Function(String? type)? typeIcon; + /// Label of the centre: the name of the notes store. final String name; final void Function(int global) onTap; @@ -306,7 +325,11 @@ class TreeCanvasState extends State { } void _build() { - _root = buildNamespaceTree(widget.model, name: widget.name); + _root = buildNamespaceTree( + widget.model, + name: widget.name, + typeIcon: widget.typeIcon, + ); expandInitial(_root); _items = const []; _userMoved = false; @@ -850,7 +873,7 @@ class _TreePainter extends CustomPainter { ink, TextPainter( text: TextSpan( - text: t.label, + text: withTypeIcon(t.icon, t.label), style: TextStyle( fontFamily: uiFont, fontSize: t.parent == null ? 14 : (branch ? 12.5 : 11.5), diff --git a/app/lib/src/views/all_pages_view.dart b/app/lib/src/views/all_pages_view.dart index 918155e..b594c2c 100644 --- a/app/lib/src/views/all_pages_view.dart +++ b/app/lib/src/views/all_pages_view.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import '../backend/graph_backend.dart'; import '../state/app_state.dart'; import '../theme/theme.dart'; +import '../widgets/type_icon.dart'; import '../widgets/common.dart'; import '../widgets/dates.dart'; import '../widgets/pickers.dart' show errorText; @@ -303,6 +304,7 @@ class _AllPagesViewState extends State { : colors.faint, ), ), + TypeIcon(p.pageType, size: 14, gap: 6), Expanded( child: Text( p.title, diff --git a/app/lib/src/views/graph_view.dart b/app/lib/src/views/graph_view.dart index d396c44..34df677 100644 --- a/app/lib/src/views/graph_view.dart +++ b/app/lib/src/views/graph_view.dart @@ -442,6 +442,7 @@ class _GraphViewState extends State { model: m, onTap: _open, name: AppScope.read(context).backend.graphName, + typeIcon: AppScope.read(context).typeIcon, ); } final sub = _sub; diff --git a/app/lib/src/views/hub_screen.dart b/app/lib/src/views/hub_screen.dart index 1279313..8d35dc8 100644 --- a/app/lib/src/views/hub_screen.dart +++ b/app/lib/src/views/hub_screen.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import '../backend/graph_backend.dart'; import '../state/app_state.dart'; import '../theme/theme.dart'; +import '../widgets/type_icon.dart'; import '../widgets/common.dart'; import '../widgets/dates.dart'; import '../widgets/pickers.dart'; @@ -296,6 +297,7 @@ class _MemberRowState extends State<_MemberRow> { color: colors.accent.withAlpha(0xCC), ), const SizedBox(width: 10), + TypeIcon(m.pageType, size: 14, gap: 6), Expanded( child: Text( m.title, diff --git a/app/lib/src/views/page_screen.dart b/app/lib/src/views/page_screen.dart index a154185..a2a0426 100644 --- a/app/lib/src/views/page_screen.dart +++ b/app/lib/src/views/page_screen.dart @@ -5,6 +5,7 @@ import '../editor/outline_view.dart'; import '../state/app_state.dart'; import '../state/outline_controller.dart'; import '../theme/theme.dart'; +import '../widgets/type_icon.dart'; import '../widgets/common.dart'; import '../widgets/dates.dart'; import '../widgets/pickers.dart'; @@ -239,6 +240,10 @@ class _Header extends StatelessWidget { Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ + Padding( + padding: const EdgeInsets.only(top: 4), + child: TypeIcon(page.pageType, size: 26, gap: 10), + ), Expanded(child: TitleField(page: page)), IconButton( key: const ValueKey('page-sidebar-toggle'), @@ -471,16 +476,24 @@ class _LinkedReferences extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - TextLink( - group.isJournal - ? longDate(group.pageTitle) - : group.pageTitle, - onTap: () => app.openId(group.pageId), - style: TextStyle( - fontSize: 13, - fontWeight: FontWeight.w600, - color: colors.ink, - ), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + TypeIcon(group.pageType), + Flexible( + child: TextLink( + group.isJournal + ? longDate(group.pageTitle) + : group.pageTitle, + onTap: () => app.openId(group.pageId), + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: colors.ink, + ), + ), + ), + ], ), const SizedBox(height: 4), for (final b in group.blocks) @@ -544,13 +557,25 @@ class RelatedPanel extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - TextLink( - x.page.isJournal ? longDate(x.page.title) : x.page.title, - icon: x.page.isJournal - ? Icons.calendar_today_outlined - : Icons.description_outlined, - onTap: () => app.openId(x.page.id), - style: TextStyle(fontSize: 13.5, color: colors.ink), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + TypeIcon(x.page.pageType), + Flexible( + child: TextLink( + x.page.isJournal + ? longDate(x.page.title) + : x.page.title, + icon: app.typeIcon(x.page.pageType) != null + ? null + : x.page.isJournal + ? Icons.calendar_today_outlined + : Icons.description_outlined, + onTap: () => app.openId(x.page.id), + style: TextStyle(fontSize: 13.5, color: colors.ink), + ), + ), + ], ), const SizedBox(height: 4), ClipRRect( diff --git a/app/lib/src/views/quick_switcher.dart b/app/lib/src/views/quick_switcher.dart index 2f93f14..a1619b7 100644 --- a/app/lib/src/views/quick_switcher.dart +++ b/app/lib/src/views/quick_switcher.dart @@ -4,6 +4,7 @@ import 'package:flutter/services.dart'; import '../backend/graph_backend.dart'; import '../state/app_state.dart'; import '../theme/theme.dart'; +import '../widgets/type_icon.dart'; /// Ctrl+K: jump to a page by title or alias, to a page whose blocks contain the text, or /// create it. @@ -168,6 +169,7 @@ class _QuickSwitcherState extends State { onMiddle: () => _open(i, newTab: true), icon: Icons.description_outlined, title: _hits[i].title, + pageType: _hits[i].pageType, detail: _hits[i].isAlias ? 'alias' : null, ), if (_blocks.isNotEmpty) @@ -217,6 +219,7 @@ class _Item extends StatelessWidget { required this.onMiddle, this.detail, this.snippet, + this.pageType, }); final bool selected; final VoidCallback onTap; @@ -225,6 +228,9 @@ class _Item extends StatelessWidget { final String title; final String? detail; + /// Type of the page hit (its emoji goes before the title). + final String? pageType; + /// Matching text shown under the title (content results). final Widget? snippet; @@ -254,11 +260,18 @@ class _Item extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(fontSize: 14, color: colors.ink), + Row( + children: [ + TypeIcon(pageType), + Expanded( + child: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 14, color: colors.ink), + ), + ), + ], ), if (snippet != null) ...[ const SizedBox(height: 2), diff --git a/app/lib/src/views/tab_strip.dart b/app/lib/src/views/tab_strip.dart index 5e5723f..3ae250a 100644 --- a/app/lib/src/views/tab_strip.dart +++ b/app/lib/src/views/tab_strip.dart @@ -115,11 +115,18 @@ class _TabItemState extends State<_TabItem> { ), child: Row( children: [ - Icon( - widget.tab.icon, - size: 13, - color: active ? colors.accent : colors.faint, - ), + if (app.tabTypeIcon(widget.tab) case final emoji?) + Text( + emoji, + key: const ValueKey('type-icon'), + style: const TextStyle(fontSize: 12.5, height: 1.15), + ) + else + Icon( + widget.tab.icon, + size: 13, + color: active ? colors.accent : colors.faint, + ), const SizedBox(width: 7), Expanded( child: Text( @@ -215,7 +222,13 @@ Future showTabsSheet(BuildContext context) { dense: true, selected: i == app.activeTab, selectedColor: colors.accent, - leading: Icon(tabs[i].icon, size: 18), + leading: switch (app.tabTypeIcon(tabs[i])) { + final String emoji => Text( + emoji, + style: const TextStyle(fontSize: 16), + ), + null => Icon(tabs[i].icon, size: 18), + }, title: Text( tabs[i].title, maxLines: 1, diff --git a/app/lib/src/views/tag_view.dart b/app/lib/src/views/tag_view.dart index c23d179..47cb865 100644 --- a/app/lib/src/views/tag_view.dart +++ b/app/lib/src/views/tag_view.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import '../backend/graph_backend.dart'; import '../state/app_state.dart'; import '../theme/theme.dart'; +import '../widgets/type_icon.dart'; import '../widgets/common.dart'; import '../widgets/pickers.dart'; @@ -81,10 +82,17 @@ class TagView extends StatelessWidget { 80, ), children: [ - Text( - '#$name', - key: const ValueKey('tag-title'), - style: Theme.of(context).textTheme.headlineLarge, + Row( + children: [ + TypeIcon(name, size: 26, gap: 10), + Expanded( + child: Text( + '#$name', + key: const ValueKey('tag-title'), + style: Theme.of(context).textTheme.headlineLarge, + ), + ), + ], ), const SizedBox(height: 6), Wrap( @@ -137,6 +145,7 @@ class TagView extends StatelessWidget { color: colors.faint, ), const SizedBox(width: 10), + TypeIcon(p.pageType, size: 14, gap: 6), Expanded( child: Text( p.title, diff --git a/app/lib/src/widgets/tags.dart b/app/lib/src/widgets/tags.dart index 56540bf..6ea282e 100644 --- a/app/lib/src/widgets/tags.dart +++ b/app/lib/src/widgets/tags.dart @@ -5,6 +5,7 @@ import '../state/app_state.dart'; import '../theme/theme.dart'; import 'common.dart'; import 'pickers.dart'; +import 'type_icon.dart'; /// The page's metadata as one compact wrapping line: the type pill, the tag chips (sorted; /// tapping one opens its [TagRoute]) and a "+ tag" link. A page has at most one type; tags @@ -107,13 +108,19 @@ class _TypePill extends StatelessWidget { color: colors.accentSoft, borderRadius: BorderRadius.circular(6), ), - child: Text( - name, - style: TextStyle( - fontSize: 12.5, - fontWeight: FontWeight.w600, - color: colors.accent, - ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + TypeIcon(name, size: 12, gap: 4), + Text( + name, + style: TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + color: colors.accent, + ), + ), + ], ), ), ), @@ -295,6 +302,7 @@ class _TypePickerState extends State<_TypePicker> { for (final t in options) ActionChip( key: ValueKey('type-opt-${t.name}'), + avatar: t.icon == null ? null : Text(t.icon!), label: Text( t.count > 0 ? '${t.name} · ${t.count}' : t.name, style: TextStyle( diff --git a/app/test/tags_types_test.dart b/app/test/tags_types_test.dart new file mode 100644 index 0000000..962aa14 --- /dev/null +++ b/app/test/tags_types_test.dart @@ -0,0 +1,288 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:synapse/src/backend/graph_backend.dart'; +import 'package:synapse/src/graph/graph_model.dart'; +import 'package:synapse/src/graph/tree_canvas.dart'; +import 'package:synapse/src/state/app_state.dart'; +import 'package:synapse/src/theme/theme.dart'; +import 'package:synapse/src/views/all_pages_view.dart'; +import 'package:synapse/src/views/graph_view.dart'; +import 'package:synapse/src/views/quick_switcher.dart'; +import 'package:synapse/src/views/shell.dart'; +import 'package:synapse/src/views/tags_types_view.dart'; +import 'package:synapse/src/widgets/emoji_picker.dart'; +import 'package:synapse/src/widgets/type_icon.dart'; + +import 'support/memory_backend.dart'; + +/// Ada (persona, tag "math"), Bob (persona), Rome (lugar), Notes (untyped). +Future demo() async { + final b = MemoryBackend(); + final ada = b.createPage('Ada'); + await b.setPageType(ada.id, 'persona'); + await b.addPageTag(ada.id, 'math'); + await b.setPageType(b.createPage('Bob').id, 'persona'); + await b.setPageType(b.createPage('Rome').id, 'lugar'); + b.createPage('Notes'); + await b.setTypeIcon('persona', '🧑'); + return b; +} + +Future pump( + WidgetTester tester, + MemoryBackend b, { + Widget home = const Shell(), + AppRoute? route, +}) async { + tester.view.physicalSize = const Size(1600, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final app = AppState(b); + await app.loadTypeIcons(); + if (route != null) app.go(route); + await tester.pumpWidget( + AppScope( + state: app, + child: MaterialApp(theme: buildTheme(Brightness.light), home: home), + ), + ); + await settle(tester); + return app; +} + +Future settle(WidgetTester tester) async { + for (var i = 0; i < 6; i++) { + await tester.pump(const Duration(milliseconds: 50)); + } +} + +PageDto byTitle(MemoryBackend b, String t) => + b.pages.values.firstWhere((p) => p.title == t); + +void main() { + test('single emoji validation', () { + expect(isSingleEmoji('🧑'), isTrue); + expect(isSingleEmoji(' 👨‍👩‍👧 '), isTrue); + expect(isSingleEmoji('🇪🇸'), isTrue); + expect(isSingleEmoji('a'), isFalse); + expect(isSingleEmoji('🧑🧑'), isFalse); + expect(isSingleEmoji(''), isFalse); + }); + + test( + 'memory backend keeps icons through rename and drops them on delete', + () async { + final b = await demo(); + expect(await b.renameType('persona', 'Gente'), 2); + var cat = await b.typeCatalog(); + expect(cat.firstWhere((t) => t.name == 'Gente').icon, '🧑'); + expect(cat.any((t) => t.name == 'persona'), isFalse); + expect(await b.removeType('gente'), 2); + cat = await b.typeCatalog(); + expect(cat.any((t) => t.name.toLowerCase() == 'gente'), isFalse); + expect(await b.createType('Libro'), 'Libro'); + cat = await b.typeCatalog(); + expect(cat.firstWhere((t) => t.name == 'Libro').count, 0); + }, + ); + + testWidgets('sidebar opens Tags & types, also in a tab', (tester) async { + final app = await pump(tester, await demo()); + await tester.tap(find.text('Tags & types')); + await settle(tester); + expect(app.route, isA()); + expect(find.byType(TagsTypesView), findsOneWidget); + expect(app.tab.title, 'Tags & types'); + expect( + routeFromJson(routeToJson(const TagsTypesRoute())), + isA(), + ); + }); + + testWidgets('types list emoji, counts and unused suggestions', ( + tester, + ) async { + final b = await demo(); + final app = await pump( + tester, + b, + home: const Scaffold(body: TagsTypesView()), + ); + final persona = find.byKey(const ValueKey('type-row-persona')); + expect( + find.descendant(of: persona, matching: find.text('🧑')), + findsOneWidget, + ); + expect( + find.descendant(of: persona, matching: find.text('2 pages')), + findsOneWidget, + ); + expect(find.byKey(const ValueKey('type-row-empresa')), findsOneWidget); + + // Pick an emoji for "lugar" from the grid. + await tester.tap(find.byKey(const ValueKey('type-icon-btn-lugar'))); + await settle(tester); + await tester.tap(find.byKey(const ValueKey('emoji-Places-📍'))); + await settle(tester); + expect(app.typeIcon('Lugar'), '📍'); + + // A pasted emoji is validated. + await tester.tap(find.byKey(const ValueKey('type-icon-btn-lugar'))); + await settle(tester); + await tester.enterText(find.byKey(const ValueKey('emoji-input')), 'xy'); + await tester.tap(find.byKey(const ValueKey('emoji-use'))); + await settle(tester); + expect(find.text('Enter a single emoji'), findsOneWidget); + await tester.enterText(find.byKey(const ValueKey('emoji-input')), '🗺️'); + await tester.tap(find.byKey(const ValueKey('emoji-use'))); + await settle(tester); + expect(app.typeIcon('lugar'), '🗺️'); + + // Clearing it. + await tester.tap(find.byKey(const ValueKey('type-icon-btn-lugar'))); + await settle(tester); + await tester.tap(find.byKey(const ValueKey('emoji-clear'))); + await settle(tester); + expect(app.typeIcon('lugar'), isNull); + + // New type with no pages. + await tester.tap(find.byKey(const ValueKey('new-type'))); + await settle(tester); + await tester.enterText(find.byType(TextField).last, 'Libro'); + await tester.tap(find.text('Create')); + await settle(tester); + expect(find.byKey(const ValueKey('type-row-Libro')), findsOneWidget); + }); + + testWidgets('renaming a type keeps its emoji; deleting says what is lost', ( + tester, + ) async { + final b = await demo(); + final app = await pump( + tester, + b, + home: const Scaffold(body: TagsTypesView()), + ); + await tester.tap(find.byKey(const ValueKey('type-menu-persona'))); + await settle(tester); + await tester.tap(find.text('Rename…')); + await settle(tester); + await tester.enterText(find.byType(TextField).last, 'Gente'); + await tester.tap(find.text('Rename').last); + await settle(tester); + expect(byTitle(b, 'Ada').pageType, 'Gente'); + expect(app.typeIcon('gente'), '🧑'); + + await tester.tap(find.byKey(const ValueKey('type-menu-Gente'))); + await settle(tester); + await tester.tap(find.text('Delete…')); + await settle(tester); + expect(find.textContaining('2 pages lose this type'), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('tt-confirm'))); + await settle(tester); + expect(byTitle(b, 'Ada').pageType, isNull); + expect(byTitle(b, 'Ada').tags, ['math']); + expect(app.typeIcon('gente'), isNull); + expect(find.byKey(const ValueKey('type-row-Gente')), findsNothing); + }); + + testWidgets('tags: explicit ones can be renamed, hub tags are locked', ( + tester, + ) async { + final b = await demo(); + final hub = b.addHub('Anime'); + b.hubsOfPage[byTitle(b, 'Notes').id] = {hub.id}; + await pump(tester, b, home: const Scaffold(body: TagsTypesView())); + await tester.tap(find.byKey(const ValueKey('tt-tab-tags'))); + await settle(tester); + expect(find.byKey(const ValueKey('tag-menu-math')), findsOneWidget); + expect(find.byKey(const ValueKey('tag-locked-Anime')), findsOneWidget); + expect(find.byKey(const ValueKey('tag-locked-persona')), findsOneWidget); + final tip = tester.widget( + find.byKey(const ValueKey('tag-locked-Anime')), + ); + expect(tip.message, contains('hub')); + + await tester.tap(find.byKey(const ValueKey('tag-menu-math'))); + await settle(tester); + await tester.tap(find.text('Rename…')); + await settle(tester); + await tester.enterText(find.byType(TextField).last, 'maths'); + await tester.tap(find.text('Rename').last); + await settle(tester); + expect(byTitle(b, 'Ada').tags, ['maths']); + // Still on the Tags section after the reload. + expect(find.byKey(const ValueKey('tag-row-maths')), findsOneWidget); + + await tester.tap(find.byKey(const ValueKey('tag-menu-maths'))); + await settle(tester); + await tester.tap(find.text('Delete…')); + await settle(tester); + await tester.tap(find.byKey(const ValueKey('tt-confirm'))); + await settle(tester); + expect(byTitle(b, 'Ada').tags, isEmpty); + }); + + testWidgets('type emoji sits before page names across the app', ( + tester, + ) async { + final b = await demo(); + final app = await pump(tester, b, route: const AllPagesRoute()); + // All pages: Ada and Bob are personas. + expect( + find.descendant(of: find.byType(AllPagesView), matching: find.text('🧑')), + findsNWidgets(2), + ); + // Page header, tab strip and recents. + app.go(PageTarget(id: byTitle(b, 'Ada').id)); + await settle(tester); + expect(app.tab.pageType, 'persona'); + expect(app.tabTypeIcon(app.tab), '🧑'); + expect(find.text('🧑'), findsAtLeastNWidgets(3)); + // Tag view lists. + app.go(const TagRoute('persona')); + await settle(tester); + expect(find.text('🧑'), findsAtLeastNWidgets(3)); + }); + + testWidgets('quick switcher hits show the emoji', (tester) async { + final b = await demo(); + await pump(tester, b, home: const Scaffold(body: QuickSwitcher())); + await tester.enterText(find.byType(TextField), 'Ad'); + await settle(tester); + expect(find.text('🧑'), findsOneWidget); + }); + + testWidgets('network view draws no emoji; the tree does', (tester) async { + final b = await demo(); + final app = await pump( + tester, + b, + route: const GraphRoute(GraphMode.network), + ); + expect(find.byType(GraphView), findsOneWidget); + expect(find.byKey(const ValueKey('type-icon')), findsNothing); + expect(find.text('🧑'), findsNothing); + final data = await b.graphData(); + final ada = data.nodes.firstWhere((n) => n.title == 'Ada'); + expect(ada.title, 'Ada', reason: 'network labels are plain titles'); + + final root = buildNamespaceTree(GraphModel(data), typeIcon: app.typeIcon); + final items = []; + void walk(TreeItem t) { + items.add(t); + t.children.forEach(walk); + } + + walk(root); + expect(items.firstWhere((t) => t.label == 'Ada').icon, '🧑'); + expect(items.firstWhere((t) => t.label == 'Rome').icon, isNull); + expect(withTypeIcon('🧑', 'Ada'), '🧑 Ada'); + }); + + test('graph nodes from the memory backend carry the page type', () async { + final b = await demo(); + final data = await b.graphData(); + expect(data.nodes.firstWhere((n) => n.title == 'Rome').pageType, 'lugar'); + }); +} From bd2236bb894d3e22b777bc1525e7faf95d6cc7b0 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 06:45:04 +0100 Subject: [PATCH 07/11] docs: type emoji, Tags & types view, type_defs sync and history Co-Authored-By: Claude Opus 5.5 --- docs/app.md | 14 ++++++++++++++ docs/architecture.md | 15 ++++++++++++++- docs/history.md | 4 ++++ docs/sync.md | 7 +++++++ 4 files changed, 39 insertions(+), 1 deletion(-) diff --git a/docs/app.md b/docs/app.md index 46af9fd..807f6c5 100644 --- a/docs/app.md +++ b/docs/app.md @@ -147,6 +147,20 @@ Both are plain names with no page, shown as one row of pills under the title. - **Hub as tag**: a note's direct hub also counts as a tag of the same name (not shown as a chip, not stored in the tags). It lists in that tag's view and graph node and merges with a same-name type or tag; "Rename" there never renames the hub itself. +- **Type emoji**: each type can have an emoji, stored in the graph (synced, in history). It is + shown before the names of pages of that type: page title, All pages, quick switcher, + recents, tabs, hub members, tag view (also its title when the tag is a type), linked + references, related pages, the type pill and picker, and the tree view labels. Never in the + network graph. `AppState.typeIcons` caches type → emoji (`loadTypeIcons`, at start and + after edits); list DTOs carry `pageType` and `TypeIcon` (`widgets/type_icon.dart`) looks + it up. +- **Tags & types view** (sidebar, under All pages; also a tab route): "Types" lists every type + with its emoji, page count and seeded suggestions; the emoji button opens a picker (curated + grid by category, a field to paste any single emoji, "Remove emoji"); "New type" creates a + type with no pages; the `⋯` menu renames (keeps the emoji) or deletes (confirms how many + pages lose it). "Tags" lists every tag with its count and sources (listed, type, hub); + explicit tags can be renamed or deleted, tags that only come from a type or a hub show a + lock explaining where to change them. Tapping a name opens its tag view. - In the graph every tag is a virtual node drawn as a hollow accent ring and linked to its pages with a separate edge kind (TAGGED); tapping one opens its tag view. A hub's implicit tag (or a tag named like a hub) has no ring of its own: the hub node diff --git a/docs/architecture.md b/docs/architecture.md index caa38ec..c75bd99 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -37,6 +37,18 @@ crates may add their own tables to the same database (prefix them: `search_*`, ` - **A page has at most one type** (`Page.types`, 0 or 1 entries; `Page::page_type()`), a name saying what the page is. It implies a tag of the same name. API: `set_page_type(page, Option<&str>)`, `type_catalog` (types in use by count, then the seeded `SUGGESTED_TYPES`). +- **Type definitions** (schema v8): graph-wide metadata of a type name lives in + `type_defs(type_key, name, icon, removed, hlc)` (`TypeDef`), synced with its own op + `Op::PutTypeDef { def }`, last writer wins per name key (like `SetAlias`). It carries the + type's emoji (`icon`, a short non-ASCII string, `normalize_icon`) and keeps a type in the + vocabulary while no page uses it; `removed` is a tombstone (it also hides a seeded + suggestion of that name). API: `create_type`, `set_type_icon(name, Option<&str>)`, + `rename_type` (`rename_tag` plus keeping an unused type), `remove_type` (clears the type + from its pages, tombstones the definition), `type_defs`, `all_page_types`. `rename_tag` + moves the definition to the new name (a target with its own icon keeps it). `type_catalog` + lists used types, then defined unused ones, then remaining suggestions, each with its icon; + `tag_catalog` counts per tag the pages listing it (`explicit`), typed with it (`typed`) + and carrying it through their hub (`from_hub`). - **A page's direct hub is an implicit tag**, like its type: members of hub "Anime" are filed under "Anime" (`page_tags`, `pages_with_tag`, `tag_catalog`, the graph's tag node). It is not stored in `Page.tags` and merges with a same-name type or tag. Only the direct hub @@ -50,7 +62,8 @@ crates may add their own tables to the same database (prefix them: `search_*`, ` A tag named like a hub in the graph uses the hub's node instead; its members, already linked by `CONTAINS`, get no `TAGGED` edge. - Known limitations: replicas still on the old schema may overwrite tags with stale values (LWW per page), and `rename_tag` is a bulk page edit, so concurrent edits on another replica can undo part of it. -- Exports use `synapse-tags::` and `synapse-type::` (see `history.md`). +- Exports use `synapse-tags::` and `synapse-type::` (see `history.md`); type definitions go + to `types.json`. ## Hubs and namespaces (`synapse-core::structure`) Two orthogonal ways to organise pages. diff --git a/docs/history.md b/docs/history.md index ac1f3cf..d08449c 100644 --- a/docs/history.md +++ b/docs/history.md @@ -16,6 +16,10 @@ works on it (`git --git-dir=/history log`, `clone`, ...). bullets). A page's tags (names, no pages) are listed in `synapse-tags:: ["a","b"]` and its single type in `synapse-type:: persona` (both restored with the page; the old list form `synapse-types::` is still read, first entry wins). Exports of older versions may carry `synapse-kind:: tag` on a former tag page; it is ignored and the page restores as a note. A page in hubs lists their titles in `synapse-hubs:: ["A","B"]`, so renaming a hub re-exports its members. Restore sets kinds first, then memberships (missing hubs or memberships that would now form a cycle are skipped). +- `types.json`: live type definitions (`[{name, icon}]`, sorted by name key; left out when + there are none). `restore_graph` defines each listed type with its icon; types defined + since keep existing but lose their icon (a tombstone would also hide a seeded suggestion). + A change alone commits as "types updated". - `assets.json`: manifest `hash → name/size/mime`, sorted. Asset bytes are **not** committed (the blob store is already content-addressed) unless `HistoryOptions::include_blobs`, which adds `blobs/`. diff --git a/docs/sync.md b/docs/sync.md index 0c743e6..e3b99f0 100644 --- a/docs/sync.md +++ b/docs/sync.md @@ -105,6 +105,13 @@ runtime (`start()` spawns onto the current one). After local edits call `trigger - **Uploads** only complete when the server reports the blob stored (`HEAD` 200); `202`/`409` responses make the client resume until done. +## Op kinds +`upsert_page`, `delete_page`, `upsert_block`, `delete_block`, `put_asset`, `set_alias` and +`put_type_def` (type metadata: name, emoji, tombstone; LWW per type name key, schema v8). +A client too old to know an op kind cannot parse a pull batch containing it: its sync stops +with an error (local edits stay pending) until it is updated. The protocol version was not +bumped for `put_type_def`, so update every client together with the server. + ## Limits / not in v1 - Per-user tokens and per-graph ACLs: `auth::Principal` already carries a graph allow-list; only the token source (env list) is implemented. From 872073a0a05b06f5bb3727879fd1f60aa90c5196 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 06:52:44 +0100 Subject: [PATCH 08/11] fix(core): clearing an undefined type's icon defines nothing Also covers that renaming a plain tag leaves an undefined (suggested) type of that name alone. Co-Authored-By: Claude Opus 5.5 --- crates/synapse-core/src/types.rs | 7 ++++--- crates/synapse-core/tests/structure.rs | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/crates/synapse-core/src/types.rs b/crates/synapse-core/src/types.rs index d504f65..8c6f801 100644 --- a/crates/synapse-core/src/types.rs +++ b/crates/synapse-core/src/types.rs @@ -245,8 +245,8 @@ impl Graph { Ok(name) } - /// Sets (or with `None` clears) the emoji of a type, defining the type if needed (see - /// [`normalize_icon`] for what an icon may be). + /// Sets (or with `None` clears) the emoji of a type, defining the type when setting one + /// (see [`normalize_icon`] for what an icon may be). Clearing an undefined type is a no-op. pub fn set_type_icon(&self, name: &str, icon: Option<&str>) -> Result<()> { let name = checked_type_name(name)?; let icon = match icon { @@ -255,7 +255,8 @@ impl Graph { }; let tx = self.tx()?; let current = self.type_def(&name)?.filter(|d| !d.removed); - if current.as_ref().is_some_and(|d| d.icon == icon) { + // Clearing the icon of an undefined type changes nothing (and defines nothing). + if current.as_ref().map_or(icon.is_none(), |d| d.icon == icon) { tx.commit()?; return Ok(()); } diff --git a/crates/synapse-core/tests/structure.rs b/crates/synapse-core/tests/structure.rs index 2d3b2b0..e425f70 100644 --- a/crates/synapse-core/tests/structure.rs +++ b/crates/synapse-core/tests/structure.rs @@ -1089,6 +1089,29 @@ fn renaming_a_type_keeps_its_icon_and_removing_drops_it() { assert_eq!(type_row(&g, "lugar"), Some(("lugar".into(), 1, None))); } +#[test] +fn renaming_a_tag_leaves_undefined_types_alone() { + let (_d, g) = graph(); + let a = page(&g, "A", &["x"]); + g.add_page_tag(a, "idea").unwrap(); + let seq = g.last_seq().unwrap(); + g.rename_tag("idea", "ocurrencia").unwrap(); + // "idea" is only a suggestion (no definition): it stays offered, nothing is defined. + assert_eq!(type_row(&g, "idea"), Some(("idea".into(), 0, None))); + assert!(g.type_defs().unwrap().is_empty()); + assert!( + g.ops_since(seq, 100) + .unwrap() + .iter() + .all(|r| !matches!(r.op, Op::PutTypeDef { .. })) + ); + // Clearing the icon of an undefined type is a no-op. + g.set_type_icon("idea", None).unwrap(); + g.set_type_icon("nueva", None).unwrap(); + assert!(g.type_defs().unwrap().is_empty()); + assert_eq!(type_row(&g, "nueva"), None); +} + #[test] fn tag_catalog_says_where_each_tag_comes_from() { let (_d, g) = graph(); From ad03383933c0bd0ed35915179ef869e02dfd912c Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 06:53:24 +0100 Subject: [PATCH 09/11] test(app): MemoryBackend follows the core's type spelling, name cap and icon clearing Co-Authored-By: Claude Opus 5.5 --- app/test/support/memory_backend.dart | 24 ++++++++++++++++++++++-- app/test/tags_types_test.dart | 8 ++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/app/test/support/memory_backend.dart b/app/test/support/memory_backend.dart index 7d98713..259e52b 100644 --- a/app/test/support/memory_backend.dart +++ b/app/test/support/memory_backend.dart @@ -514,6 +514,16 @@ class MemoryBackend implements GraphBackend { /// Type definitions like the core's `type_defs`: key -> (name, icon, removed). final typeDefs = {}; + /// Pages in the core's catalogue order (`created_at`, then id): the first spells a name. + List _byCreation() => pages.values.toList() + ..sort((a, b) { + final c = a.createdAt.compareTo(b.createdAt); + return c != 0 ? c : a.id.compareTo(b.id); + }); + + /// Like the core's `MAX_TAG_CHARS`. + static const maxTagChars = 48; + ({String name, String? icon, bool removed})? _liveDef(String name) { final d = typeDefs[_tagKey(name)]; return d == null || d.removed ? null : d; @@ -522,7 +532,7 @@ class MemoryBackend implements GraphBackend { @override Future> typeCatalog() async { final used = {}; - for (final p in pages.values) { + for (final p in _byCreation()) { for (final t in [if (p.pageType != null) p.pageType!]) { final k = _tagKey(t); used[k] = _tag( @@ -580,6 +590,9 @@ class MemoryBackend implements GraphBackend { String _typeName(String raw) { final n = _normTag(raw); if (n.isEmpty) throw Exception('Empty type name'); + if (n.runes.length > maxTagChars) { + throw Exception('Type is longer than $maxTagChars characters'); + } return n; } @@ -587,7 +600,7 @@ class MemoryBackend implements GraphBackend { String _typeSpelling(String name) { final d = _liveDef(name); if (d != null) return d.name; - for (final p in pages.values) { + for (final p in _byCreation()) { if (p.pageType != null && _tagKey(p.pageType!) == _tagKey(name)) { return p.pageType!; } @@ -616,6 +629,10 @@ class MemoryBackend implements GraphBackend { i.runes.every((r) => r < 128))) { throw Exception('Not an emoji icon'); } + final current = _liveDef(n); + final next = (i == null || i.isEmpty) ? null : i; + // Like the core: clearing an undefined type's icon defines nothing. + if (current == null ? next == null : current.icon == next) return; typeDefs[_tagKey(n)] = ( name: _typeSpelling(n), icon: (i == null || i.isEmpty) ? null : i, @@ -710,6 +727,9 @@ class MemoryBackend implements GraphBackend { Future renameTag(String old, String new_) async { final name = _normTag(new_); if (name.isEmpty) throw Exception('Empty tag name'); + if (name.runes.length > maxTagChars) { + throw Exception('Tag is longer than $maxTagChars characters'); + } var n = 0; for (final p in pages.values.toList()) { final hasTag = p.tags.any((t) => _tagKey(t) == _tagKey(old)); diff --git a/app/test/tags_types_test.dart b/app/test/tags_types_test.dart index 962aa14..5ba3d69 100644 --- a/app/test/tags_types_test.dart +++ b/app/test/tags_types_test.dart @@ -73,6 +73,14 @@ void main() { 'memory backend keeps icons through rename and drops them on delete', () async { final b = await demo(); + // Like the core: clearing an undefined type's icon defines nothing, names are capped, + // and renaming a plain tag defines no type. + await b.setTypeIcon('nueva', null); + expect(b.typeDefs.containsKey('nueva'), isFalse); + expect(() => b.renameTag('math', 'x' * 49), throwsException); + expect(() => b.createType('x' * 49), throwsException); + await b.renameTag('math', 'idea'); + expect(b.typeDefs.containsKey('math'), isFalse); expect(await b.renameType('persona', 'Gente'), 2); var cat = await b.typeCatalog(); expect(cat.firstWhere((t) => t.name == 'Gente').icon, '🧑'); From 1a8bca5deb8c1ef533eb9fc8a10c530c7d4177c5 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 06:55:22 +0100 Subject: [PATCH 10/11] fix(app): tag view refreshes type icons after renaming or removing a tag Co-Authored-By: Claude Opus 5.5 --- app/lib/src/views/tag_view.dart | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/lib/src/views/tag_view.dart b/app/lib/src/views/tag_view.dart index 47cb865..7f4e197 100644 --- a/app/lib/src/views/tag_view.dart +++ b/app/lib/src/views/tag_view.dart @@ -26,6 +26,8 @@ class TagView extends StatelessWidget { () => app.backend.renameTag(name, next), report: false, ); + // A type of that name moves its emoji to the new name. + await app.loadTypeIcons(); app.replaceRoute(TagRoute(next)); } catch (e) { messenger.showSnackBar(SnackBar(content: Text(errorText(e)))); @@ -59,6 +61,7 @@ class TagView extends StatelessWidget { if (ok != true) return; try { await app.queue.run(() => app.backend.removeTag(name), report: false); + await app.loadTypeIcons(); app.reload(); } catch (e) { messenger.showSnackBar(SnackBar(content: Text(errorText(e)))); From 8a0fdc7610c42b1e4723444ab0875b3d8b27caf5 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 06:55:22 +0100 Subject: [PATCH 11/11] fix(app): type icon cache refreshes on reload and reaches the tree view loadTypeIcons logs failures, only notifies on change and bumps iconsVersion; every generation bump reloads it. The tree re-resolves label icons when iconsVersion changes, without re-running the layout. Co-Authored-By: Claude Opus 5.5 --- app/lib/src/graph/tree_canvas.dart | 25 ++++++++-- app/lib/src/state/app_state.dart | 40 +++++++++++---- app/lib/src/views/graph_view.dart | 2 + app/test/tags_types_test.dart | 79 ++++++++++++++++++++++++++++++ docs/app.md | 7 +-- 5 files changed, 136 insertions(+), 17 deletions(-) diff --git a/app/lib/src/graph/tree_canvas.dart b/app/lib/src/graph/tree_canvas.dart index bee4391..2f0601e 100644 --- a/app/lib/src/graph/tree_canvas.dart +++ b/app/lib/src/graph/tree_canvas.dart @@ -257,12 +257,16 @@ class TreeCanvas extends StatefulWidget { required this.onTap, this.name = 'Graph', this.typeIcon, + this.iconsVersion = 0, }); final GraphModel model; /// Emoji of a page type, shown before page labels. final String? Function(String? type)? typeIcon; + /// Changes when the type icons change: labels re-resolve their emoji (no new layout). + final int iconsVersion; + /// Label of the centre: the name of the notes store. final String name; final void Function(int global) onTap; @@ -313,9 +317,21 @@ class TreeCanvasState extends State { if (!identical(oldWidget.model, widget.model) || oldWidget.name != widget.name) { _build(); + } else if (oldWidget.iconsVersion != widget.iconsVersion) { + _refreshIcons(_root); + _repaint.value++; } } + /// Re-reads the type emoji of every page item (labels redraw with them). + void _refreshIcons(TreeItem t) { + final g = t.global; + if (g != null) { + t.icon = widget.typeIcon?.call(widget.model.node(g).pageType); + } + t.children.forEach(_refreshIcons); + } + @override void dispose() { _generation++; @@ -739,8 +755,8 @@ class _TreePainter extends CustomPainter { final Brightness brightness; final TextScaler textScaler; - /// Laid-out labels per item, invalidated when the text colours change. - static final _cache = Expando<(Color, TextPainter)>(); + /// Laid-out labels per item, invalidated when the text colour or the icon changes. + static final _cache = Expando<(Color, String?, TextPainter)>(); @override void paint(Canvas canvas, Size size) { @@ -868,9 +884,10 @@ class _TreePainter extends CustomPainter { final branch = t.children.isNotEmpty; final ink = branch || t.parent == null ? colors.ink : colors.muted; var entry = _cache[t]; - if (entry == null || entry.$1 != ink) { + if (entry == null || entry.$1 != ink || entry.$2 != t.icon) { entry = _cache[t] = ( ink, + t.icon, TextPainter( text: TextSpan( text: withTypeIcon(t.icon, t.label), @@ -890,7 +907,7 @@ class _TreePainter extends CustomPainter { )..layout(maxWidth: 170), ); } - final tp = entry.$2; + final tp = entry.$3; final r = s._radius(t) * scale.clamp(0.6, 1.6); // Labels on the outer side of the node, away from its parent. final par = t.parent == null ? null : s._index[t.parent!]; diff --git a/app/lib/src/state/app_state.dart b/app/lib/src/state/app_state.dart index 0729fc9..fc75c80 100644 --- a/app/lib/src/state/app_state.dart +++ b/app/lib/src/state/app_state.dart @@ -1,5 +1,6 @@ import 'dart:ui' show PlatformDispatcher; +import 'package:flutter/foundation.dart' show mapEquals; import 'package:flutter/material.dart'; import 'package:flutter/services.dart' show HardwareKeyboard; @@ -362,18 +363,37 @@ class AppState extends ChangeNotifier { String? tabTypeIcon(AppTab t) => t.route is PageTarget ? typeIcon(t.pageType) : null; - /// Reloads [typeIcons] from the type catalogue (at start and after type edits). + /// Bumped whenever [typeIcons] changes (lets painters such as the tree view redraw). + int iconsVersion = 0; + + /// Reloads [typeIcons] from the type catalogue (at start, after type edits and on every + /// [reload]); listeners are only notified when something changed. Errors are logged. Future loadTypeIcons() async { - final types = await backend.typeCatalog(); + final List types; + try { + types = await backend.typeCatalog(); + } catch (e, st) { + debugPrint('loading type icons failed: $e\n$st'); + return; + } + final next = { + for (final t in types) + if (t.icon != null) t.name.toLowerCase(): t.icon!, + }; + if (mapEquals(next, typeIcons)) return; typeIcons ..clear() - ..addAll({ - for (final t in types) - if (t.icon != null) t.name.toLowerCase(): t.icon!, - }); + ..addAll(next); + iconsVersion++; notifyListeners(); } + /// Views reload from the core: so do the type icons (they may have changed elsewhere). + void _bumpGeneration() { + generation++; + loadTypeIcons().ignore(); + } + /// Hubs expanded in the sidebar tree (kept here so it survives sidebar rebuilds). final expandedHubs = {}; @@ -405,7 +425,7 @@ class AppState extends ChangeNotifier { /// Rebuilds the current view from the core (after queued writes have run). void reload() { - generation++; + _bumpGeneration(); notifyListeners(); } @@ -495,7 +515,7 @@ class AppState extends ChangeNotifier { } } } - generation++; + _bumpGeneration(); _saveSettings(); notifyListeners(); } @@ -547,7 +567,7 @@ class AppState extends ChangeNotifier { t.label = null; } } - generation++; + _bumpGeneration(); _saveSettings(); notifyListeners(); } @@ -557,7 +577,7 @@ class AppState extends ChangeNotifier { tab ..route = r ..label = null; - generation++; + _bumpGeneration(); _saveSettings(); notifyListeners(); } diff --git a/app/lib/src/views/graph_view.dart b/app/lib/src/views/graph_view.dart index 34df677..d4ca975 100644 --- a/app/lib/src/views/graph_view.dart +++ b/app/lib/src/views/graph_view.dart @@ -443,6 +443,8 @@ class _GraphViewState extends State { onTap: _open, name: AppScope.read(context).backend.graphName, typeIcon: AppScope.read(context).typeIcon, + // Subscribes: icon edits (or icons loaded after a cold start) reach the labels. + iconsVersion: AppScope.of(context).iconsVersion, ); } final sub = _sub; diff --git a/app/test/tags_types_test.dart b/app/test/tags_types_test.dart index 5ba3d69..4f3e455 100644 --- a/app/test/tags_types_test.dart +++ b/app/test/tags_types_test.dart @@ -293,4 +293,83 @@ void main() { final data = await b.graphData(); expect(data.nodes.firstWhere((n) => n.title == 'Rome').pageType, 'lugar'); }); + + testWidgets('the tree picks up icons loaded or edited after it was built', ( + tester, + ) async { + final b = await demo(); + tester.view.physicalSize = const Size(1600, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + // Cold start: the icon cache is still empty when the tree is built. + final app = AppState(b)..go(const GraphRoute(GraphMode.tree)); + await tester.pumpWidget( + AppScope( + state: app, + child: MaterialApp( + theme: buildTheme(Brightness.light), + home: const Scaffold(body: GraphView(mode: GraphMode.tree)), + ), + ), + ); + await settle(tester); + TreeItem ada() { + final items = []; + void walk(TreeItem t) { + items.add(t); + t.children.forEach(walk); + } + + walk(tester.state(find.byType(TreeCanvas)).root); + return items.firstWhere((t) => t.label == 'Ada'); + } + + expect(ada().icon, isNull); + await app.loadTypeIcons(); + await settle(tester); + expect(ada().icon, '🧑'); + await b.setTypeIcon('persona', '👤'); + await app.loadTypeIcons(); + await settle(tester); + expect(ada().icon, '👤'); + }); + + test('reload refreshes the icon cache; failures are logged', () async { + final b = await demo(); + final app = AppState(b); + await app.loadTypeIcons(); + expect(app.typeIcon('persona'), '🧑'); + final v = app.iconsVersion; + await app.loadTypeIcons(); + expect(app.iconsVersion, v, reason: 'unchanged icons do not notify'); + // Changed elsewhere (sync, restore): a reload picks it up. + await b.setTypeIcon('persona', '👤'); + app.reload(); + await Future.delayed(Duration.zero); + expect(app.typeIcon('persona'), '👤'); + await AppState(_FailingBackend()).loadTypeIcons(); + }); + + testWidgets( + 'renaming a tag from its view moves the type emoji in the cache', + (tester) async { + final b = await demo(); + final app = await pump(tester, b, route: const TagRoute('persona')); + await tester.tap(find.byKey(const ValueKey('tag-rename'))); + await settle(tester); + await tester.enterText( + find.byKey(const ValueKey('tag-rename-input')), + 'gente', + ); + await tester.tap(find.byKey(const ValueKey('tag-rename-confirm'))); + await settle(tester); + expect(app.typeIcon('gente'), '🧑'); + expect(app.typeIcon('persona'), isNull); + }, + ); +} + +class _FailingBackend extends MemoryBackend { + @override + Future> typeCatalog() async => throw Exception('boom'); } diff --git a/docs/app.md b/docs/app.md index 807f6c5..54f00bd 100644 --- a/docs/app.md +++ b/docs/app.md @@ -151,9 +151,10 @@ Both are plain names with no page, shown as one row of pills under the title. shown before the names of pages of that type: page title, All pages, quick switcher, recents, tabs, hub members, tag view (also its title when the tag is a type), linked references, related pages, the type pill and picker, and the tree view labels. Never in the - network graph. `AppState.typeIcons` caches type → emoji (`loadTypeIcons`, at start and - after edits); list DTOs carry `pageType` and `TypeIcon` (`widgets/type_icon.dart`) looks - it up. + network graph. `AppState.typeIcons` caches type → emoji (`loadTypeIcons`: at start, after + edits and on every view reload, so synced or restored changes show; `iconsVersion` makes + the tree view redraw its labels without a new layout); list DTOs carry `pageType` and + `TypeIcon` (`widgets/type_icon.dart`) looks it up. - **Tags & types view** (sidebar, under All pages; also a tab route): "Types" lists every type with its emoji, page count and seeded suggestions; the emoji button opens a picker (curated grid by category, a field to paste any single emoji, "Remove emoji"); "New type" creates a