mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 23:36:20 +00:00
feat(core): a page's direct hub is an implicit tag
Members of a hub are indexed under the hub's title in page_tags, tag_catalog and the graph tag nodes, merged with a same-name type or tag. Hub rename, delete and membership changes re-index the derived index (no ops). Schema v7 rebuilds it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3585ce67af
commit
6f483ce763
10 files changed
+273
-77
No files matched your search
@@ -173,12 +173,12 @@ class GraphModel {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tag nodes (and pages targeted by inline `#tag` references) actually used as tags,
|
/// Virtual tag nodes in use (targets of `TAGGED` edges), most used first. Pages targeted
|
||||||
/// most used first.
|
/// by inline `#x` references are ordinary notes and are not listed.
|
||||||
late final List<int> tags = () {
|
late final List<int> tags = () {
|
||||||
final count = <int, int>{};
|
final count = <int, int>{};
|
||||||
for (var e = 0; e < edgeCount; e++) {
|
for (var e = 0; e < edgeCount; e++) {
|
||||||
if (kind(e) == EdgeKind.tag || kind(e) == EdgeKind.tagged) {
|
if (kind(e) == EdgeKind.tagged && isTag(target(e))) {
|
||||||
count[target(e)] = (count[target(e)] ?? 0) + 1;
|
count[target(e)] = (count[target(e)] ?? 0) + 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -307,13 +307,28 @@ class GraphFilter {
|
|||||||
'-${d.day.toString().padLeft(2, '0')}';
|
'-${d.day.toString().padLeft(2, '0')}';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool inRange(int i) =>
|
||||||
|
(from == null || day(i).compareTo(from!) >= 0) &&
|
||||||
|
(to == null || day(i).compareTo(to!) <= 0);
|
||||||
|
// A tag node has no creation date: it stays when one of its tagged pages is in range.
|
||||||
|
bool tagInRange(int i) {
|
||||||
|
if (from == null && to == null) return true;
|
||||||
|
for (final e in g.adjacency[i]) {
|
||||||
|
if (g.kind(e) != EdgeKind.tagged || g.target(e) != i) continue;
|
||||||
|
final p = g.source(e);
|
||||||
|
if (!g.isTag(p) && (journals || !g.isJournal(p)) && inRange(p)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
final base = <int>[
|
final base = <int>[
|
||||||
for (var i = 0; i < g.nodeCount; i++)
|
for (var i = 0; i < g.nodeCount; i++)
|
||||||
if ((journals || !g.isJournal(i)) &&
|
if ((journals || !g.isJournal(i)) &&
|
||||||
(tagged == null || tagged.contains(i)) &&
|
(tagged == null || tagged.contains(i)) &&
|
||||||
(q.isEmpty || g.node(i).title.toLowerCase().contains(q)) &&
|
(q.isEmpty || g.node(i).title.toLowerCase().contains(q)) &&
|
||||||
(from == null || day(i).compareTo(from!) >= 0) &&
|
(g.isTag(i) ? tagInRange(i) : inRange(i)))
|
||||||
(to == null || day(i).compareTo(to!) <= 0))
|
|
||||||
i,
|
i,
|
||||||
];
|
];
|
||||||
if (orphans && minDegree == 0) return base;
|
if (orphans && minDegree == 0) return base;
|
||||||
|
|||||||
@@ -199,7 +199,7 @@ class NetworkCanvasState extends State<NetworkCanvas>
|
|||||||
? -1
|
? -1
|
||||||
: (() {
|
: (() {
|
||||||
final i = g.tags.indexOf(n.primaryTag!);
|
final i = g.tags.indexOf(n.primaryTag!);
|
||||||
return i < 10 ? i : -1;
|
return i >= 0 && i < 10 ? i : -1;
|
||||||
})(),
|
})(),
|
||||||
ColorBy.hub =>
|
ColorBy.hub =>
|
||||||
n.homeHub == null
|
n.homeHub == null
|
||||||
|
|||||||
@@ -68,11 +68,17 @@ class _GraphViewState extends State<GraphView> {
|
|||||||
if (focus != null) break;
|
if (focus != null) break;
|
||||||
focus = m.indexOf(r.id);
|
focus = m.indexOf(r.id);
|
||||||
}
|
}
|
||||||
if (focus == null && m.nodeCount > 0) {
|
if (focus != null && m.isTag(focus)) focus = null;
|
||||||
focus = List.generate(
|
if (focus == null) {
|
||||||
m.nodeCount,
|
final pages = [
|
||||||
(i) => i,
|
for (var i = 0; i < m.nodeCount; i++)
|
||||||
).reduce((a, b) => m.node(a).degree >= m.node(b).degree ? a : b);
|
if (!m.isTag(i)) i,
|
||||||
|
];
|
||||||
|
if (pages.isNotEmpty) {
|
||||||
|
focus = pages.reduce(
|
||||||
|
(a, b) => m.node(a).degree >= m.node(b).degree ? a : b,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
setState(() {
|
setState(() {
|
||||||
_model = m;
|
_model = m;
|
||||||
@@ -124,7 +130,12 @@ class _GraphViewState extends State<GraphView> {
|
|||||||
final f = _focus;
|
final f = _focus;
|
||||||
if (f == null) return;
|
if (f == null) return;
|
||||||
final app = AppScope.read(context);
|
final app = AppScope.read(context);
|
||||||
final related = await app.backend.related(m.node(f).id, limit: 40);
|
final List<RelatedDto> related;
|
||||||
|
try {
|
||||||
|
related = await app.backend.related(m.node(f).id, limit: 40);
|
||||||
|
} catch (_) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (!mounted || _focus != f || _mode != GraphMode.brain) return;
|
if (!mounted || _focus != f || _mode != GraphMode.brain) return;
|
||||||
final top = related.isEmpty
|
final top = related.isEmpty
|
||||||
? 1.0
|
? 1.0
|
||||||
@@ -265,7 +276,7 @@ class _GraphViewState extends State<GraphView> {
|
|||||||
onSubmitted: (q) {
|
onSubmitted: (q) {
|
||||||
final lq = q.toLowerCase().trim();
|
final lq = q.toLowerCase().trim();
|
||||||
for (var i = 0; i < m.nodeCount; i++) {
|
for (var i = 0; i < m.nodeCount; i++) {
|
||||||
if (m.node(i).title.toLowerCase().contains(lq)) {
|
if (!m.isTag(i) && m.node(i).title.toLowerCase().contains(lq)) {
|
||||||
_setFocus(i);
|
_setFocus(i);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -453,7 +464,9 @@ class _GraphViewState extends State<GraphView> {
|
|||||||
hulls: _mode == GraphMode.clusters,
|
hulls: _mode == GraphMode.clusters,
|
||||||
focus: explore ? _focus : null,
|
focus: explore ? _focus : null,
|
||||||
brain: _mode == GraphMode.brain ? _brain : null,
|
brain: _mode == GraphMode.brain ? _brain : null,
|
||||||
onTap: explore ? _setFocus : _open,
|
onTap: explore
|
||||||
|
? (i) => m.isTag(i) ? _open(i) : _setFocus(i)
|
||||||
|
: _open,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
Positioned(
|
Positioned(
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use rusqlite::OptionalExtension;
|
use rusqlite::OptionalExtension;
|
||||||
|
|
||||||
pub const VERSION: i64 = 6;
|
pub const VERSION: i64 = 7;
|
||||||
|
|
||||||
pub const SCHEMA: &str = r#"
|
pub const SCHEMA: &str = r#"
|
||||||
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||||
@@ -116,28 +116,74 @@ CREATE TABLE IF NOT EXISTS ops (
|
|||||||
);
|
);
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
/// Rebuilds the `page_tags` index from every page's `tags` column and first type (the type
|
/// Every page's tag sources: `tags`, `types` and the title of its direct hub (an implicit tag,
|
||||||
/// implies a tag of the same name). Malformed JSON values count as empty.
|
/// only for notes: hubs, templates and journals get none). Joined through `page_hubs`, which
|
||||||
pub fn rebuild_page_tags(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
|
/// holds at most one row per page. `?1` limits the result to one page id (NULL: all pages).
|
||||||
conn.execute("DELETE FROM page_tags", [])?;
|
pub const TAG_SOURCES_SQL: &str = "SELECT p.id, p.tags, p.types, h.title FROM pages p
|
||||||
let rows: Vec<(String, String, String)> = {
|
LEFT JOIN page_hubs ph ON ph.page_id = p.id AND p.kind = 'note' AND p.journal_date IS NULL
|
||||||
let mut st =
|
LEFT JOIN pages h ON h.id = ph.hub_id AND h.kind = 'hub'
|
||||||
conn.prepare("SELECT id, tags, types FROM pages WHERE tags != '[]' OR types != '[]'")?;
|
WHERE (?1 IS NULL OR p.id = ?1)";
|
||||||
st.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?
|
|
||||||
.collect::<rusqlite::Result<_>>()?
|
/// One page's tag sources, see [`TAG_SOURCES_SQL`]. Malformed JSON values count as empty.
|
||||||
};
|
pub struct TagSource {
|
||||||
|
pub id: String,
|
||||||
|
pub tags: Vec<String>,
|
||||||
|
pub types: Vec<String>,
|
||||||
|
pub hub: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads [`TagSource`]s for one page or (`None`) all of them.
|
||||||
|
pub fn tag_sources(
|
||||||
|
conn: &rusqlite::Connection,
|
||||||
|
only: Option<&str>,
|
||||||
|
) -> rusqlite::Result<Vec<TagSource>> {
|
||||||
|
let mut st = conn.prepare_cached(TAG_SOURCES_SQL)?;
|
||||||
|
let rows = st.query_map([only], |r| {
|
||||||
|
let tags: String = r.get(1)?;
|
||||||
|
let types: String = r.get(2)?;
|
||||||
|
Ok(TagSource {
|
||||||
|
id: r.get(0)?,
|
||||||
|
tags: serde_json::from_str(&tags).unwrap_or_default(),
|
||||||
|
types: serde_json::from_str(&types).unwrap_or_default(),
|
||||||
|
hub: r.get(3)?,
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
rows.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TagSource {
|
||||||
|
/// Every tag name: listed tags, the first type and the hub title (one type per page).
|
||||||
|
pub fn names(&self) -> impl Iterator<Item = &String> {
|
||||||
|
self.tags
|
||||||
|
.iter()
|
||||||
|
.chain(self.types.iter().take(1))
|
||||||
|
.chain(self.hub.iter())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn insert_tag_rows(conn: &rusqlite::Connection, sources: &[TagSource]) -> rusqlite::Result<()> {
|
||||||
let mut ins =
|
let mut ins =
|
||||||
conn.prepare("INSERT OR IGNORE INTO page_tags(page_id, tag_key) VALUES (?1, ?2)")?;
|
conn.prepare_cached("INSERT OR IGNORE INTO page_tags(page_id, tag_key) VALUES (?1, ?2)")?;
|
||||||
for (id, tags, types) in rows {
|
for src in sources {
|
||||||
let tags: Vec<String> = serde_json::from_str(&tags).unwrap_or_default();
|
for t in src.names() {
|
||||||
let types: Vec<String> = serde_json::from_str(&types).unwrap_or_default();
|
ins.execute([&src.id, &crate::model::title_key(t)])?;
|
||||||
for t in tags.iter().chain(types.iter().take(1)) {
|
|
||||||
ins.execute([&id, &crate::model::title_key(t)])?;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Rebuilds the `page_tags` index from every page's tags, first type and hub.
|
||||||
|
pub fn rebuild_page_tags(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
|
||||||
|
conn.execute("DELETE FROM page_tags", [])?;
|
||||||
|
insert_tag_rows(conn, &tag_sources(conn, None)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rewrites the `page_tags` rows of one page (derived data: no ops needed).
|
||||||
|
pub fn reindex_page_tags(conn: &rusqlite::Connection, id: &str) -> rusqlite::Result<()> {
|
||||||
|
conn.execute("DELETE FROM page_tags WHERE page_id=?1", [id])?;
|
||||||
|
insert_tag_rows(conn, &tag_sources(conn, Some(id))?)
|
||||||
|
}
|
||||||
|
|
||||||
/// v6: tag pages become notes, tags are sorted and deduplicated, a page keeps one type.
|
/// v6: tag pages become notes, tags are sorted and deduplicated, a page keeps one type.
|
||||||
/// Malformed `tags`/`types` values are repaired to empty lists.
|
/// Malformed `tags`/`types` values are repaired to empty lists.
|
||||||
fn migrate_v6(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
|
fn migrate_v6(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
|
||||||
@@ -219,9 +265,12 @@ pub fn migrate(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
|
|||||||
if version.is_some_and(|v| v < 3) {
|
if version.is_some_and(|v| v < 3) {
|
||||||
rebuild_page_hubs(conn)?;
|
rebuild_page_hubs(conn)?;
|
||||||
}
|
}
|
||||||
// v6 rebuilds `page_tags` too, which also covers the v4 rebuild.
|
// v6 rebuilds `page_tags` too, which covers the v4 and v7 rebuilds.
|
||||||
if version.is_some_and(|v| v < 6) {
|
if version.is_some_and(|v| v < 6) {
|
||||||
migrate_v6(conn)?;
|
migrate_v6(conn)?;
|
||||||
|
} else if version.is_some_and(|v| v < 7) {
|
||||||
|
// v7: a page's hub title is an implicit tag, so the index changes.
|
||||||
|
rebuild_page_tags(conn)?;
|
||||||
}
|
}
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"INSERT OR REPLACE INTO meta(key, value) VALUES ('schema', ?1)",
|
"INSERT OR REPLACE INTO meta(key, value) VALUES ('schema', ?1)",
|
||||||
|
|||||||
@@ -1214,15 +1214,6 @@ impl Graph {
|
|||||||
],
|
],
|
||||||
)?;
|
)?;
|
||||||
let id = p.id.to_string();
|
let id = p.id.to_string();
|
||||||
self.exec("DELETE FROM page_tags WHERE page_id=?1", [&id])?;
|
|
||||||
// The type implies a tag of the same name, so the index covers both (a page has one
|
|
||||||
// type: older replicas may sync more, and only the first counts).
|
|
||||||
for t in tags.iter().chain(p.types.iter().take(1)) {
|
|
||||||
self.exec(
|
|
||||||
"INSERT OR IGNORE INTO page_tags(page_id, tag_key) VALUES (?1, ?2)",
|
|
||||||
params![id, title_key(t)],
|
|
||||||
)?;
|
|
||||||
}
|
|
||||||
self.exec("DELETE FROM page_hubs WHERE page_id=?1", [&id])?;
|
self.exec("DELETE FROM page_hubs WHERE page_id=?1", [&id])?;
|
||||||
// A page belongs to one hub: only the first entry counts (older replicas may sync more).
|
// A page belongs to one hub: only the first entry counts (older replicas may sync more).
|
||||||
for h in p.hubs.iter().take(1) {
|
for h in p.hubs.iter().take(1) {
|
||||||
@@ -1231,6 +1222,25 @@ impl Graph {
|
|||||||
params![id, h.to_string()],
|
params![id, h.to_string()],
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
|
// Tag index: tags, type and direct hub. The hub's title is an implicit tag of its
|
||||||
|
// members, so they are re-indexed too (this page may be a hub, renamed or converted).
|
||||||
|
schema::reindex_page_tags(&self.conn, &id)?;
|
||||||
|
self.reindex_hub_members(&id)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-indexes the tags of every page whose direct hub is `hub`.
|
||||||
|
pub(crate) fn reindex_hub_members(&self, hub: &str) -> Result<()> {
|
||||||
|
let ids: Vec<String> = {
|
||||||
|
let mut st = self
|
||||||
|
.conn
|
||||||
|
.prepare_cached("SELECT page_id FROM page_hubs WHERE hub_id=?1")?;
|
||||||
|
st.query_map([hub], |r| r.get(0))?
|
||||||
|
.collect::<std::result::Result<_, _>>()?
|
||||||
|
};
|
||||||
|
for m in ids {
|
||||||
|
schema::reindex_page_tags(&self.conn, &m)?;
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1267,6 +1277,8 @@ impl Graph {
|
|||||||
// `hubs` and dangle until those pages are rewritten.
|
// `hubs` and dangle until those pages are rewritten.
|
||||||
self.exec("DELETE FROM page_hubs WHERE page_id=?1", [&s])?;
|
self.exec("DELETE FROM page_hubs WHERE page_id=?1", [&s])?;
|
||||||
self.exec("DELETE FROM page_tags WHERE page_id=?1", [&s])?;
|
self.exec("DELETE FROM page_tags WHERE page_id=?1", [&s])?;
|
||||||
|
// Members of a deleted hub lose its implicit tag.
|
||||||
|
self.reindex_hub_members(&s)?;
|
||||||
self.exec(
|
self.exec(
|
||||||
"INSERT OR REPLACE INTO tombstones(id, hlc) VALUES (?1, ?2)",
|
"INSERT OR REPLACE INTO tombstones(id, hlc) VALUES (?1, ?2)",
|
||||||
params![s, hlc],
|
params![s, hlc],
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
|
|
||||||
use crate::error::{Error, Result};
|
use crate::error::{Error, Result};
|
||||||
use crate::model::{Page, PageId, title_key};
|
use crate::model::{Page, PageId, title_key};
|
||||||
|
use crate::schema;
|
||||||
use crate::store::{Graph, parse_id};
|
use crate::store::{Graph, parse_id};
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
|
|
||||||
@@ -113,52 +114,36 @@ impl Graph {
|
|||||||
rows.map(|r| parse_id(&r?)).collect()
|
rows.map(|r| parse_id(&r?)).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tags of every tagged page: the listed ones, then the type if not already among them
|
/// Tags of every tagged page: the listed ones, then the type and the hub title if not
|
||||||
/// (each type implies a tag), names as stored.
|
/// already among them (each implies a tag), names as stored.
|
||||||
pub fn all_page_tags(&self) -> Result<HashMap<PageId, Vec<String>>> {
|
pub fn all_page_tags(&self) -> Result<HashMap<PageId, Vec<String>>> {
|
||||||
let mut st = self.conn().prepare_cached(
|
|
||||||
"SELECT id, tags, types FROM pages WHERE tags != '[]' OR types != '[]'",
|
|
||||||
)?;
|
|
||||||
let rows = st.query_map([], |r| {
|
|
||||||
Ok((
|
|
||||||
r.get::<_, String>(0)?,
|
|
||||||
r.get::<_, String>(1)?,
|
|
||||||
r.get::<_, String>(2)?,
|
|
||||||
))
|
|
||||||
})?;
|
|
||||||
let mut out = HashMap::new();
|
let mut out = HashMap::new();
|
||||||
for row in rows {
|
for src in schema::tag_sources(self.conn(), None)? {
|
||||||
let (id, tags, types) = row?;
|
let mut all: Vec<String> = Vec::new();
|
||||||
let mut all: Vec<String> = serde_json::from_str(&tags).unwrap_or_default();
|
for t in src.names() {
|
||||||
let types: Vec<String> = serde_json::from_str(&types).unwrap_or_default();
|
if !all.iter().any(|x| title_key(x) == title_key(t)) {
|
||||||
for t in types.into_iter().take(1) {
|
all.push(t.clone());
|
||||||
if !all.iter().any(|x| title_key(x) == title_key(&t)) {
|
|
||||||
all.push(t);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
out.insert(parse_id(&id)?, all);
|
if !all.is_empty() {
|
||||||
|
out.insert(parse_id(&src.id)?, all);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Ok(out)
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Every tag in use, listed or implied by a type: spelling of its first page, with its page
|
/// Every tag in use (listed, implied by a type or by the page's hub): spelling of its first
|
||||||
/// count. Most used first, then by name.
|
/// page, with its page count. Most used first, then by name.
|
||||||
pub fn tag_catalog(&self) -> Result<Vec<TagInfo>> {
|
pub fn tag_catalog(&self) -> Result<Vec<TagInfo>> {
|
||||||
let mut st = self.conn().prepare_cached(
|
|
||||||
"SELECT tags, types FROM pages WHERE tags != '[]' OR types != '[]'
|
|
||||||
ORDER BY created_at, id",
|
|
||||||
)?;
|
|
||||||
let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
|
|
||||||
let mut used: HashMap<String, (String, u32)> = HashMap::new();
|
let mut used: HashMap<String, (String, u32)> = HashMap::new();
|
||||||
for row in rows {
|
let mut sources = schema::tag_sources(self.conn(), None)?;
|
||||||
let (tags, types) = row?;
|
sources.sort_by(|a, b| a.id.cmp(&b.id));
|
||||||
let tags: Vec<String> = serde_json::from_str(&tags).unwrap_or_default();
|
for src in sources {
|
||||||
let types: Vec<String> = serde_json::from_str(&types).unwrap_or_default();
|
|
||||||
let mut seen = HashSet::new();
|
let mut seen = HashSet::new();
|
||||||
for t in tags.into_iter().chain(types.into_iter().take(1)) {
|
for t in src.names() {
|
||||||
let key = title_key(&t);
|
let key = title_key(t);
|
||||||
if seen.insert(key.clone()) {
|
if seen.insert(key.clone()) {
|
||||||
used.entry(key).or_insert((t, 0)).1 += 1;
|
used.entry(key).or_insert((t.clone(), 0)).1 += 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -180,7 +165,8 @@ impl Graph {
|
|||||||
|
|
||||||
/// Renames a tag everywhere: in the `tags` and `types` of every page carrying it (one
|
/// 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
|
/// 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.
|
/// `new`, the two merge. 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> {
|
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()))?;
|
let new = normalize_tag(new).ok_or_else(|| Error::Invalid("empty tag name".into()))?;
|
||||||
if new.chars().count() > MAX_TAG_CHARS {
|
if new.chars().count() > MAX_TAG_CHARS {
|
||||||
|
|||||||
@@ -506,7 +506,7 @@ fn old_ops_and_v2_databases_load() {
|
|||||||
r.get(0)
|
r.get(0)
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(schema, "6");
|
assert_eq!(schema, "7");
|
||||||
let p = g.get_page(id).unwrap().unwrap();
|
let p = g.get_page(id).unwrap().unwrap();
|
||||||
assert_eq!((p.kind, p.title.as_str()), (PageKind::Note, "Legacy"));
|
assert_eq!((p.kind, p.title.as_str()), (PageKind::Note, "Legacy"));
|
||||||
let h = g.create_hub("New hub", "").unwrap();
|
let h = g.create_hub("New hub", "").unwrap();
|
||||||
@@ -911,3 +911,88 @@ fn remote_upserts_store_tags_sorted() {
|
|||||||
["alfa", "Beta", "zeta"]
|
["alfa", "Beta", "zeta"]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_direct_hub_is_an_implicit_tag_of_its_members() {
|
||||||
|
let (_d, g) = graph();
|
||||||
|
let anime = hub(&g, "Anime");
|
||||||
|
let media = hub(&g, "Media");
|
||||||
|
g.add_to_hub(anime, media).unwrap();
|
||||||
|
let a = page(&g, "A", &["x"]);
|
||||||
|
let b = page(&g, "B", &["x"]);
|
||||||
|
g.add_to_hub(a, anime).unwrap();
|
||||||
|
g.add_to_hub(b, anime).unwrap();
|
||||||
|
// The hub tag is not stored in `tags`, ancestors do not count, hubs and templates get none.
|
||||||
|
assert!(g.get_page(a).unwrap().unwrap().tags.is_empty());
|
||||||
|
let mut got = g.pages_with_tag("anime").unwrap();
|
||||||
|
got.sort();
|
||||||
|
let mut want = vec![a, b];
|
||||||
|
want.sort();
|
||||||
|
assert_eq!(got, want);
|
||||||
|
assert!(g.pages_with_tag("Media").unwrap().is_empty());
|
||||||
|
let tmpl = g.hub_template(anime).unwrap();
|
||||||
|
assert!(!g.pages_with_tag("Anime").unwrap().contains(&tmpl));
|
||||||
|
assert!(!g.pages_with_tag("Anime").unwrap().contains(&anime));
|
||||||
|
|
||||||
|
// Merges with a same-name type: one tag, the page counted once.
|
||||||
|
g.set_page_type(a, Some("anime")).unwrap();
|
||||||
|
let cat = g.tag_catalog().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
cat.iter()
|
||||||
|
.filter(|t| t.name.to_lowercase() == "anime")
|
||||||
|
.count(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
cat.iter()
|
||||||
|
.find(|t| t.name.to_lowercase() == "anime")
|
||||||
|
.unwrap()
|
||||||
|
.count,
|
||||||
|
2
|
||||||
|
);
|
||||||
|
assert_eq!(g.all_page_tags().unwrap()[&a], ["anime"]);
|
||||||
|
|
||||||
|
// Renaming the hub re-indexes its members without touching them.
|
||||||
|
g.rename_page(anime, "Series").unwrap();
|
||||||
|
assert!(
|
||||||
|
g.pages_with_tag("Anime").unwrap().contains(&a),
|
||||||
|
"type still implies it"
|
||||||
|
);
|
||||||
|
assert!(!g.pages_with_tag("Anime").unwrap().contains(&b));
|
||||||
|
assert!(g.pages_with_tag("Series").unwrap().contains(&b));
|
||||||
|
|
||||||
|
// Moving a page between hubs moves the implicit tag; leaving the hub drops it.
|
||||||
|
g.add_to_hub(b, media).unwrap();
|
||||||
|
assert!(!g.pages_with_tag("Series").unwrap().contains(&b));
|
||||||
|
assert_eq!(g.pages_with_tag("Media").unwrap(), [b]);
|
||||||
|
g.remove_from_hub(b, media).unwrap();
|
||||||
|
assert!(g.pages_with_tag("Media").unwrap().is_empty());
|
||||||
|
|
||||||
|
// rename_tag never renames the hub; only explicit tags and types.
|
||||||
|
g.add_to_hub(b, media).unwrap();
|
||||||
|
assert_eq!(g.rename_tag("Media", "Press").unwrap(), 0);
|
||||||
|
assert_eq!(g.get_page(media).unwrap().unwrap().title, "Media");
|
||||||
|
assert_eq!(g.pages_with_tag("Media").unwrap(), [b]);
|
||||||
|
|
||||||
|
// Deleting the hub removes the tag from its members.
|
||||||
|
g.delete_page(media).unwrap();
|
||||||
|
assert!(g.pages_with_tag("Media").unwrap().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn v6_databases_gain_hub_tags() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let a = {
|
||||||
|
let g = Graph::open(dir.path()).unwrap();
|
||||||
|
let h = hub(&g, "Anime");
|
||||||
|
let a = page(&g, "A", &["x"]);
|
||||||
|
g.add_to_hub(a, h).unwrap();
|
||||||
|
g.conn().execute("DELETE FROM page_tags", []).unwrap();
|
||||||
|
g.conn()
|
||||||
|
.execute("UPDATE meta SET value='6' WHERE key='schema'", [])
|
||||||
|
.unwrap();
|
||||||
|
a
|
||||||
|
};
|
||||||
|
let g = Graph::open(dir.path()).unwrap();
|
||||||
|
assert_eq!(g.pages_with_tag("anime").unwrap(), [a]);
|
||||||
|
}
|
||||||
@@ -473,3 +473,30 @@ fn page_type_and_tag_renaming_round_trip_through_the_api() {
|
|||||||
assert_eq!(g.remove_tag("red".into()).unwrap(), 1);
|
assert_eq!(g.remove_tag("red".into()).unwrap(), 1);
|
||||||
assert!(g.set_page_type(a, None).unwrap().page_type.is_none());
|
assert!(g.set_page_type(a, None).unwrap().page_type.is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hub_members_point_at_one_virtual_tag_node_named_after_the_hub() {
|
||||||
|
let (_d, g) = open();
|
||||||
|
let hub = g.create_hub("Anime".into(), String::new()).unwrap();
|
||||||
|
let (a, _) = page_with(&g, "Naruto", &["x"]);
|
||||||
|
let (b, _) = page_with(&g, "Bleach", &["y"]);
|
||||||
|
g.add_to_hub(a.clone(), hub.id.clone()).unwrap();
|
||||||
|
g.add_to_hub(b.clone(), hub.id.clone()).unwrap();
|
||||||
|
g.set_page_type(b.clone(), Some("anime".into())).unwrap();
|
||||||
|
let data = g.graph_data().unwrap();
|
||||||
|
let tags: Vec<_> = data.nodes.iter().filter(|n| n.is_tag).collect();
|
||||||
|
assert_eq!(tags.len(), 1, "hub tag and same-name type merge");
|
||||||
|
assert_eq!(tags[0].title, "Anime");
|
||||||
|
let target = data.nodes.iter().position(|n| n.is_tag).unwrap() as u32;
|
||||||
|
let mut from: Vec<String> = (0..data.kinds.len())
|
||||||
|
.filter(|&e| data.kinds[e] == edge_kind::TAGGED && data.targets[e] == target)
|
||||||
|
.map(|e| data.nodes[data.sources[e] as usize].title.clone())
|
||||||
|
.collect();
|
||||||
|
from.sort();
|
||||||
|
assert_eq!(from, ["Bleach", "Naruto"]);
|
||||||
|
let cat = g.tag_catalog().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
(cat[0].name.to_lowercase().as_str(), cat[0].count),
|
||||||
|
("anime", 2)
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -140,6 +140,9 @@ Both are plain names with no page, shown as one row of pills under the title.
|
|||||||
several can be added in a row; hovering a chip shows its ×. A chip opens the tag view: pages
|
several can be added in a row; hovering a chip shows its ×. A chip opens the tag view: pages
|
||||||
with that tag or type, "Rename" (also renames types, merging duplicates) and "Remove from all
|
with that tag or type, "Rename" (also renames types, merging duplicates) and "Remove from all
|
||||||
pages". An inline `#tema` in the text still links to a page of that name.
|
pages". An inline `#tema` in the text still links to a page of that name.
|
||||||
|
- **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.
|
||||||
- In the graph every tag is a virtual node drawn as a hollow accent ring and linked to its
|
- 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.
|
pages with a separate edge kind (TAGGED); tapping one opens its tag view.
|
||||||
|
|
||||||
|
|||||||
@@ -37,6 +37,12 @@ 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
|
- **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,
|
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`).
|
Option<&str>)`, `type_catalog` (types in use by count, then the seeded `SUGGESTED_TYPES`).
|
||||||
|
- **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
|
||||||
|
counts (not ancestors); hubs, templates and journals get none. The index is derived, so
|
||||||
|
renaming or deleting a hub, or moving a member, just re-indexes `page_tags` (no ops).
|
||||||
|
`rename_tag` never renames a hub: it only changes explicit tags and types.
|
||||||
- Schema v6 turned former tag pages (kind `tag`) into plain notes and trimmed multiple types to
|
- Schema v6 turned former tag pages (kind `tag`) into plain notes and trimmed multiple types to
|
||||||
the first; `PageKind` has no `Tag` any more and "tag" parses as a note.
|
the first; `PageKind` has no `Tag` any more and "tag" parses as a note.
|
||||||
- In the graph (`synapse-ffi`) every tag in use is a virtual node (`GraphNode.is_tag`, id
|
- In the graph (`synapse-ffi`) every tag in use is a virtual node (`GraphNode.is_tag`, id
|
||||||
|
|||||||
Reference in new issue
Block a user