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:
dasemuandClaude Opus 5.5 committed 2026-10-21 03:36:32 +02:00
1 parent fbcfcf678f
commit 305428eaea
10 files changed
+4859 -1

No files matched your search

Generated
+516 -1
View File
@@ -2,6 +2,58 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "addr2line"
version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b"
dependencies = [
"gimli",
]
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
[[package]]
name = "allo-isolate"
version = "0.1.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "449e356a4864c017286dbbec0e12767ea07efba29e3b7d984194c2a7ff3c4550"
dependencies = [
"anyhow",
"atomic",
"backtrace",
]
[[package]]
name = "android_log-sys"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84521a3cf562bc62942e294181d9eef17eb38ceb8c68677bc49f144e4c3d4f8d"
[[package]]
name = "android_logger"
version = "0.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbb4e440d04be07da1f1bf44fb4495ebd58669372fe0cffa6e48595ac5bd88a3"
dependencies = [
"android_log-sys",
"env_filter",
"log",
]
[[package]]
name = "android_system_properties"
version = "0.1.6"
@@ -11,18 +63,45 @@ dependencies = [
"libc",
]
[[package]]
name = "anyhow"
version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "arrayvec"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
[[package]]
name = "atomic"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c59bdb34bc650a32731b31bd8f0829cc15d24a708ee31559e0bb34f2bc320cba"
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "backtrace"
version = "0.3.76"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6"
dependencies = [
"addr2line",
"cfg-if",
"libc",
"miniz_oxide",
"object",
"rustc-demangle",
"windows-link",
]
[[package]]
name = "bitflags"
version = "2.13.2"
@@ -42,12 +121,39 @@ dependencies = [
"cpufeatures",
]
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "build-target"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "832133bbabbbaa9fbdba793456a2827627a7d2b8fb96032fa1e7666d7895832b"
[[package]]
name = "bumpalo"
version = "3.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
[[package]]
name = "bytemuck"
version = "1.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
[[package]]
name = "byteorder"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "cc"
version = "1.9.0"
@@ -76,6 +182,16 @@ dependencies = [
"windows-link",
]
[[package]]
name = "console_error_panic_hook"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc"
dependencies = [
"cfg-if",
"wasm-bindgen",
]
[[package]]
name = "constant_time_eq"
version = "0.4.2"
@@ -97,6 +213,69 @@ dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "dart-sys"
version = "4.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57967e4b200d767d091b961d6ab42cc7d0cc14fe9e052e75d0d3cf9eb732d895"
dependencies = [
"cc",
]
[[package]]
name = "dashmap"
version = "5.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856"
dependencies = [
"cfg-if",
"hashbrown 0.14.5",
"lock_api",
"once_cell",
"parking_lot_core",
]
[[package]]
name = "delegate-attr"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a84c9a9c129b98e707ac9a31e204c10c064dd9f949b7da362310ff1a8b137d79"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]]
name = "env_filter"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bf3c259d255ca70051b30e2e95b5446cdb8949ac4cd22c0d7fd634d89f568e2"
dependencies = [
"log",
"regex",
]
[[package]]
name = "errno"
version = "0.3.14"
@@ -131,18 +310,119 @@ version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "flutter_rust_bridge"
version = "2.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24a973d15b8fc7de9fb29cdfbec58a2ac41f6252492d3b882abfdc603e32b34f"
dependencies = [
"allo-isolate",
"android_logger",
"anyhow",
"build-target",
"bytemuck",
"byteorder",
"console_error_panic_hook",
"dart-sys",
"delegate-attr",
"flutter_rust_bridge_macros",
"futures",
"js-sys",
"lazy_static",
"log",
"oslog",
"portable-atomic",
"threadpool",
"tokio",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
]
[[package]]
name = "flutter_rust_bridge_macros"
version = "2.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "901eec2d226107dad1c55b30f7421c4687bebcf70ed43ca44d1b447ca087b238"
dependencies = [
"hex",
"md-5",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "foldhash"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "futures"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3"
dependencies = [
"futures-channel",
"futures-core",
"futures-executor",
"futures-io",
"futures-sink",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-channel"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
dependencies = [
"futures-core",
"futures-sink",
]
[[package]]
name = "futures-core"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
[[package]]
name = "futures-executor"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"
dependencies = [
"futures-core",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-io"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
[[package]]
name = "futures-macro"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "futures-sink"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"
[[package]]
name = "futures-task"
version = "0.3.34"
@@ -155,12 +435,27 @@ version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
dependencies = [
"futures-channel",
"futures-core",
"futures-io",
"futures-macro",
"futures-sink",
"futures-task",
"memchr",
"pin-project-lite",
"slab",
]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "getrandom"
version = "0.4.3"
@@ -172,6 +467,18 @@ dependencies = [
"r-efi",
]
[[package]]
name = "gimli"
version = "0.32.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7"
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
[[package]]
name = "hashbrown"
version = "0.15.5"
@@ -187,9 +494,21 @@ version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1"
dependencies = [
"hashbrown",
"hashbrown 0.15.5",
]
[[package]]
name = "hermit-abi"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "iana-time-zone"
version = "0.1.65"
@@ -231,6 +550,12 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "lazy_static"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
[[package]]
name = "libc"
version = "0.2.191"
@@ -254,18 +579,46 @@ version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "lock_api"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
dependencies = [
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "md-5"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
dependencies = [
"cfg-if",
"digest",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -275,12 +628,55 @@ dependencies = [
"autocfg",
]
[[package]]
name = "num_cpus"
version = "1.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"
dependencies = [
"hermit-abi",
"libc",
]
[[package]]
name = "object"
version = "0.37.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe"
dependencies = [
"memchr",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "oslog"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80d2043d1f61d77cb2f4b1f7b7b2295f40507f5f8e9d1c8bf10a1ca5f97a3969"
dependencies = [
"cc",
"dashmap",
"log",
]
[[package]]
name = "parking_lot_core"
version = "0.9.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-link",
]
[[package]]
name = "pin-project-lite"
version = "0.2.17"
@@ -293,6 +689,12 @@ version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "portable-atomic"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
[[package]]
name = "proc-macro2"
version = "1.0.107"
@@ -317,6 +719,44 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "redox_syscall"
version = "0.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
dependencies = [
"bitflags",
]
[[package]]
name = "regex"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "rusqlite"
version = "0.37.0"
@@ -331,6 +771,12 @@ dependencies = [
"smallvec",
]
[[package]]
name = "rustc-demangle"
version = "0.1.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb"
[[package]]
name = "rustix"
version = "1.1.5"
@@ -350,6 +796,12 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "serde"
version = "1.0.229"
@@ -453,6 +905,18 @@ dependencies = [
"uuid",
]
[[package]]
name = "synapse-ffi"
version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
"flutter_rust_bridge",
"synapse-core",
"tempfile",
"uuid",
]
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -486,6 +950,30 @@ dependencies = [
"syn 3.0.9",
]
[[package]]
name = "threadpool"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d050e60b33d41c19108b32cea32164033a9013fe3b46cbd4457559bfbf77afaa"
dependencies = [
"num_cpus",
]
[[package]]
name = "tokio"
version = "1.54.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0c168a474b95bfecfe908a65d4bdffc523144b649a74c09c286afb35d53e0bc"
dependencies = [
"pin-project-lite",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-ident"
version = "1.0.27"
@@ -511,6 +999,12 @@ version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "wasm-bindgen"
version = "0.2.129"
@@ -524,6 +1018,17 @@ dependencies = [
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e"
dependencies = [
"js-sys",
"tokio",
"wasm-bindgen",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.129"
@@ -556,6 +1061,16 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "web-sys"
version = "0.3.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "windows-core"
version = "0.62.2"
+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)'] }
+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 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,
}
+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<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()
}
+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;
+157
View File
@@ -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),
}
}
})
}
+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;
+174
View File
@@ -0,0 +1,174 @@
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 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());
}