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 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-26 06:33:33 +01:00
1 parent a8559fd467
commit 206b62d4ab
8 files changed
+471 -16

No files matched your search

+1 -1
View File
@@ -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};
+37 -6
View File
@@ -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<PageId> },
UpsertPage {
page: Page,
},
DeletePage {
id: PageId,
},
UpsertBlock {
block: Block,
},
DeleteBlock {
id: BlockId,
},
PutAsset {
asset: Asset,
},
SetAlias {
alias: String,
page: Option<PageId>,
},
/// 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<String>,
#[serde(default)]
pub removed: bool,
}
/// Fields for creating a page; defaults come from the graph clock.
+11 -1
View File
@@ -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()],
+29
View File
@@ -1161,6 +1161,19 @@ impl Graph {
true
}
}
Op::PutTypeDef { def } => {
let local: Option<String> = 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<Option<Page>> {
Ok(self
+6 -1
View File
@@ -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<String>,
}
/// 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<usize> {
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)
}
+233 -5
View File
@@ -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<Option<String>> {
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<String> {
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<Vec<TagInfo>> {
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<TagInfo> = 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<HashMap<String, TypeDef>> {
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::<rusqlite::Result<_>>()?)
}
/// The definition of one type name (case-insensitive), removed ones included.
pub fn type_def(&self, name: &str) -> Result<Option<TypeDef>> {
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<String> {
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<String> {
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<usize> {
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<usize> {
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,
})
}
}
+153 -1
View File
@@ -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<String>)> {
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::<Op>(&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("🧑"));
}
+1 -1
View File
@@ -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();