Merge branch 'refs/heads/claude/app-13aee9' into feat/integration

# Conflicts:
#	Cargo.lock
This commit is contained in:
dasemu committed 2026-10-21 14:00:08 +02:00
commit 5f719f5541
151 files changed
+22629 -6

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
[package]
name = "synapse-ffi"
version = "0.1.0"
edition.workspace = true
license.workspace = true
description = "flutter_rust_bridge API over the Synapse core: the only surface the app sees"
[lib]
crate-type = ["cdylib", "staticlib", "rlib"]
[dependencies]
anyhow = "1"
chrono.workspace = true
flutter_rust_bridge = "=2.13.0"
synapse-core.workspace = true
uuid.workspace = true
[dev-dependencies]
tempfile = "3"
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(frb_expand)'] }
+118
View File
@@ -0,0 +1,118 @@
//! Fills a graph with a few weeks of demo journals and pages, through the same API the app
//! uses. `cargo run -p synapse-ffi --example seed -- /path/to/graph`
use synapse_ffi::api::dto::{Place, PlaceKind};
use synapse_ffi::api::graph::SynapseGraph;
fn main() -> anyhow::Result<()> {
let dir = std::env::args()
.nth(1)
.ok_or_else(|| anyhow::anyhow!("usage: seed <graph dir>"))?;
let g = SynapseGraph::open(dir)?;
let today = chrono::NaiveDate::parse_from_str(&g.today(), "%Y-%m-%d")?;
let day = |back: i64| (today - chrono::Duration::days(back)).to_string();
let last = |page: &str, content: &str| {
g.insert_block(
page.to_string(),
Place {
kind: PlaceKind::LastChildOf,
anchor: None,
},
content.to_string(),
)
};
let child = |page: &str, parent: &str, content: &str| {
g.insert_block(
page.to_string(),
Place {
kind: PlaceKind::LastChildOf,
anchor: Some(parent.to_string()),
},
content.to_string(),
)
};
let entries: &[(i64, &[&str])] = &[
(
24,
&[
"Started reading about [[Spreading Activation]] for the related panel",
"TODO sketch the #timeline view",
],
),
(
21,
&[
"Call with Ana about [[Synapse]] sync design",
"#rust ownership notes",
],
),
(
17,
&[
"DONE pick fonts: Inter + Noto Serif",
"Idea: [[Hebbian Learning]] for links",
],
),
(12, &["Weekly review", "Read [[Zettelkasten]] chapter 3"]),
(
8,
&["Drafted [[Outliner Keymap]]", "TODO benchmark tantivy"],
),
(5, &["[[Synapse]] FFI is green", "Lunch with Marta #people"]),
(2, &["Thinking about [[Spreading Activation]] decay rates"]),
(
0,
&[
"## Today",
"TODO review the **editor** key handling",
"Linked [[Synapse]] and [[Zettelkasten]] ideas",
"Code: `cargo test --workspace`",
],
),
];
for (back, lines) in entries {
let j = g.journal(day(*back))?;
let pid = j.page.id.clone();
if !j.blocks.is_empty() {
continue;
}
let mut prev = None;
for l in *lines {
let b = last(&pid, l)?;
prev.get_or_insert(b.id);
}
if *back == 0 {
let first = prev.unwrap();
child(&pid, &first, "Nested notes stay under their parent")?;
}
}
let syn = g.open_page("Synapse".into())?;
if syn.blocks.is_empty() {
let id = syn.page.id;
let a = last(&id, "A native, brain-like second brain")?;
child(&id, &a.id, "Rust core + Flutter UI, no webviews")?;
child(
&id,
&a.id,
"Journals chained in time; pages born in journals",
)?;
last(
&id,
"Related: [[Hebbian Learning]], [[Spreading Activation]]",
)?;
last(&id, "DONE ship the outliner")?;
g.add_alias(id, "Second Brain".into())?;
}
let sa = g.open_page("Spreading Activation".into())?;
if sa.blocks.is_empty() {
last(
&sa.page.id,
"Activate a note, propagate through weighted edges with decay",
)?;
last(&sa.page.id, "Used by the **Related** panel in [[Synapse]]")?;
}
println!("seeded {}", g.dir());
Ok(())
}
+171
View File
@@ -0,0 +1,171 @@
//! Plain data transferred to the UI. Ids are UUID strings and days are `YYYY-MM-DD`, which
//! keeps the generated Dart side free of extra codecs.
use synapse_core::{Block, Page, journal_title};
/// Page header data.
#[derive(Debug, Clone, PartialEq)]
pub struct PageDto {
pub id: String,
pub title: String,
/// Set for journal pages.
pub journal_date: Option<String>,
/// Journal day the page was born in.
pub origin_journal: Option<String>,
pub created_at: i64,
pub updated_at: i64,
}
impl From<&Page> for PageDto {
fn from(p: &Page) -> Self {
Self {
id: p.id.to_string(),
title: p.title.clone(),
journal_date: p.journal_date.map(journal_title),
origin_journal: p.origin_journal.map(journal_title),
created_at: p.created_at,
updated_at: p.updated_at,
}
}
}
/// One row of the outline, in pre-order.
#[derive(Debug, Clone, PartialEq)]
pub struct BlockDto {
pub id: String,
pub parent_id: Option<String>,
pub depth: u32,
pub content: String,
pub collapsed: bool,
pub has_children: bool,
}
impl BlockDto {
pub(crate) fn new(depth: usize, b: &Block, has_children: bool) -> Self {
Self {
id: b.id.to_string(),
parent_id: b.parent_id.map(|p| p.to_string()),
depth: depth as u32,
content: b.content.clone(),
collapsed: b.collapsed,
has_children,
}
}
}
/// Everything the page view needs in one call.
#[derive(Debug, Clone, PartialEq)]
pub struct PageData {
pub page: PageDto,
pub blocks: Vec<BlockDto>,
pub aliases: Vec<String>,
/// Previous/next existing journal (journal pages only).
pub prev_journal: Option<String>,
pub next_journal: Option<String>,
}
/// Where a block goes, relative to `anchor`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlaceKind {
After,
Before,
/// Last child of `anchor`, or last root block when `anchor` is `None`.
LastChildOf,
/// First child of `anchor`, or first root block when `anchor` is `None`.
FirstChildOf,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Place {
pub kind: PlaceKind,
pub anchor: Option<String>,
}
/// Blocks of one page referencing the queried page.
#[derive(Debug, Clone, PartialEq)]
pub struct BacklinkGroup {
pub page_id: String,
pub page_title: String,
pub is_journal: bool,
pub blocks: Vec<BlockDto>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct PageBrief {
pub id: String,
pub title: String,
pub is_journal: bool,
}
impl From<&Page> for PageBrief {
fn from(p: &Page) -> Self {
Self {
id: p.id.to_string(),
title: p.title.clone(),
is_journal: p.is_journal(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct RelatedDto {
pub page: PageBrief,
pub score: f32,
}
/// Target of a `((block ref))`.
#[derive(Debug, Clone, PartialEq)]
pub struct BlockRefDto {
pub id: String,
pub content: String,
pub page_id: String,
pub page_title: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct EditDto {
pub page_id: String,
pub edits: u32,
}
#[derive(Debug, Clone, PartialEq)]
pub struct TimelineDayDto {
pub date: String,
pub journal_id: Option<String>,
/// Pages born on this day.
pub created: Vec<String>,
/// Pages edited on this day.
pub edited: Vec<EditDto>,
}
/// Timeline slice plus the titles of every page it mentions.
#[derive(Debug, Clone, PartialEq)]
pub struct TimelineDto {
pub days: Vec<TimelineDayDto>,
pub pages: Vec<PageBrief>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct AssetDto {
pub hash: String,
pub size: u64,
pub mime: Option<String>,
pub original_name: Option<String>,
}
/// Quick switcher / `[[` autocomplete hit.
#[derive(Debug, Clone, PartialEq)]
pub struct TitleHit {
pub page_id: String,
/// The matched title or alias.
pub title: String,
pub is_alias: bool,
}
/// `((` autocomplete hit.
#[derive(Debug, Clone, PartialEq)]
pub struct BlockHit {
pub id: String,
pub content: String,
pub page_title: String,
}
+336
View File
@@ -0,0 +1,336 @@
//! The graph handle and read-side queries (pages, journals, links, timeline, assets).
use super::dto::*;
use anyhow::{Context, Result, anyhow, bail};
use chrono::NaiveDate;
use flutter_rust_bridge::frb;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::sync::{Mutex, MutexGuard};
use synapse_core::{Graph, NewPage, Page, PageId, journal_title};
use uuid::Uuid;
/// An open graph. Opaque to Dart; every call locks the graph for its duration, so calls are
/// short and coarse-grained. The app serialises writes on its side to keep their order.
pub struct SynapseGraph {
graph: Mutex<Graph>,
}
impl SynapseGraph {
/// Opens (or creates) the graph stored in `dir`.
pub fn open(dir: String) -> Result<SynapseGraph> {
let graph = Graph::open(&dir).with_context(|| format!("opening graph at {dir}"))?;
Ok(SynapseGraph {
graph: Mutex::new(graph),
})
}
pub(crate) fn lock(&self) -> MutexGuard<'_, Graph> {
self.graph.lock().unwrap_or_else(|e| e.into_inner())
}
/// Graph directory.
#[frb(sync)]
pub fn dir(&self) -> String {
self.lock().dir().to_string_lossy().into_owned()
}
/// Today's date (graph clock) as `YYYY-MM-DD`.
#[frb(sync)]
pub fn today(&self) -> String {
journal_title(self.lock().today())
}
// ------------------------------------------------------------- pages
pub fn page(&self, id: String) -> Result<Option<PageData>> {
let g = self.lock();
match g.get_page(parse_id(&id)?)? {
Some(p) => Ok(Some(page_view(&g, &p)?)),
None => Ok(None),
}
}
/// Page by title or alias, without creating it.
pub fn page_by_title(&self, title: String) -> Result<Option<PageData>> {
let g = self.lock();
match g.page_by_title(&title)? {
Some(p) => Ok(Some(page_view(&g, &p)?)),
None => Ok(None),
}
}
/// Page by title or alias, created if missing (following a `[[link]]`). Date titles open
/// the journal of that day.
pub fn open_page(&self, title: String) -> Result<PageData> {
let g = self.lock();
let page = match g.page_by_title(&title)? {
Some(p) => p,
None => match parse_day(&title) {
Some(d) => g.journal(d)?,
None => g.create_page(NewPage::titled(title))?,
},
};
page_view(&g, &page)
}
/// Pages ordered by last update, most recent first.
pub fn list_pages(
&self,
include_journals: bool,
limit: u32,
offset: u32,
) -> Result<Vec<PageDto>> {
let g = self.lock();
Ok(g.list_pages(include_journals, limit, offset)?
.iter()
.map(PageDto::from)
.collect())
}
pub fn rename_page(&self, id: String, new_title: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(&g.rename_page(parse_id(&id)?, &new_title)?))
}
pub fn delete_page(&self, id: String) -> Result<()> {
Ok(self.lock().delete_page(parse_id(&id)?)?)
}
pub fn aliases(&self, page_id: String) -> Result<Vec<String>> {
Ok(self.lock().aliases_of(parse_id(&page_id)?)?)
}
pub fn add_alias(&self, page_id: String, alias: String) -> Result<()> {
let alias = alias.trim();
if alias.is_empty() {
bail!("empty alias");
}
Ok(self.lock().set_alias(alias, Some(parse_id(&page_id)?))?)
}
pub fn remove_alias(&self, alias: String) -> Result<()> {
Ok(self.lock().set_alias(&alias, None)?)
}
// ---------------------------------------------------------- journals
/// The journal of `date` (created if missing).
pub fn journal(&self, date: String) -> Result<PageData> {
let g = self.lock();
let p = g.journal(parse_date(&date)?)?;
page_view(&g, &p)
}
/// Journals feed, newest first. With `before = None` it starts at today (creating today's
/// journal); otherwise at the newest journal strictly before `before`.
pub fn journals(&self, before: Option<String>, limit: u32) -> Result<Vec<PageData>> {
let g = self.lock();
let mut out = Vec::new();
let mut cursor = match before {
None => {
let today = g.today_journal()?;
let date = today.journal_date;
out.push(page_view(&g, &today)?);
date
}
Some(b) => Some(parse_date(&b)?),
};
while (out.len() as u32) < limit {
let Some(d) = cursor else { break };
let Some(prev) = g.journal_neighbors(d)?.prev else {
break;
};
let page = g.journal(prev)?;
out.push(page_view(&g, &page)?);
cursor = Some(prev);
}
Ok(out)
}
pub fn journal_neighbors(&self, date: String) -> Result<(Option<String>, Option<String>)> {
let n = self.lock().journal_neighbors(parse_date(&date)?)?;
Ok((n.prev.map(journal_title), n.next.map(journal_title)))
}
/// Timeline data for `[from, to]` (oldest first) with titles of every page it mentions.
pub fn timeline(&self, from: String, to: String) -> Result<TimelineDto> {
let g = self.lock();
let days = g.timeline(parse_date(&from)?, parse_date(&to)?)?;
let mut ids: BTreeSet<PageId> = BTreeSet::new();
let days = days
.into_iter()
.map(|d| {
ids.extend(d.created.iter().copied());
ids.extend(d.edited.iter().map(|(p, _)| *p));
TimelineDayDto {
date: journal_title(d.date),
journal_id: d.journal.map(|j| j.to_string()),
created: d.created.iter().map(Uuid::to_string).collect(),
edited: d
.edited
.iter()
.map(|(p, n)| EditDto {
page_id: p.to_string(),
edits: *n,
})
.collect(),
}
})
.collect();
let mut pages = Vec::with_capacity(ids.len());
for id in ids {
if let Some(p) = g.get_page(id)? {
pages.push(PageBrief::from(&p));
}
}
Ok(TimelineDto { days, pages })
}
// ------------------------------------------------------------- links
/// Linked references grouped by page (most recently edited first).
pub fn backlinks(&self, page_id: String) -> Result<Vec<BacklinkGroup>> {
let g = self.lock();
let mut groups: Vec<BacklinkGroup> = Vec::new();
let mut index: HashMap<PageId, usize> = HashMap::new();
let mut seen: HashSet<Uuid> = HashSet::new();
for bl in g.backlinks(parse_id(&page_id)?)? {
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
});
groups[i].blocks.push(BlockDto::new(0, &bl.block, false));
}
Ok(groups)
}
/// Notes related to `page_id` by spreading activation.
pub fn related(&self, page_id: String, limit: u32) -> Result<Vec<RelatedDto>> {
let g = self.lock();
let mut out = Vec::new();
for (id, score) in g.related(parse_id(&page_id)?, limit as usize)? {
if let Some(p) = g.get_page(id)? {
out.push(RelatedDto {
page: PageBrief::from(&p),
score,
});
}
}
Ok(out)
}
/// Records navigation between pages (strengthens their synapse).
pub fn record_visit(&self, from: Option<String>, to: String) -> Result<()> {
let from = from.as_deref().map(parse_id).transpose()?;
Ok(self.lock().record_visit(from, parse_id(&to)?)?)
}
/// Target of a `((block ref))`.
pub fn block_ref(&self, id: String) -> Result<Option<BlockRefDto>> {
let g = self.lock();
let Some(b) = g.get_block(parse_id(&id)?)? else {
return Ok(None);
};
let page_title = g.get_page(b.page_id)?.map(|p| p.title).unwrap_or_default();
Ok(Some(BlockRefDto {
id: b.id.to_string(),
content: b.content,
page_id: b.page_id.to_string(),
page_title,
}))
}
// ------------------------------------------------------------ assets
/// Copies a file into the blob store (streamed).
pub fn put_asset_file(&self, path: String, mime: Option<String>) -> Result<AssetDto> {
let a = self
.lock()
.put_asset_file(std::path::Path::new(&path), mime.as_deref())?;
Ok(asset_dto(a))
}
/// Stores in-memory bytes (clipboard, Android content URIs).
pub fn put_asset_bytes(
&self,
bytes: Vec<u8>,
name: Option<String>,
mime: Option<String>,
) -> Result<AssetDto> {
let a = self
.lock()
.put_asset_reader(&bytes[..], name.as_deref(), mime.as_deref())?;
Ok(asset_dto(a))
}
/// Local file path of an asset (for `asset://<hash>` images), if present.
#[frb(sync)]
pub fn asset_path(&self, hash: String) -> Option<String> {
if hash.len() != 64 || !hash.bytes().all(|c| c.is_ascii_hexdigit()) {
return None;
}
let g = self.lock();
g.blobs()
.contains(&hash)
.then(|| g.blobs().path_of(&hash).to_string_lossy().into_owned())
}
}
fn asset_dto(a: synapse_core::Asset) -> AssetDto {
AssetDto {
hash: a.hash,
size: a.size,
mime: a.mime,
original_name: a.original_name,
}
}
pub(crate) fn page_view(g: &Graph, p: &Page) -> Result<PageData> {
let (prev, next) = match p.journal_date {
Some(d) => {
let n = g.journal_neighbors(d)?;
(n.prev.map(journal_title), n.next.map(journal_title))
}
None => (None, None),
};
Ok(PageData {
page: PageDto::from(p),
blocks: outline(g, p.id)?,
aliases: g.aliases_of(p.id)?,
prev_journal: prev,
next_journal: next,
})
}
/// The page outline as UI rows.
pub(crate) fn outline(g: &Graph, page: PageId) -> Result<Vec<BlockDto>> {
let tree = g.page_tree(page)?;
Ok(tree
.iter()
.enumerate()
.map(|(i, (d, b))| {
let has_children = tree.get(i + 1).is_some_and(|(nd, _)| nd > d);
BlockDto::new(*d, b, has_children)
})
.collect())
}
pub(crate) fn parse_id(s: &str) -> Result<Uuid> {
Uuid::parse_str(s).map_err(|e| anyhow!("bad id {s:?}: {e}"))
}
pub(crate) fn parse_date(s: &str) -> Result<NaiveDate> {
parse_day(s).ok_or_else(|| anyhow!("bad date {s:?}, expected YYYY-MM-DD"))
}
fn parse_day(s: &str) -> Option<NaiveDate> {
NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok()
}
+15
View File
@@ -0,0 +1,15 @@
//! Everything under `api` is scanned by `flutter_rust_bridge_codegen` and exposed to Dart.
//!
//! - `graph`: the opaque [`graph::SynapseGraph`] handle and read-side queries.
//! - `outline`: block editing (insert, update, move, indent/outdent, merge, delete).
//! - `search`: title/block lookup (stopgap until `synapse-search` is wired).
//!
//! Extension points for Phase 2 (one module each, methods on `SynapseGraph` or their own
//! opaque handles): `ai` (synapse-ai), `history` (synapse-history), `caldav`
//! (synapse-caldav) and `sync` (synapse-sync client). Add `pub mod <name>;` here, implement it
//! on top of the locked `Graph`, and regenerate the bindings.
pub mod dto;
pub mod graph;
pub mod outline;
pub mod search;
+163
View File
@@ -0,0 +1,163 @@
//! Outliner editing. Structural operations return the page's refreshed outline so the UI can
//! re-sync to the authoritative order after its optimistic update.
//!
//! The core exposes single-block primitives, each in its own transaction; compound edits here
//! (indent, outdent, merge) are sequences of them. See the crate docs for the core helper that
//! would make them atomic.
use super::dto::*;
use super::graph::{SynapseGraph, outline, parse_id};
use anyhow::{Result, bail};
use synapse_core::{Block, BlockId, Graph, PageId, Placement};
impl SynapseGraph {
pub fn insert_block(&self, page_id: String, place: Place, content: String) -> Result<BlockDto> {
let g = self.lock();
let page = parse_id(&page_id)?;
let at = placement(&g, page, &place)?;
let b = g.insert_block(page, at, &content)?;
Ok(BlockDto::new(0, &b, false))
}
/// Replaces a block's Markdown (the debounced save while typing).
pub fn update_block(&self, id: String, content: String) -> Result<()> {
self.lock().update_block(parse_id(&id)?, &content)?;
Ok(())
}
pub fn set_collapsed(&self, id: String, collapsed: bool) -> Result<()> {
Ok(self.lock().set_collapsed(parse_id(&id)?, collapsed)?)
}
/// Deletes a block and its subtree.
pub fn delete_block(&self, id: String) -> Result<Vec<BlockDto>> {
let g = self.lock();
let b = get(&g, parse_id(&id)?)?;
g.delete_block(b.id)?;
outline(&g, b.page_id)
}
/// Moves a block with its subtree (drag and drop), possibly to another page.
pub fn move_block(&self, id: String, page_id: String, place: Place) -> Result<Vec<BlockDto>> {
let g = self.lock();
let page = parse_id(&page_id)?;
let at = placement(&g, page, &place)?;
g.move_block(parse_id(&id)?, page, at)?;
outline(&g, page)
}
/// Tab: the block becomes the last child of its previous sibling (no-op for a first child).
pub fn indent_block(&self, id: String) -> Result<Vec<BlockDto>> {
let g = self.lock();
let b = get(&g, parse_id(&id)?)?;
let sibs = siblings(&g, &b)?;
let i = sibs.iter().position(|s| s.id == b.id).unwrap_or(0);
if i > 0 {
let prev = &sibs[i - 1];
if prev.collapsed {
g.set_collapsed(prev.id, false)?;
}
g.move_block(b.id, b.page_id, Placement::LastChildOf(Some(prev.id)))?;
}
outline(&g, b.page_id)
}
/// Shift-Tab: the block moves right after its parent, adopting its following siblings as
/// children so it keeps its visual place (Logseq's default outdenting).
pub fn outdent_block(&self, id: String) -> Result<Vec<BlockDto>> {
let g = self.lock();
let b = get(&g, parse_id(&id)?)?;
let Some(parent) = b.parent_id else {
return outline(&g, b.page_id);
};
let sibs = siblings(&g, &b)?;
let i = sibs.iter().position(|s| s.id == b.id).unwrap_or(0);
g.move_block(b.id, b.page_id, Placement::After(parent))?;
for s in &sibs[i + 1..] {
g.move_block(s.id, b.page_id, Placement::LastChildOf(Some(b.id)))?;
}
if b.collapsed && i + 1 < sibs.len() {
g.set_collapsed(b.id, false)?;
}
outline(&g, b.page_id)
}
/// Backspace at the start of `id`: its text is appended to `into` (the previous visible
/// block) and the block is deleted. Its children keep their visual place: they take the
/// block's slot when `into` is its parent, otherwise they become last children of `into`.
pub fn merge_block(&self, id: String, into: String) -> Result<Vec<BlockDto>> {
let g = self.lock();
let b = get(&g, parse_id(&id)?)?;
let target = get(&g, parse_id(&into)?)?;
if b.id == target.id {
bail!("cannot merge a block into itself");
}
if !b.content.is_empty() {
g.update_block(target.id, &format!("{}{}", target.content, b.content))?;
}
let children: Vec<BlockId> = g
.page_tree(b.page_id)?
.into_iter()
.filter(|(_, c)| c.parent_id == Some(b.id))
.map(|(_, c)| c.id)
.collect();
if !children.is_empty() && target.collapsed && b.parent_id != Some(target.id) {
g.set_collapsed(target.id, false)?;
}
let at = if b.parent_id == Some(target.id) {
Placement::Before(b.id)
} else {
Placement::LastChildOf(Some(target.id))
};
for c in children {
g.move_block(c, target.page_id, at)?;
}
g.delete_block(b.id)?;
outline(&g, target.page_id)
}
/// Current outline of a page.
pub fn outline(&self, page_id: String) -> Result<Vec<BlockDto>> {
outline(&self.lock(), parse_id(&page_id)?)
}
}
fn get(g: &Graph, id: BlockId) -> Result<Block> {
match g.get_block(id)? {
Some(b) => Ok(b),
None => bail!("block {id} not found"),
}
}
/// Siblings of `b` (including itself) in order.
fn siblings(g: &Graph, b: &Block) -> Result<Vec<Block>> {
Ok(g.page_tree(b.page_id)?
.into_iter()
.filter(|(_, s)| s.parent_id == b.parent_id)
.map(|(_, s)| s)
.collect())
}
fn placement(g: &Graph, page: PageId, place: &Place) -> Result<Placement> {
let anchor = place.anchor.as_deref().map(parse_id).transpose()?;
let need = |a: Option<BlockId>| match a {
Some(a) => Ok(a),
None => Err(anyhow::anyhow!("{:?} needs an anchor block", place.kind)),
};
Ok(match place.kind {
PlaceKind::After => Placement::After(need(anchor)?),
PlaceKind::Before => Placement::Before(need(anchor)?),
PlaceKind::LastChildOf => Placement::LastChildOf(anchor),
PlaceKind::FirstChildOf => {
let first = g
.page_tree(page)?
.into_iter()
.find(|(_, b)| b.parent_id == anchor)
.map(|(_, b)| b.id);
match first {
Some(f) => Placement::Before(f),
None => Placement::LastChildOf(anchor),
}
}
})
}
+94
View File
@@ -0,0 +1,94 @@
//! Search used by the quick switcher and the editor's autocompletes.
//!
//! Extension point: these are simple in-process scans meant to be replaced by
//! `synapse-search` (tantivy full-text + vectors) once it is wired in. Keep the signatures;
//! swap the bodies.
use super::dto::*;
use super::graph::SynapseGraph;
use anyhow::Result;
use synapse_core::title_key;
impl SynapseGraph {
/// Page titles and aliases matching `query`: exact, then prefix, then word-prefix, then
/// substring; shorter titles first within a tier. Empty query returns recent pages.
pub fn search_titles(&self, query: String, limit: u32) -> Result<Vec<TitleHit>> {
let g = self.lock();
let q = title_key(&query);
if q.is_empty() {
return Ok(g
.list_pages(false, limit, 0)?
.iter()
.map(|p| TitleHit {
page_id: p.id.to_string(),
title: p.title.clone(),
is_alias: false,
})
.collect());
}
let mut hits: Vec<(u8, usize, String, synapse_core::PageId)> = g
.all_titles()?
.into_iter()
.filter_map(|(t, id)| {
let k = title_key(&t);
let tier = if k == q {
0
} else if k.starts_with(&q) {
1
} else if k
.match_indices(&q)
.any(|(i, _)| !k[..i].ends_with(|c: char| c.is_alphanumeric()))
{
2
} else if k.contains(&q) {
3
} else {
return None;
};
Some((tier, k.chars().count(), t, id))
})
.collect();
hits.sort_by(|a, b| (a.0, a.1, &a.2).cmp(&(b.0, b.1, &b.2)));
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)?
.is_some_and(|p| title_key(&p.title) != title_key(&title));
out.push(TitleHit {
page_id: id.to_string(),
title,
is_alias,
});
}
Ok(out)
}
/// Blocks whose text contains `query` (for `((` autocomplete), most recent first.
pub fn search_blocks(&self, query: String, limit: u32) -> Result<Vec<BlockHit>> {
let q = query.trim();
if q.is_empty() {
return Ok(Vec::new());
}
let pattern = format!(
"%{}%",
q.replace('\\', "\\\\")
.replace('%', "\\%")
.replace('_', "\\_")
);
let g = self.lock();
// Read-only stopgap over the core tables until synapse-search lands.
let mut st = g.conn().prepare_cached(
"SELECT b.id, b.content, p.title FROM blocks b JOIN pages p ON p.id = b.page_id
WHERE b.content LIKE ?1 ESCAPE '\\' ORDER BY b.updated_at DESC LIMIT ?2",
)?;
let rows = st.query_map((pattern, limit), |r| {
Ok(BlockHit {
id: r.get(0)?,
content: r.get(1)?,
page_title: r.get(2)?,
})
})?;
Ok(rows.collect::<std::result::Result<_, _>>()?)
}
}
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
//! FFI surface of Synapse for the Flutter app (flutter_rust_bridge v2). The app never touches
//! storage directly: everything goes through [`api`]. Bindings are generated from `api` with
//! `cd app && flutter_rust_bridge_codegen generate`.
pub mod api;
#[rustfmt::skip]
mod frb_generated;
+187
View File
@@ -0,0 +1,187 @@
use synapse_ffi::api::dto::{BlockDto, Place, PlaceKind};
use synapse_ffi::api::graph::SynapseGraph;
fn open() -> (tempfile::TempDir, SynapseGraph) {
let dir = tempfile::tempdir().unwrap();
let g = SynapseGraph::open(dir.path().to_string_lossy().into_owned()).unwrap();
(dir, g)
}
fn place(kind: PlaceKind, anchor: Option<&str>) -> Place {
Place {
kind,
anchor: anchor.map(str::to_string),
}
}
/// `(depth, content)` rows for compact assertions.
fn shape(rows: &[BlockDto]) -> Vec<(u32, &str)> {
rows.iter().map(|b| (b.depth, b.content.as_str())).collect()
}
fn page_with(g: &SynapseGraph, title: &str, lines: &[&str]) -> (String, Vec<String>) {
let page = g.open_page(title.into()).unwrap().page.id;
let mut ids = Vec::new();
for l in lines {
let b = g
.insert_block(
page.clone(),
place(PlaceKind::LastChildOf, None),
(*l).into(),
)
.unwrap();
ids.push(b.id);
}
(page, ids)
}
#[test]
fn indent_and_outdent_keep_visual_order() {
let (_d, g) = open();
let (_, ids) = page_with(&g, "P", &["a", "b", "c", "d"]);
g.indent_block(ids[1].clone()).unwrap();
g.indent_block(ids[2].clone()).unwrap();
let rows = g.indent_block(ids[3].clone()).unwrap();
assert_eq!(shape(&rows), vec![(0, "a"), (1, "b"), (1, "c"), (1, "d")]);
assert!(rows[0].has_children);
// Outdenting `c` adopts `d` as its child (Logseq's direct outdenting).
let rows = g.outdent_block(ids[2].clone()).unwrap();
assert_eq!(shape(&rows), vec![(0, "a"), (1, "b"), (0, "c"), (1, "d")]);
// A first child cannot be indented; a root block cannot be outdented.
let rows = g.indent_block(ids[1].clone()).unwrap();
assert_eq!(shape(&rows), vec![(0, "a"), (1, "b"), (0, "c"), (1, "d")]);
let rows = g.outdent_block(ids[0].clone()).unwrap();
assert_eq!(rows.len(), 4);
}
#[test]
fn merge_appends_text_and_adopts_children() {
let (_d, g) = open();
let (page, ids) = page_with(&g, "P", &["hello ", "world", "x"]);
g.indent_block(ids[2].clone()).unwrap();
let rows = g.merge_block(ids[1].clone(), ids[0].clone()).unwrap();
assert_eq!(shape(&rows), vec![(0, "hello world"), (1, "x")]);
assert_eq!(g.outline(page).unwrap().len(), 2);
}
#[test]
fn merging_a_first_child_into_its_parent_keeps_grandchildren_in_place() {
let (_d, g) = open();
let (_, ids) = page_with(&g, "P", &["p", "c", "gc", "s"]);
g.indent_block(ids[1].clone()).unwrap();
g.indent_block(ids[2].clone()).unwrap();
g.indent_block(ids[2].clone()).unwrap();
g.indent_block(ids[3].clone()).unwrap();
// p > c > gc, p > s
let rows = g.merge_block(ids[1].clone(), ids[0].clone()).unwrap();
assert_eq!(shape(&rows), vec![(0, "pc"), (1, "gc"), (1, "s")]);
}
#[test]
fn insert_first_child_and_move() {
let (_d, g) = open();
let (page, ids) = page_with(&g, "P", &["a", "b"]);
g.insert_block(
page.clone(),
place(PlaceKind::FirstChildOf, Some(&ids[0])),
"a1".into(),
)
.unwrap();
g.insert_block(
page.clone(),
place(PlaceKind::FirstChildOf, Some(&ids[0])),
"a0".into(),
)
.unwrap();
let rows = g
.move_block(
ids[1].clone(),
page,
place(PlaceKind::Before, Some(&ids[0])),
)
.unwrap();
assert_eq!(shape(&rows), vec![(0, "b"), (0, "a"), (1, "a0"), (1, "a1")]);
}
#[test]
fn journals_feed_starts_today_and_walks_back() {
let (_d, g) = open();
for d in ["2024-01-01", "2024-01-03", "2024-02-10"] {
g.journal(d.into()).unwrap();
}
let feed = g.journals(None, 3).unwrap();
assert_eq!(
feed[0].page.journal_date.as_deref(),
Some(g.today().as_str())
);
assert_eq!(feed[1].page.title, "2024-02-10");
assert_eq!(feed[2].page.title, "2024-01-03");
assert_eq!(feed[2].prev_journal.as_deref(), Some("2024-01-01"));
let more = g.journals(Some("2024-01-03".into()), 10).unwrap();
assert_eq!(more.len(), 1);
assert_eq!(more[0].page.title, "2024-01-01");
}
#[test]
fn links_backlinks_search_and_timeline() {
let (_d, g) = open();
let j = g.journal(g.today()).unwrap();
let jb = g
.insert_block(
j.page.id.clone(),
place(PlaceKind::LastChildOf, None),
"met [[Rust Lang]] and #ideas".into(),
)
.unwrap();
let rust = g.page_by_title("rust lang".into()).unwrap().unwrap();
assert_eq!(
rust.page.origin_journal.as_deref(),
Some(g.today().as_str())
);
let groups = g.backlinks(rust.page.id.clone()).unwrap();
assert_eq!(groups.len(), 1);
assert!(groups[0].is_journal);
assert_eq!(groups[0].blocks[0].id, jb.id);
g.add_alias(rust.page.id.clone(), "Ferris".into()).unwrap();
let hits = g.search_titles("fer".into(), 10).unwrap();
assert_eq!(hits[0].page_id, rust.page.id);
assert!(hits[0].is_alias);
let hits = g.search_titles("lang".into(), 10).unwrap();
assert_eq!(hits[0].title, "Rust Lang");
let blocks = g.search_blocks("#ideas".into(), 10).unwrap();
assert_eq!(blocks.len(), 1);
assert!(g.search_blocks("100%".into(), 10).unwrap().is_empty());
let r = g.block_ref(jb.id.clone()).unwrap().unwrap();
assert_eq!(r.page_title, g.today());
let t = g.timeline(g.today(), g.today()).unwrap();
assert_eq!(t.days.len(), 1);
assert!(t.days[0].created.contains(&rust.page.id));
assert!(t.pages.iter().any(|p| p.title == "ideas"));
g.record_visit(Some(j.page.id.clone()), rust.page.id.clone())
.unwrap();
let related = g.related(j.page.id, 5).unwrap();
assert!(related.iter().any(|r| r.page.id == rust.page.id));
}
#[test]
fn assets_round_trip() {
let (_d, g) = open();
let a = g
.put_asset_bytes(
b"png".to_vec(),
Some("x.png".into()),
Some("image/png".into()),
)
.unwrap();
let path = g.asset_path(a.hash.clone()).unwrap();
assert_eq!(std::fs::read(path).unwrap(), b"png");
assert!(g.asset_path("zz".into()).is_none());
}