mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 23:36:20 +00:00
feat(ffi): flutter_rust_bridge API over synapse-core
Opaque SynapseGraph handle (graph behind a mutex) with coarse-grained calls: journals feed, page views, outline editing (insert, update, move, indent, outdent, merge, delete), backlinks, aliases, rename, timeline, related, record_visit, assets and a title/block search stopgap. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fbcfcf678f
commit
305428eaea
10 files changed
+4859
-1
No files matched your search
@@ -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 PageView {
|
||||
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,
|
||||
}
|
||||
@@ -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<PageView>> {
|
||||
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<PageView>> {
|
||||
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<PageView> {
|
||||
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<PageView> {
|
||||
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<PageView>> {
|
||||
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<PageView> {
|
||||
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(PageView {
|
||||
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()
|
||||
}
|
||||
@@ -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;
|
||||
@@ -0,0 +1,157 @@
|
||||
//! 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), its children are moved under `into`, and the block is deleted.
|
||||
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 {
|
||||
g.set_collapsed(target.id, false)?;
|
||||
}
|
||||
for c in children {
|
||||
g.move_block(c, target.page_id, Placement::LastChildOf(Some(target.id)))?;
|
||||
}
|
||||
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),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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<_, _>>()?)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user