Merge pull request #2 from Dasemu/feat/hubs-tags-themes

feat: hubs, tag pages, types, themes and key bindings
This commit is contained in:
dasemu authored and GitHub committed 2026-10-26 02:48:30 +01:00
commit 78c3c48ceb
71 files changed
+13420 -522

No files matched your search

+2 -2
View File
@@ -5,7 +5,7 @@ plugins {
}
android {
namespace = "es.zenvairo.synapse"
namespace = "dev.dasemu.synapse"
compileSdk = flutter.compileSdkVersion
ndkVersion = flutter.ndkVersion
@@ -16,7 +16,7 @@ android {
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId = "es.zenvairo.synapse"
applicationId = "dev.dasemu.synapse"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = flutter.minSdkVersion
@@ -1,4 +1,4 @@
package es.zenvairo.synapse
package dev.dasemu.synapse
import io.flutter.embedding.android.FlutterActivity
+1 -7
View File
@@ -100,13 +100,7 @@ void main() {
}
await shot(tester, 'app-network');
for (final mode in [
'Local',
'Synapses',
'Clusters',
'Namespaces',
'Timeline',
]) {
for (final mode in ['Synapses', 'Clusters', 'Tree', 'Timeline']) {
await tester.tap(find.text(mode).last);
await wait(tester, const Duration(seconds: 3));
expect(tester.takeException(), isNull);
+7 -1
View File
@@ -8,6 +8,7 @@ import 'src/app.dart';
import 'src/backend/graph_backend.dart';
import 'src/editor/block_row.dart' as editor;
import 'src/rust/frb_generated.dart';
import 'src/state/settings.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
@@ -20,5 +21,10 @@ Future<void> main() async {
Platform.environment['SYNAPSE_GRAPH'] ??
'${(await getApplicationSupportDirectory()).path}${Platform.pathSeparator}graph';
final backend = await FfiGraphBackend.open(dir);
runApp(SynapseApp(backend: backend));
runApp(
SynapseApp(
backend: backend,
settings: FileSettings('$dir${Platform.pathSeparator}app-settings.json'),
),
);
}
+25 -10
View File
@@ -2,19 +2,24 @@ import 'package:flutter/material.dart';
import 'backend/graph_backend.dart';
import 'state/app_state.dart';
import 'state/settings.dart';
import 'theme/theme.dart';
import 'views/shell.dart';
class SynapseApp extends StatefulWidget {
const SynapseApp({super.key, required this.backend});
const SynapseApp({super.key, required this.backend, this.settings});
final GraphBackend backend;
final SettingsStore? settings;
@override
State<SynapseApp> createState() => _SynapseAppState();
}
class _SynapseAppState extends State<SynapseApp> {
late final AppState _state = AppState(widget.backend)..loadRecent();
late final AppState _state = AppState(
widget.backend,
settings: widget.settings,
)..loadRecent();
@override
void dispose() {
@@ -28,14 +33,24 @@ class _SynapseAppState extends State<SynapseApp> {
state: _state,
child: ListenableBuilder(
listenable: _state,
builder: (context, _) => MaterialApp(
title: 'Synapse',
debugShowCheckedModeBanner: false,
theme: buildTheme(Brightness.light),
darkTheme: buildTheme(Brightness.dark),
themeMode: _state.themeMode,
home: const Shell(),
),
builder: (context, _) {
final t = themeById(_state.themeId);
final built = t == null
? null
: buildTheme(t.brightness, colors: t.colors);
return MaterialApp(
title: 'Synapse',
debugShowCheckedModeBanner: false,
theme: built ?? buildTheme(Brightness.light),
darkTheme: built ?? buildTheme(Brightness.dark),
themeMode: t == null
? ThemeMode.system
: (t.brightness == Brightness.dark
? ThemeMode.dark
: ThemeMode.light),
home: const Shell(),
);
},
),
);
}
+135 -3
View File
@@ -11,6 +11,9 @@ export '../rust/api/dto.dart';
/// in-memory implementation. Keeping the UI on this interface (instead of the generated
/// opaque class) is what makes the editor testable without the native library.
abstract class GraphBackend {
/// Name of the notes store (shown at the centre of the tree view).
String get graphName;
/// Today's date in the graph clock, `YYYY-MM-DD`.
String today();
@@ -54,6 +57,52 @@ abstract class GraphBackend {
String? assetPath(String hash);
Future<AssetDto> putAssetFile(String path, {String? mime});
/// Hub (folder) structure of the whole graph.
Future<HubsDto> hubs();
Future<PageStructure> pageStructure(String pageId);
Future<PageDto> createHub(String title, String description);
/// Tags are pages of kind `tag` (topics); a page can have any number. Types are plain
/// names saying what a page is.
Future<PageDto> setPageTags(String pageId, List<String> tags);
Future<PageDto> addPageTag(String pageId, String tag);
Future<PageDto> removePageTag(String pageId, String tag);
Future<PageDto> setPageTypes(String pageId, List<String> types);
Future<PageDto> addPageType(String pageId, String type);
Future<PageDto> removePageType(String pageId, String type);
/// Types in use (most used first), then the seeded suggestions not used yet.
Future<List<TagDto>> typeCatalog();
/// Tag pages, most used first.
Future<List<TagDto>> tagCatalog();
Future<List<PageBrief>> pagesWithTag(String tag);
/// Id of the hub's template page (opens like a note; may be empty).
Future<String> hubTemplate(String hubId);
/// Creates a note in the hub, starting from a copy of the hub's template.
Future<PageDto> createPageFromTemplate(String hubId, String title);
Future<PageDto> setHubDescription(String hubId, String description);
/// Membership is stored on the member: it lists the hub among its parents.
Future<void> addToHub(String pageId, String hubId);
Future<void> removeFromHub(String pageId, String hubId);
Future<HubPreviewDto> hubConversionPreview(String pageId);
Future<PageDto> convertToHub(
String pageId,
String title,
String description,
List<String> memberIds, {
String? keepOutlineAs,
});
Future<PageDto> convertToNote(String pageId);
/// Logseq leftovers that can be removed, and their removal. Returns the number deleted.
Future<List<LegacyCandidate>> legacyCandidates();
Future<int> purgePages(List<String> ids);
/// The whole page-level graph (cached by the core until the graph changes).
Future<GraphData> graphData();
@@ -89,12 +138,20 @@ class _FfiLayout implements LayoutEngine {
}
class FfiGraphBackend implements GraphBackend {
FfiGraphBackend(this._g);
FfiGraphBackend(this._g, this.graphName);
final SynapseGraph _g;
static Future<FfiGraphBackend> open(String dir) async =>
FfiGraphBackend(await SynapseGraph.open(dir: dir));
@override
final String graphName;
static Future<FfiGraphBackend> open(String dir) async {
final parts = dir.split(RegExp(r'[\\/]')).where((p) => p.isNotEmpty);
return FfiGraphBackend(
await SynapseGraph.open(dir: dir),
parts.isEmpty ? 'Graph' : parts.last,
);
}
@override
String today() => _g.today();
@@ -183,6 +240,81 @@ class FfiGraphBackend implements GraphBackend {
Future<AssetDto> putAssetFile(String path, {String? mime}) =>
_g.putAssetFile(path: path, mime: mime);
@override
Future<HubsDto> hubs() => _g.hubs();
@override
Future<PageStructure> pageStructure(String pageId) =>
_g.pageStructure(pageId: pageId);
@override
Future<PageDto> setPageTags(String pageId, List<String> tags) =>
_g.setPageTags(pageId: pageId, tags: tags);
@override
Future<PageDto> addPageTag(String pageId, String tag) =>
_g.addPageTag(pageId: pageId, tag: tag);
@override
Future<PageDto> removePageTag(String pageId, String tag) =>
_g.removePageTag(pageId: pageId, tag: tag);
@override
Future<PageDto> setPageTypes(String pageId, List<String> types) =>
_g.setPageTypes(pageId: pageId, types: types);
@override
Future<PageDto> addPageType(String pageId, String type) =>
_g.addPageType(pageId: pageId, ty: type);
@override
Future<PageDto> removePageType(String pageId, String type) =>
_g.removePageType(pageId: pageId, ty: type);
@override
Future<List<TagDto>> typeCatalog() => _g.typeCatalog();
@override
Future<List<TagDto>> tagCatalog() => _g.tagCatalog();
@override
Future<List<PageBrief>> pagesWithTag(String tag) => _g.pagesWithTag(tag: tag);
@override
Future<String> hubTemplate(String hubId) => _g.hubTemplate(hubId: hubId);
@override
Future<PageDto> createPageFromTemplate(String hubId, String title) =>
_g.createPageFromTemplate(hubId: hubId, title: title);
@override
Future<PageDto> createHub(String title, String description) =>
_g.createHub(title: title, description: description);
@override
Future<PageDto> setHubDescription(String hubId, String description) =>
_g.setHubDescription(hubId: hubId, description: description);
@override
Future<void> addToHub(String pageId, String hubId) =>
_g.addToHub(pageId: pageId, hubId: hubId);
@override
Future<void> removeFromHub(String pageId, String hubId) =>
_g.removeFromHub(pageId: pageId, hubId: hubId);
@override
Future<HubPreviewDto> hubConversionPreview(String pageId) =>
_g.hubConversionPreview(pageId: pageId);
@override
Future<PageDto> convertToHub(
String pageId,
String title,
String description,
List<String> memberIds, {
String? keepOutlineAs,
}) => _g.convertToHub(
pageId: pageId,
title: title,
description: description,
memberIds: memberIds,
keepOutlineAs: keepOutlineAs,
);
@override
Future<PageDto> convertToNote(String pageId) =>
_g.convertToNote(pageId: pageId);
@override
Future<List<LegacyCandidate>> legacyCandidates() => _g.legacyCandidates();
@override
Future<int> purgePages(List<String> ids) => _g.purgePages(ids: ids);
@override
Future<GraphData> graphData() => _g.graphData();
+42
View File
@@ -6,6 +6,7 @@ import 'package:flutter/services.dart';
import '../backend/graph_backend.dart';
import '../state/app_state.dart';
import '../state/keymap.dart';
import '../state/outline_controller.dart';
import '../state/outline_ops.dart';
import '../theme/theme.dart';
@@ -512,6 +513,12 @@ class _BlockEditorState extends State<BlockEditor> {
final seq = ++_searchSeq;
final backend = c.backend;
Future<List<CompletionItem>> search() async {
if (q.kind == CompletionKind.command) {
return [
for (final cmd in matchCommands(q.query))
CompletionItem('/${cmd.name}', cmd.name, detail: cmd.label),
];
}
if (q.kind == CompletionKind.block) {
final hits = await backend.searchBlocks(q.query, limit: 8);
return [
@@ -564,10 +571,35 @@ class _BlockEditorState extends State<BlockEditor> {
final q = _query;
if (q == null || i >= _items.length) return;
final v = applyCompletion(_text.text, q, _items[i]);
final again =
q.kind == CompletionKind.command &&
slashCommands.firstWhere((c) => c.name == _items[i].value).then;
_closeCompletion();
_text.value = v;
_last = v;
c.setText(n, v.text);
// `/link` leaves the caret inside `[[]]`: go straight on to the page picker.
if (again) _updateCompletion();
}
/// Applies an editor formatting shortcut to the selection; false if `a` is not one.
bool _format(AppAction a) {
final (open, close) = switch (a) {
AppAction.bold => ('**', '**'),
AppAction.italic => ('*', '*'),
AppAction.strike => ('~~', '~~'),
AppAction.highlight => ('==', '=='),
AppAction.code => ('`', '`'),
AppAction.link => ('[[', ']]'),
_ => ('', ''),
};
if (open.isEmpty) return false;
final v = wrapSelection(_text.value, open, close);
_text.value = v;
_last = v;
c.setText(n, v.text);
_updateCompletion();
return true;
}
// -------------------------------------------------------------- keys
@@ -619,6 +651,14 @@ class _BlockEditorState extends State<BlockEditor> {
final caret = sel.isValid ? sel.extentOffset : _text.text.length;
final len = _text.text.length;
if (ctrl || alt) {
final bound = AppScope.read(context).keymap.actionFor(
Combo(key, ctrl: ctrl, shift: shift, alt: alt),
editor: true,
);
if (bound != null && _format(bound)) return KeyEventResult.handled;
}
if (_completing) {
if (key == LogicalKeyboardKey.arrowDown) {
setState(() => _selected = (_selected + 1) % _items.length);
@@ -842,6 +882,8 @@ class CompletionPopup extends StatelessWidget {
? Icons.add_rounded
: kind == CompletionKind.block
? Icons.notes_rounded
: kind == CompletionKind.command
? Icons.bolt_rounded
: kind == CompletionKind.tag
? Icons.tag_rounded
: Icons.description_outlined,
+139 -2
View File
@@ -1,8 +1,8 @@
import 'package:flutter/services.dart';
enum CompletionKind { page, tag, block }
enum CompletionKind { page, tag, block, command }
/// An autocomplete trigger under the caret: `[[query`, `#query` or `((query`.
/// An autocomplete trigger under the caret: `[[query`, `#query`, `((query` or `/query`.
class CompletionQuery {
const CompletionQuery(this.kind, this.start, this.query);
@@ -39,6 +39,121 @@ class CompletionItem {
bool _ws(String c) => c.trim().isEmpty;
/// A `/command`. `insert` is the text it produces; `|` marks where the caret lands (end of
/// the text when absent). `then` re-opens autocomplete afterwards (the link commands).
class SlashCommand {
const SlashCommand(
this.name,
this.label,
this.insert, {
this.keywords = '',
this.then = false,
});
final String name;
final String label;
final String insert;
final String keywords;
final bool then;
/// Today's date as a journal title, for `/today`.
static String today() {
final d = DateTime.now();
String two(int n) => n.toString().padLeft(2, '0');
return '${d.year}-${two(d.month)}-${two(d.day)}';
}
String text() => insert.replaceAll('{today}', today());
}
const slashCommands = [
SlashCommand(
'link',
'Link to a page',
'[[|]]',
keywords: 'page wiki',
then: true,
),
SlashCommand(
'ref',
'Reference a block',
'((|))',
keywords: 'block',
then: true,
),
SlashCommand('url', 'Web link', '[|](https://)', keywords: 'http markdown'),
SlashCommand('image', 'Image', '![|](https://)', keywords: 'picture img'),
SlashCommand('bold', 'Bold', '**|**', keywords: 'strong'),
SlashCommand('italic', 'Italic', '*|*', keywords: 'emphasis'),
SlashCommand('strike', 'Strikethrough', '~~|~~', keywords: 'delete'),
SlashCommand('highlight', 'Highlight', '==|==', keywords: 'mark'),
SlashCommand('code', 'Inline code', '`|`', keywords: 'mono'),
SlashCommand('codeblock', 'Code block', '```\n|\n```', keywords: 'fence'),
SlashCommand('h1', 'Heading 1', '# |', keywords: 'title'),
SlashCommand('h2', 'Heading 2', '## |', keywords: 'title'),
SlashCommand('h3', 'Heading 3', '### |', keywords: 'title'),
SlashCommand('todo', 'Task', 'TODO |', keywords: 'task checkbox'),
SlashCommand('quote', 'Quote', '> |', keywords: 'blockquote'),
SlashCommand('divider', 'Divider', '---', keywords: 'rule line hr'),
SlashCommand(
'today',
"Link to today's journal",
'[[{today}]]',
keywords: 'date',
),
SlashCommand('tag', 'Tag', '#|', keywords: 'hashtag', then: true),
];
/// Commands matching `query` (name prefix first, then name/label/keyword substrings).
List<SlashCommand> matchCommands(String query, {int limit = 8}) {
final q = query.toLowerCase();
final starts = <SlashCommand>[];
final rest = <SlashCommand>[];
for (final c in slashCommands) {
if (c.name.startsWith(q)) {
starts.add(c);
} else if ('${c.label} ${c.keywords}'.toLowerCase().contains(q)) {
rest.add(c);
}
}
return [...starts, ...rest].take(limit).toList();
}
/// Wraps the selection in `open`/`close` (or inserts the pair with the caret between). If the
/// selection is already wrapped, unwraps it.
TextEditingValue wrapSelection(TextEditingValue v, String open, String close) {
final sel = v.selection;
if (!sel.isValid) return v;
final t = v.text;
final inner = t.substring(sel.start, sel.end);
if (!sel.isCollapsed &&
sel.start >= open.length &&
sel.end + close.length <= t.length &&
t.substring(sel.start - open.length, sel.start) == open &&
t.substring(sel.end, sel.end + close.length) == close) {
return TextEditingValue(
text:
t.substring(0, sel.start - open.length) +
inner +
t.substring(sel.end + close.length),
selection: TextSelection(
baseOffset: sel.start - open.length,
extentOffset: sel.end - open.length,
),
);
}
final text =
t.substring(0, sel.start) + open + inner + close + t.substring(sel.end);
return TextEditingValue(
text: text,
selection: sel.isCollapsed
? TextSelection.collapsed(offset: sel.start + open.length)
: TextSelection(
baseOffset: sel.start + open.length,
extentOffset: sel.end + open.length,
),
);
}
/// Finds the autocomplete trigger that the caret is in, if any.
CompletionQuery? detectCompletion(String text, int caret) {
if (caret < 0 || caret > text.length) return null;
@@ -69,6 +184,15 @@ CompletionQuery? detectCompletion(String text, int caret) {
),
);
}
final slash = before.lastIndexOf('/');
if (slash >= 0 && (slash == 0 || _ws(before[slash - 1]))) {
final q = before.substring(slash + 1);
if (!q.contains(RegExp(r'\s'))) {
consider(
CompletionQuery(CompletionKind.command, lineStart + slash + 1, q),
);
}
}
final hash = before.lastIndexOf('#');
if (hash >= 0 && (hash == 0 || _ws(before[hash - 1]))) {
final q = before.substring(hash + 1);
@@ -98,6 +222,19 @@ TextEditingValue applyCompletion(
final head = text.substring(0, q.start);
var tail = text.substring(end);
switch (q.kind) {
case CompletionKind.command:
final cmd = slashCommands.firstWhere((c) => c.name == item.value);
final body = cmd.text();
final at = body.indexOf('|');
final clean = body.replaceFirst('|', '');
// `head` still ends with the `/`.
final before = head.substring(0, head.length - 1);
return TextEditingValue(
text: before + clean + tail,
selection: TextSelection.collapsed(
offset: before.length + (at < 0 ? clean.length : at),
),
);
case CompletionKind.page:
if (tail.startsWith(']]')) tail = tail.substring(2);
final t = '$head${item.value}]]';
+10
View File
@@ -86,6 +86,9 @@ class BlockRefDtoLike {
final String pageId;
}
/// Characters a backslash can escape in a block (Markdown's ASCII punctuation).
const escapable = r'\\`*_{}[]()#+-.!~=|<>:"';
final _marker = RegExp(r'^(TODO|DOING|NOW|LATER|DONE|CANCELED|CANCELLED) ');
final _heading = RegExp(r'^(#{1,6}) ');
final _uuid = RegExp(
@@ -245,6 +248,13 @@ class BlockRenderer {
while (i < s.length) {
final c = s[i];
// Backslash escape: `\*` shows a literal `*` and hides the backslash.
if (c == r'\' && i + 1 < s.length && escapable.contains(s[i + 1])) {
flush(i);
_text(s[i + 1], off + i + 1, style);
i = plain = i + 2;
continue;
}
// `code`
if (c == '`') {
final j = s.indexOf('`', i + 1);
+123 -2
View File
@@ -11,7 +11,9 @@ enum EdgeKind {
blockRef('Block ref'),
embed('Embed'),
mention('Mention'),
synapse('Synapse');
synapse('Synapse'),
contains('Contains'),
tagged('Shared tag');
const EdgeKind(this.label);
final String label;
@@ -51,6 +53,123 @@ class GraphModel {
bool isJournal(int i) => node(i).journalDate != null;
bool isHub(int i) => node(i).isHub;
/// Whether the graph has any hub (folder-like page).
late final bool hasHubs = data.nodes.any((n) => n.isHub);
/// Hubs that are the home hub of the most pages first (journals excluded); ties by index.
/// A hub's position here is its colour rank in the hub grouping.
late final List<int> hubOrder = () {
final count = <int, int>{};
for (var i = 0; i < nodeCount; i++) {
final h = node(i).homeHub;
if (h != null && !isJournal(i)) count[h] = (count[h] ?? 0) + 1;
}
return count.keys.toList()..sort((a, b) {
final c = count[b]!.compareTo(count[a]!);
return c != 0 ? c : a.compareTo(b);
});
}();
/// Hub node index → colour rank (see [hubOrder]).
late final Map<int, int> hubRank = {
for (var r = 0; r < hubOrder.length; r++) hubOrder[r]: r,
};
/// Members of each hub: the targets of its `CONTAINS` edges (hub -> member), in edge order.
late final Map<int, Set<int>> hubMembers = () {
final m = <int, Set<int>>{};
for (var e = 0; e < edgeCount; e++) {
if (kind(e) != EdgeKind.contains) continue;
final hub = source(e), page = target(e);
if (hub == page) continue;
(m[hub] ??= <int>{}).add(page);
}
return m;
}();
/// Layout-only springs from every page in `nodes` to its home hub, so folders cluster.
List<(int, int, double)> hubSprings(
Iterable<int> nodes, {
double strength = 0.6,
}) => [
for (final i in nodes)
if (node(i).homeHub case final h? when h != i) (i, h, strength),
];
/// The tag that groups page `i` in the "by tags" clusters: the page's most widely used tag
/// (ties: alphabetical). Keys are lower-case; journals and untagged pages have none.
String? homeTag(int i) {
if (isJournal(i)) return null;
String? best;
for (final t in node(i).tags) {
final k = t.toLowerCase();
if (best == null ||
_tagUse[k]! > _tagUse[best]! ||
(_tagUse[k] == _tagUse[best] && k.compareTo(best) < 0)) {
best = k;
}
}
return best;
}
/// Pages per tag key and the first spelling met, over every non-journal page.
late final Map<String, int> _tagUse = () {
final m = <String, int>{};
for (var i = 0; i < nodeCount; i++) {
if (isJournal(i)) continue;
for (final t in node(i).tags) {
final k = t.toLowerCase();
m[k] = (m[k] ?? 0) + 1;
_tagName.putIfAbsent(k, () => t);
}
}
return m;
}();
final _tagName = <String, String>{};
/// Tag keys that are the home tag of the most pages first; a tag's position is its colour
/// rank in the tag grouping.
late final List<String> tagGroups = () {
final count = <String, int>{};
for (var i = 0; i < nodeCount; i++) {
final t = homeTag(i);
if (t != null) count[t] = (count[t] ?? 0) + 1;
}
return count.keys.toList()..sort((a, b) {
final c = count[b]!.compareTo(count[a]!);
return c != 0 ? c : a.compareTo(b);
});
}();
late final Map<String, int> tagGroupRank = {
for (var r = 0; r < tagGroups.length; r++) tagGroups[r]: r,
};
/// Display name of a tag key.
String tagLabel(String key) => _tagName[key] ?? key;
/// Layout-only springs from every page in `nodes` to the best connected page of its home
/// tag, so pages sharing a tag cluster spatially.
List<(int, int, double)> tagSprings(
Iterable<int> nodes, {
double strength = 0.6,
}) {
final anchor = <String, int>{};
for (final i in nodes) {
final t = homeTag(i);
if (t == null) continue;
final a = anchor[t];
if (a == null || node(i).degree > node(a).degree) anchor[t] = i;
}
return [
for (final i in nodes)
if (homeTag(i) case final t? when anchor[t] != i)
(i, anchor[t]!, strength),
];
}
/// Tag pages actually used as tags, most used first.
late final List<int> tags = () {
final count = <int, int>{};
@@ -112,7 +231,7 @@ class GraphModel {
/// Filters of the network modes.
class GraphFilter {
const GraphFilter({
this.journals = false,
this.journals = true,
this.orphans = true,
this.minDegree = 0,
this.tag,
@@ -126,6 +245,8 @@ class GraphFilter {
EdgeKind.blockRef,
EdgeKind.embed,
EdgeKind.mention,
EdgeKind.contains,
EdgeKind.tagged,
},
});
+143 -11
View File
@@ -10,7 +10,7 @@ import '../state/app_state.dart';
import '../theme/theme.dart';
import 'graph_model.dart';
enum ColorBy { cluster, tag, none }
enum ColorBy { cluster, tag, hub, tagGroup, none }
/// Calm categorical palette (cluster / tag colours), tuned for each theme.
List<Color> graphPalette(Brightness b) => b == Brightness.light
@@ -119,6 +119,7 @@ class NetworkCanvasState extends State<NetworkCanvas>
// Reused point buffers (no per-frame allocation or boxing).
final _edgeBufs = <EdgeKind, _Buf>{};
final _nodeBufs = <(int, int), _Buf>{};
final _hubBufs = <int, _Buf>{};
Float32List _meshPos = Float32List(0);
Int32List _meshCol = Int32List(0);
double _startScale = 1;
@@ -189,6 +190,8 @@ class NetworkCanvasState extends State<NetworkCanvas>
3.0,
22.0,
);
// Hubs are a little larger; the painter adds a ring around them.
if (n.isHub) _radius[k] = _radius[k] * 1.2 + 1.5;
_colorIndex[k] = switch (widget.colorBy) {
ColorBy.cluster => n.cluster < 10 ? n.cluster : -1,
ColorBy.tag =>
@@ -198,6 +201,18 @@ class NetworkCanvasState extends State<NetworkCanvas>
final i = g.tags.indexOf(n.primaryTag!);
return i < 10 ? i : -1;
})(),
ColorBy.hub =>
n.homeHub == null
? -1
: (() {
final r = g.hubRank[n.homeHub!] ?? -1;
return r < 10 ? r : -1;
})(),
ColorBy.tagGroup => (() {
final t = g.homeTag(sub.nodes[k]);
final r = t == null ? -1 : (g.tagGroupRank[t] ?? -1);
return r < 10 ? r : -1;
})(),
ColorBy.none => -1,
};
}
@@ -451,6 +466,8 @@ class _NetworkPainter extends CustomPainter {
/// Laid-out labels per subgraph, invalidated when the text colour changes.
static final _labels = Expando<(Color, Map<int, TextPainter>)>();
static final _hullLabels = Expando<(Color, Map<int, TextPainter>)>();
static const _ringWidth = 1.6;
Color _edgeColor(EdgeKind k) => switch (k) {
EdgeKind.link => colors.muted,
@@ -460,6 +477,8 @@ class _NetworkPainter extends CustomPainter {
EdgeKind.embed => colors.ref,
EdgeKind.mention => colors.faint,
EdgeKind.synapse => palette[3],
EdgeKind.contains => colors.ink,
EdgeKind.tagged => palette[1],
};
@override
@@ -494,7 +513,9 @@ class _NetworkPainter extends CustomPainter {
canvas.scale(scale);
// Cluster hulls.
if (s.widget.hulls) _hulls(canvas, sub, pos, scale);
final hullLabels = s.widget.hulls
? _hulls(canvas, sub, pos, scale)
: const <_HullLabel>[];
// Edges, batched by kind.
final pulse = s._pulse.value;
@@ -585,15 +606,35 @@ class _NetworkPainter extends CustomPainter {
b.n = 0;
}
final journalColor = colors.faint;
for (final b in s._hubBufs.values) {
b.n = 0;
}
for (var k = 0; k < sub.length; k++) {
if (!visible(k)) continue;
final r = brain == null
? s._radius[k]
: 3 + 9 * (brain.activation[sub.nodes[k]] ?? 0);
if (g.isHub(sub.nodes[k])) {
s._hubBufs
.putIfAbsent(((r + _ringWidth) * 2).round(), _Buf.new)
.add2(pos[2 * k], pos[2 * k + 1]);
}
final ci = g.isJournal(sub.nodes[k]) ? -2 : s._colorIndex[k];
final key = (ci, (r * 2).round());
buckets.putIfAbsent(key, _Buf.new).add2(pos[2 * k], pos[2 * k + 1]);
}
// Hub rings: a slightly larger disc under the node (one call per size bucket).
for (final MapEntry(key: d2, value: pts) in s._hubBufs.entries) {
if (pts.n == 0) continue;
canvas.drawRawPoints(
ui.PointMode.points,
pts.view,
Paint()
..color = colors.ink.withValues(alpha: dim ? 0.2 : 0.8)
..strokeWidth = d2.toDouble()
..strokeCap = StrokeCap.round,
);
}
for (final MapEntry(key: (ci, d2), value: pts) in buckets.entries) {
if (pts.n == 0) continue;
var c = ci == -2 ? journalColor : (ci < 0 ? colors.muted : palette[ci]);
@@ -656,6 +697,7 @@ class _NetworkPainter extends CustomPainter {
}
canvas.restore();
_paintHullLabels(canvas, size, sub, hullLabels);
_paintLabels(canvas, size, sub, pos, highlight, focusLocal);
}
@@ -748,18 +790,39 @@ class _NetworkPainter extends CustomPainter {
}
}
void _hulls(Canvas canvas, SubGraph sub, Float32List pos, double scale) {
final byCluster = <int, List<Offset>>{};
/// Draws the soft hulls (by hub when colouring by hub, else by community) and returns
/// the labels to draw on screen afterwards.
List<_HullLabel> _hulls(
Canvas canvas,
SubGraph sub,
Float32List pos,
double scale,
) {
final g = sub.model;
final by = state.widget.colorBy;
final byHub = by == ColorBy.hub;
final byTag = by == ColorBy.tagGroup;
final groups = <int, List<Offset>>{};
for (var k = 0; k < sub.length; k++) {
final c = sub.model.node(sub.nodes[k]).cluster;
if (c >= 10) continue;
byCluster
.putIfAbsent(c, () => [])
.add(Offset(pos[2 * k], pos[2 * k + 1]));
final n = g.node(sub.nodes[k]);
final int c;
if (byHub) {
final h = n.homeHub;
c = h == null ? -1 : (g.hubRank[h] ?? -1);
} else if (byTag) {
final t = g.homeTag(sub.nodes[k]);
c = t == null ? -1 : (g.tagGroupRank[t] ?? -1);
} else {
c = n.cluster;
}
if (c < 0 || c >= 10) continue;
groups.putIfAbsent(c, () => []).add(Offset(pos[2 * k], pos[2 * k + 1]));
}
for (final MapEntry(key: c, value: pts) in byCluster.entries) {
final labels = <_HullLabel>[];
for (final MapEntry(key: c, value: pts) in groups.entries) {
if (pts.length < 3) continue;
final hull = convexHull(corePoints(pts));
final core = corePoints(pts);
final hull = convexHull(core);
if (hull.length < 3) continue;
final path = Path()..addPolygon(hull, true);
final color = palette[c];
@@ -777,6 +840,65 @@ class _NetworkPainter extends CustomPainter {
..strokeWidth = 28 / scale
..strokeJoin = StrokeJoin.round,
);
if (byHub || byTag) {
var cx = 0.0, cy = 0.0, x0 = double.infinity, x1 = -double.infinity;
for (final p in core) {
cx += p.dx;
cy += p.dy;
x0 = math.min(x0, p.dx);
x1 = math.max(x1, p.dx);
}
labels.add(
_HullLabel(
c,
byHub ? g.node(g.hubOrder[c]).title : g.tagLabel(g.tagGroups[c]),
Offset(cx / core.length, cy / core.length),
(x1 - x0) * scale,
),
);
}
}
return labels;
}
/// Hub titles at the hull centroids, only when the hull is wide enough on screen.
void _paintHullLabels(
Canvas canvas,
Size size,
SubGraph sub,
List<_HullLabel> labels,
) {
if (labels.isEmpty) return;
final s = state;
var entry = _hullLabels[sub];
if (entry == null || entry.$1 != colors.muted) {
entry = _hullLabels[sub] = (colors.muted, <int, TextPainter>{});
}
for (final l in labels) {
if (l.screenWidth < 90) continue;
final at = l.center * s._scale + s._offset;
if (at.dx < -100 ||
at.dy < -30 ||
at.dx > size.width + 100 ||
at.dy > size.height + 30) {
continue;
}
final tp = entry.$2[l.group] ??= TextPainter(
text: TextSpan(
text: l.title,
style: TextStyle(
fontFamily: uiFont,
fontSize: 13,
fontWeight: FontWeight.w600,
color: colors.muted,
),
),
textDirection: TextDirection.ltr,
maxLines: 1,
ellipsis: '…',
textScaler: textScaler,
)..layout(maxWidth: 200);
tp.paint(canvas, at - Offset(tp.width / 2, tp.height / 2));
}
}
@@ -813,6 +935,7 @@ class _NetworkPainter extends CustomPainter {
k == focus ||
(brainAct != null && brainAct > 0.15) ||
screenR >= (compact ? 7 : (sub.length > 200 ? 8.5 : 5.5)) ||
(!compact && sub.model.isHub(sub.nodes[k]) && screenR >= 5) ||
(sub.length <= 40 && !compact)) {
candidates.add(k);
}
@@ -885,6 +1008,15 @@ class _NetworkPainter extends CustomPainter {
old.colors != colors || !identical(old.state, state);
}
/// A hub title to draw at a hull centroid (world position, screen width of the hull).
class _HullLabel {
const _HullLabel(this.group, this.title, this.center, this.screenWidth);
final int group;
final String title;
final Offset center;
final double screenWidth;
}
/// Growable float buffer reused across frames.
class _Buf {
Float32List data = Float32List(256);
+270 -77
View File
@@ -4,13 +4,15 @@ import 'package:flutter/material.dart';
import '../theme/theme.dart';
import 'graph_model.dart';
import 'network_canvas.dart';
/// A node of the namespace / tag tree.
/// A node of the hub / namespace / tag tree.
class TreeItem {
TreeItem(this.label, {this.global});
TreeItem(this.label, {this.global, this.isHub = false});
final String label;
/// Drawn with the folder look.
final bool isHub;
/// Page index when the item is a page.
int? global;
final children = <TreeItem>[];
@@ -19,6 +21,12 @@ class TreeItem {
double angle = 0;
Offset pos = Offset.zero;
/// Colour-space position: centre hue (degrees) of this branch's sector and its width.
/// Siblings split their parent's sector evenly, so they are equally far apart in hue.
double hue = 0;
double span = 360;
int sibling = 0;
TreeItem child(String label) {
for (final c in children) {
if (c.label == label) return c;
@@ -29,14 +37,75 @@ class TreeItem {
}
}
/// Builds a tree with two branches: namespaces (`a/b/c` titles split on `/`) and tags (each
/// tag with the pages using it, most used tags first).
/// Hub branches: root hubs (hubs that are no other hub's member) with their members,
/// recursively, plus the notes that live in no hub (orphans included). A hub is expanded once (the first time it is reached) and never inside
/// itself, so cycles and shared sub-hubs stay bounded; later occurrences are leaves.
List<TreeItem> _hubBranches(GraphModel g, int maxPerHub, int maxLoose) {
final branches = <TreeItem>[];
final members = g.hubMembers;
final nested = {for (final m in members.values) ...m};
final expanded = <int>{};
TreeItem build(int hub) {
final item = TreeItem(g.node(hub).title, global: hub, isHub: true);
if (!expanded.add(hub)) return item;
var shown = 0;
final all = members[hub] ?? const <int>{};
// Sub-hubs are always listed; plain pages are capped.
for (final m in all) {
if (g.isHub(m)) {
item.children.add(build(m));
} else if (shown < maxPerHub) {
shown++;
item.children.add(TreeItem(g.node(m).title, global: m));
}
}
final hidden = all.where((m) => !g.isHub(m)).length - shown;
if (hidden > 0) item.children.add(TreeItem('… $hidden more'));
return item;
}
final hubs = [
for (var i = 0; i < g.nodeCount; i++)
if (g.isHub(i)) i,
];
for (final h in hubs) {
if (!nested.contains(h)) branches.add(build(h));
}
// Hubs only reachable through a cycle still need a place.
for (final h in hubs) {
if (!expanded.contains(h)) branches.add(build(h));
}
// Notes under no container hang straight off the centre (namespaced ones keep their
// namespace branch).
final loose = [
for (var i = 0; i < g.nodeCount; i++)
if (!g.isHub(i) &&
!g.isJournal(i) &&
!nested.contains(i) &&
!g.node(i).title.contains('/'))
i,
];
for (final i in loose.take(maxLoose)) {
branches.add(TreeItem(g.node(i).title, global: i));
}
if (loose.length > maxLoose) {
branches.add(TreeItem('… ${loose.length - maxLoose} more'));
}
return branches;
}
/// Builds a tree from hubs (folders, straight off the centre, with loose notes), namespaces (`a/b/c` titles split on `/`, attached
/// directly to the centre) and tags (each tag with the pages using it, most used tags first).
TreeItem buildNamespaceTree(
GraphModel g, {
String name = 'Graph',
int maxTags = 24,
int maxPerTag = 30,
int maxPerHub = 40,
int maxLoose = 80,
}) {
final root = TreeItem('Graph');
final root = TreeItem(name);
root.children.addAll(_hubBranches(g, maxPerHub, maxLoose));
final ns = TreeItem('Namespaces');
final byTitle = <String, int>{};
for (var i = 0; i < g.nodeCount; i++) {
@@ -53,7 +122,8 @@ TreeItem buildNamespaceTree(
at.global ??= byTitle[path];
}
}
if (ns.children.isNotEmpty) root.children.add(ns);
// No "Namespaces" node: top-level namespaces hang straight off the centre.
root.children.addAll(ns.children);
final tags = TreeItem('Tags');
for (final tag in g.tags.take(maxTags)) {
final item = TreeItem('#${g.node(tag).title}', global: tag);
@@ -68,11 +138,32 @@ TreeItem buildNamespaceTree(
tags.children.add(item);
}
if (tags.children.isNotEmpty) root.children.add(tags);
// With a single branch, that branch is the centre.
final top = root.children.length == 1 ? root.children.single : root;
_measure(top, 0);
_place(top, 0, 2 * math.pi);
return top;
_measure(root, 0);
_place(root, 0, 2 * math.pi);
_colorize(root);
return root;
}
/// Gives every arm of `t` its own sector of the hue circle (the centre's arms share it all),
/// and every sub-branch an equal slice of its parent's sector.
void _colorize(TreeItem t) {
final k = t.children.length;
for (var j = 0; j < k; j++) {
final c = t.children[j];
c.span = t.span / k;
c.hue = t.hue - t.span / 2 + (j + 0.5) * c.span;
c.sibling = j;
_colorize(c);
}
}
/// Branch colour: hue from the sector, alternating lightness so neighbours stay apart even
/// when the slices get thin.
Color treeColor(TreeItem t, Brightness b) {
final dark = b == Brightness.dark;
final l =
(dark ? 0.66 : 0.48) + (t.sibling.isOdd ? (dark ? -0.08 : 0.08) : 0);
return HSLColor.fromAHSL(1, (t.hue % 360 + 360) % 360, 0.62, l).toColor();
}
int _measure(TreeItem t, int depth) {
@@ -98,6 +189,16 @@ void _place(TreeItem t, double a0, double a1) {
}
}
void _shift(TreeItem t, Offset d) {
for (final x in _walk(t)) {
x.pos += d;
}
}
class _Tick extends ChangeNotifier {
void bump() => notifyListeners();
}
Iterable<TreeItem> _walk(TreeItem t) sync* {
yield t;
for (final c in t.children) {
@@ -105,10 +206,18 @@ Iterable<TreeItem> _walk(TreeItem t) sync* {
}
}
/// Radial tree of namespaces and tags; pan/zoom with the GPU transform (no repaint).
/// Radial tree of hubs, namespaces and tags; pan/zoom with the GPU transform (no repaint).
class TreeCanvas extends StatefulWidget {
const TreeCanvas({super.key, required this.model, required this.onTap});
const TreeCanvas({
super.key,
required this.model,
required this.onTap,
this.name = 'Graph',
});
final GraphModel model;
/// Label of the centre: the name of the notes store.
final String name;
final void Function(int global) onTap;
@override
@@ -116,21 +225,26 @@ class TreeCanvas extends StatefulWidget {
}
class _TreeCanvasState extends State<TreeCanvas> {
late TreeItem _root = buildNamespaceTree(widget.model);
late TreeItem _root = buildNamespaceTree(widget.model, name: widget.name);
final _tick = _Tick();
TreeItem? _drag;
bool _pan = true;
final _transform = TransformationController();
bool _placed = false;
@override
void didUpdateWidget(TreeCanvas oldWidget) {
super.didUpdateWidget(oldWidget);
if (!identical(oldWidget.model, widget.model)) {
_root = buildNamespaceTree(widget.model);
if (!identical(oldWidget.model, widget.model) ||
oldWidget.name != widget.name) {
_root = buildNamespaceTree(widget.model, name: widget.name);
}
}
@override
void dispose() {
_transform.dispose();
_tick.dispose();
super.dispose();
}
@@ -139,18 +253,36 @@ class _TreeCanvasState extends State<TreeCanvas> {
return maxDepth * _ring + 170;
}
/// Nodes can be dragged away from the rings, so the scene is larger than the layout.
double get _half => _extent * 1.6;
TreeItem? _hit(Offset scene, double half) {
final p = scene - Offset(half, half);
TreeItem? best;
var d = 12.0;
for (final t in _walk(_root)) {
final x = (t.pos - p).distance;
if (x < d) {
d = x;
best = t;
}
}
return best;
}
@override
Widget build(BuildContext context) {
final colors = context.colors;
if (_root.children.isEmpty) {
return Center(
child: Text(
'No namespaces (a/b titles) or tags yet.',
'No hubs, namespaces (a/b titles) or tags yet.',
style: TextStyle(color: colors.muted),
),
);
}
final extent = _extent;
final half = _half;
return LayoutBuilder(
builder: (context, box) {
if (!_placed) {
@@ -161,8 +293,8 @@ class _TreeCanvasState extends State<TreeCanvas> {
);
_transform.value = Matrix4.identity()
..translateByDouble(
box.maxWidth / 2 - extent * s,
box.maxHeight / 2 - extent * s,
box.maxWidth / 2 - half * s,
box.maxHeight / 2 - half * s,
0,
1,
)
@@ -171,26 +303,41 @@ class _TreeCanvasState extends State<TreeCanvas> {
return InteractiveViewer(
transformationController: _transform,
constrained: false,
panEnabled: _pan,
minScale: 0.05,
maxScale: 6,
boundaryMargin: const EdgeInsets.all(double.infinity),
child: GestureDetector(
onTapUp: (d) {
final p = d.localPosition - Offset(extent, extent);
for (final t in _walk(_root)) {
if (t.global != null && (t.pos - p).distance < 10) {
widget.onTap(t.global!);
return;
}
child: Listener(
// Dragging a node moves it with its whole branch; empty space pans the view.
onPointerDown: (e) {
final t = _hit(e.localPosition, half);
if (t != null) {
_drag = t;
setState(() => _pan = false);
}
},
child: CustomPaint(
size: Size(2 * extent, 2 * extent),
painter: _TreePainter(
_root,
extent,
colors,
graphPalette(Theme.of(context).brightness),
onPointerMove: (e) {
final t = _drag;
if (t == null) return;
_shift(t, e.delta / _transform.value.getMaxScaleOnAxis());
_tick.bump();
},
onPointerUp: (_) => _release(),
onPointerCancel: (_) => _release(),
child: GestureDetector(
onTapUp: (d) {
final t = _hit(d.localPosition, half);
if (t?.global != null) widget.onTap(t!.global!);
},
child: CustomPaint(
size: Size(2 * half, 2 * half),
painter: _TreePainter(
_root,
half,
colors,
Theme.of(context).brightness,
_tick,
),
),
),
),
@@ -198,29 +345,38 @@ class _TreeCanvasState extends State<TreeCanvas> {
},
);
}
void _release() {
if (_drag == null) return;
_drag = null;
setState(() => _pan = true);
}
}
class _TreePainter extends CustomPainter {
_TreePainter(this.root, this.extent, this.colors, this.palette);
_TreePainter(
this.root,
this.extent,
this.colors,
this.brightness,
Listenable tick,
) : super(repaint: tick);
final TreeItem root;
final double extent;
final SynapseColors colors;
final List<Color> palette;
final Brightness brightness;
@override
void paint(Canvas canvas, Size size) {
canvas.translate(extent, extent);
final link = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 1.2
..color = colors.line;
..strokeWidth = 1.4;
for (final t in _walk(root)) {
for (final c in t.children) {
// Curve from parent to child bending through the child's angle.
final mid = Offset.fromDirection(
c.angle,
t.depth * _ring + _ring * 0.5,
);
// Curve from parent to child bending through the child's ray.
final mid = c.pos - Offset.fromDirection(c.angle, _ring * 0.5);
link.color = treeColor(c, brightness).withValues(alpha: 0.7);
canvas.drawPath(
Path()
..moveTo(t.pos.dx, t.pos.dy)
@@ -229,43 +385,80 @@ class _TreePainter extends CustomPainter {
);
}
}
var branch = 0;
// Colour per first-level branch; with a single-branch tree each subtree gets its own.
for (final b in root.children) {
final color = palette[branch++ % palette.length];
for (final t in _walk(b)) {
final r = t.children.isEmpty ? 3.5 : 5.5;
canvas.drawCircle(
t.pos,
r,
Paint()..color = t.global == null ? colors.faint : color,
);
final tp = TextPainter(
text: TextSpan(
text: t.label,
style: TextStyle(
fontFamily: uiFont,
fontSize: t.children.isEmpty ? 11 : 12.5,
fontWeight: t.children.isEmpty
? FontWeight.w400
: FontWeight.w600,
color: t.children.isEmpty ? colors.muted : colors.ink,
),
),
textDirection: TextDirection.ltr,
maxLines: 1,
ellipsis: '…',
)..layout(maxWidth: 150);
// Labels outside the circle, left of the node on the left half.
final left = math.cos(t.angle) < 0;
final at = t.pos + Offset(left ? -tp.width - 8 : 8, -tp.height / 2);
tp.paint(canvas, at);
void node(TreeItem t, Color color) {
final r = t.children.isEmpty ? 3.5 : 5.5;
final fill = Paint()
..color = t.global == null ? color.withValues(alpha: 0.55) : color;
if (t.isHub) {
_folder(canvas, t.pos, fill);
} else {
canvas.drawCircle(t.pos, r, fill);
}
final tp = TextPainter(
text: TextSpan(
text: t.label,
style: TextStyle(
fontFamily: uiFont,
fontSize: t.children.isEmpty ? 11 : 12.5,
fontWeight: t.children.isEmpty ? FontWeight.w400 : FontWeight.w600,
color: t.children.isEmpty ? colors.muted : colors.ink,
),
),
textDirection: TextDirection.ltr,
maxLines: 1,
ellipsis: '…',
)..layout(maxWidth: 150);
// Labels outside the circle, left of the node on the left half.
final left = math.cos(t.angle) < 0;
tp.paint(
canvas,
t.pos + Offset(left ? -tp.width - 8 : 8, -tp.height / 2),
);
}
canvas.drawCircle(Offset.zero, 7, Paint()..color = colors.accent);
for (final t in _walk(root).skip(1)) {
node(t, treeColor(t, brightness));
}
// The centre carries the name of the notes store.
final c = TextPainter(
text: TextSpan(
text: root.label,
style: TextStyle(
fontFamily: uiFont,
fontSize: 14,
fontWeight: FontWeight.w700,
color: colors.ink,
),
),
textDirection: TextDirection.ltr,
maxLines: 1,
ellipsis: '…',
)..layout(maxWidth: 180);
c.paint(canvas, root.pos + Offset(-c.width / 2, -c.height - 12));
canvas.drawCircle(root.pos, 7, Paint()..color = colors.accent);
}
/// Small folder glyph (body plus tab) centred on `c`.
void _folder(Canvas canvas, Offset c, Paint paint) {
canvas.drawRRect(
RRect.fromRectAndRadius(
Rect.fromCenter(center: c.translate(0, 1), width: 13, height: 9),
const Radius.circular(2),
),
paint,
);
canvas.drawRRect(
RRect.fromRectAndRadius(
Rect.fromLTWH(c.dx - 6.5, c.dy - 5, 6, 3),
const Radius.circular(1.2),
),
paint,
);
}
@override
bool shouldRepaint(_TreePainter old) =>
!identical(old.root, root) || old.colors != colors;
!identical(old.root, root) ||
old.colors != colors ||
old.brightness != brightness;
}
+310 -8
View File
@@ -8,7 +8,7 @@ import '../frb_generated.dart';
import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart';
// These functions are ignored because they are not marked as `pub`: `new`
// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `assert_fields_are_eq`, `assert_fields_are_eq`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `from`
// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `assert_fields_are_eq`, `assert_fields_are_eq`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `from`
class AssetDto {
final String hash;
@@ -236,7 +236,8 @@ class GraphNode {
final String? originJournal;
final PlatformInt64 createdAt;
/// Distinct neighbours over structural edges (links, tags, properties, block refs).
/// Distinct neighbours over structural edges (links, tags, properties, block refs, hub
/// membership).
final int degree;
/// Distinct pages referencing this one.
@@ -248,6 +249,15 @@ class GraphNode {
/// Node index of the tag this page uses most, if any.
final int? primaryTag;
/// The page is a hub (`PageKind::Hub`).
final bool isHub;
/// Node index of the deepest hub containing this page (a hub: itself).
final int? homeHub;
/// Tag names of the page (see `PageDto::tags`), for grouping by tag.
final List<String> tags;
const GraphNode({
required this.id,
required this.title,
@@ -258,6 +268,9 @@ class GraphNode {
required this.backlinks,
required this.cluster,
this.primaryTag,
required this.isHub,
this.homeHub,
required this.tags,
});
@override
@@ -270,7 +283,10 @@ class GraphNode {
degree.hashCode ^
backlinks.hashCode ^
cluster.hashCode ^
primaryTag.hashCode;
primaryTag.hashCode ^
isHub.hashCode ^
homeHub.hashCode ^
tags.hashCode;
@override
bool operator ==(Object other) =>
@@ -285,7 +301,127 @@ class GraphNode {
degree == other.degree &&
backlinks == other.backlinks &&
cluster == other.cluster &&
primaryTag == other.primaryTag;
primaryTag == other.primaryTag &&
isHub == other.isHub &&
homeHub == other.homeHub &&
tags == other.tags;
}
/// A hub (folder-like page) with its members.
class HubDto {
final String id;
final String title;
final String description;
/// 0 for root hubs, one more per level of nesting.
final int depth;
/// Sub-hubs first, then notes, each by title.
final List<PageBrief> members;
/// Ids of the members that are hubs themselves.
final List<String> subHubs;
const HubDto({
required this.id,
required this.title,
required this.description,
required this.depth,
required this.members,
required this.subHubs,
});
@override
int get hashCode =>
id.hashCode ^
title.hashCode ^
description.hashCode ^
depth.hashCode ^
members.hashCode ^
subHubs.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is HubDto &&
runtimeType == other.runtimeType &&
id == other.id &&
title == other.title &&
description == other.description &&
depth == other.depth &&
members == other.members &&
subHubs == other.subHubs;
}
/// Defaults for the "convert to hub" dialog.
class HubPreviewDto {
/// Last namespace segment of the title.
final String suggestedTitle;
/// First prose block as plain text (<= 280 chars).
final String suggestedDescription;
/// Candidate members: pages the outline links or tags (outline order), then pages
/// referencing the note from properties or tags.
final List<PageBrief> members;
/// Blocks that are prose rather than links (what "keep the outline" would save).
final int proseBlocks;
final int blocks;
/// `"<suggested_title> (notes)"`, for the note receiving the outline.
final String suggestedNoteTitle;
const HubPreviewDto({
required this.suggestedTitle,
required this.suggestedDescription,
required this.members,
required this.proseBlocks,
required this.blocks,
required this.suggestedNoteTitle,
});
@override
int get hashCode =>
suggestedTitle.hashCode ^
suggestedDescription.hashCode ^
members.hashCode ^
proseBlocks.hashCode ^
blocks.hashCode ^
suggestedNoteTitle.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is HubPreviewDto &&
runtimeType == other.runtimeType &&
suggestedTitle == other.suggestedTitle &&
suggestedDescription == other.suggestedDescription &&
members == other.members &&
proseBlocks == other.proseBlocks &&
blocks == other.blocks &&
suggestedNoteTitle == other.suggestedNoteTitle;
}
class HubsDto {
/// Sorted by title.
final List<HubDto> hubs;
/// Ids of the hubs that are not a member of any hub, by title.
final List<String> roots;
const HubsDto({required this.hubs, required this.roots});
@override
int get hashCode => hubs.hashCode ^ roots.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is HubsDto &&
runtimeType == other.runtimeType &&
hubs == other.hubs &&
roots == other.roots;
}
/// One batch of layout iterations.
@@ -310,19 +446,77 @@ class LayoutFrame {
alpha == other.alpha;
}
/// A page the legacy purge offers to delete.
class LegacyCandidate {
final String id;
final String title;
final String reason;
final int blocks;
final bool preselected;
const LegacyCandidate({
required this.id,
required this.title,
required this.reason,
required this.blocks,
required this.preselected,
});
@override
int get hashCode =>
id.hashCode ^
title.hashCode ^
reason.hashCode ^
blocks.hashCode ^
preselected.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is LegacyCandidate &&
runtimeType == other.runtimeType &&
id == other.id &&
title == other.title &&
reason == other.reason &&
blocks == other.blocks &&
preselected == other.preselected;
}
/// A level of a namespace (`A/B` under `A`); `id` is `None` when only deeper pages exist.
class NamespaceEntry {
final String title;
final String? id;
const NamespaceEntry({required this.title, this.id});
@override
int get hashCode => title.hashCode ^ id.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is NamespaceEntry &&
runtimeType == other.runtimeType &&
title == other.title &&
id == other.id;
}
class PageBrief {
final String id;
final String title;
final bool isJournal;
final bool isHub;
const PageBrief({
required this.id,
required this.title,
required this.isJournal,
required this.isHub,
});
@override
int get hashCode => id.hashCode ^ title.hashCode ^ isJournal.hashCode;
int get hashCode =>
id.hashCode ^ title.hashCode ^ isJournal.hashCode ^ isHub.hashCode;
@override
bool operator ==(Object other) =>
@@ -331,7 +525,8 @@ class PageBrief {
runtimeType == other.runtimeType &&
id == other.id &&
title == other.title &&
isJournal == other.isJournal;
isJournal == other.isJournal &&
isHub == other.isHub;
}
/// Everything the page view needs in one call.
@@ -385,6 +580,21 @@ class PageDto {
final PlatformInt64 createdAt;
final PlatformInt64 updatedAt;
/// The page is a hub (no blocks; members list instead of an outline).
final bool isHub;
/// Hub description (empty for notes).
final String description;
/// Titles of the tag pages this page is filed under, in the order they were added.
final List<String> tags;
/// The page is a tag page (a topic that other pages are filed under).
final bool isTag;
/// Type names ("persona", "lugar"...: plain names, not pages), in the order added.
final List<String> types;
const PageDto({
required this.id,
required this.title,
@@ -392,6 +602,11 @@ class PageDto {
this.originJournal,
required this.createdAt,
required this.updatedAt,
required this.isHub,
required this.description,
required this.tags,
required this.isTag,
required this.types,
});
@override
@@ -401,7 +616,12 @@ class PageDto {
journalDate.hashCode ^
originJournal.hashCode ^
createdAt.hashCode ^
updatedAt.hashCode;
updatedAt.hashCode ^
isHub.hashCode ^
description.hashCode ^
tags.hashCode ^
isTag.hashCode ^
types.hashCode;
@override
bool operator ==(Object other) =>
@@ -413,7 +633,60 @@ class PageDto {
journalDate == other.journalDate &&
originJournal == other.originJournal &&
createdAt == other.createdAt &&
updatedAt == other.updatedAt;
updatedAt == other.updatedAt &&
isHub == other.isHub &&
description == other.description &&
tags == other.tags &&
isTag == other.isTag &&
types == other.types;
}
/// Hub and namespace context of one page.
class PageStructure {
final bool isHub;
/// Hub description (empty for notes).
final String description;
/// Empty unless the page is a hub; sub-hubs first, then notes.
final List<PageBrief> members;
/// Hubs the page belongs to (its own membership list), by title.
final List<PageBrief> inHubs;
/// Ancestor namespaces from the root: `A`, `A/B` for `A/B/C` (they may not exist).
final List<NamespaceEntry> nsPath;
final List<NamespaceEntry> nsChildren;
const PageStructure({
required this.isHub,
required this.description,
required this.members,
required this.inHubs,
required this.nsPath,
required this.nsChildren,
});
@override
int get hashCode =>
isHub.hashCode ^
description.hashCode ^
members.hashCode ^
inHubs.hashCode ^
nsPath.hashCode ^
nsChildren.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is PageStructure &&
runtimeType == other.runtimeType &&
isHub == other.isHub &&
description == other.description &&
members == other.members &&
inHubs == other.inHubs &&
nsPath == other.nsPath &&
nsChildren == other.nsChildren;
}
class Place {
@@ -464,6 +737,35 @@ class RelatedDto {
score == other.score;
}
/// A tag or type of the vocabulary.
class TagDto {
final String name;
/// Pages using it.
final int count;
/// One of the seeded suggestions.
final bool suggested;
const TagDto({
required this.name,
required this.count,
required this.suggested,
});
@override
int get hashCode => name.hashCode ^ count.hashCode ^ suggested.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is TagDto &&
runtimeType == other.runtimeType &&
name == other.name &&
count == other.count &&
suggested == other.suggested;
}
class TimelineDayDto {
final String date;
final String? journalId;
+90
View File
@@ -15,6 +15,14 @@ import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart';
abstract class SynapseGraph implements RustOpaqueInterface {
Future<void> addAlias({required String pageId, required String alias});
Future<PageDto> addPageTag({required String pageId, required String tag});
Future<PageDto> addPageType({required String pageId, required String ty});
/// Puts a page in a hub (no-op when it already is). Fails for journals, non-hub targets,
/// the hub itself and memberships that would create a cycle.
Future<void> addToHub({required String pageId, required String hubId});
Future<List<String>> aliases({required String pageId});
/// Local file path of an asset (for `asset://<hash>` images), if present.
@@ -26,6 +34,32 @@ abstract class SynapseGraph implements RustOpaqueInterface {
/// Target of a `((block ref))`.
Future<BlockRefDto?> blockRef({required String id});
/// Turns a note into a hub in one transaction: renames it to `title` (links rewritten),
/// moves its outline to a new note `keep_outline_as` (or deletes it when `None`; a blank title is an error), sets the
/// description and adds `member_ids` (invalid members are skipped).
Future<PageDto> convertToHub({
required String pageId,
required String title,
required String description,
required List<String> memberIds,
String? keepOutlineAs,
});
/// Turns a hub back into a note: description, then one `[[Member]]` block per member.
Future<PageDto> convertToNote({required String pageId});
/// Creates an empty hub. Fails when the title is taken.
Future<PageDto> createHub({
required String title,
required String description,
});
/// Creates a note in the hub, starting from a copy of the hub's template.
Future<PageDto> createPageFromTemplate({
required String hubId,
required String title,
});
/// Deletes a block and its subtree.
Future<List<BlockDto>> deleteBlock({required String id});
@@ -38,6 +72,16 @@ abstract class SynapseGraph implements RustOpaqueInterface {
/// graph changes.
Future<GraphData> graphData();
/// Defaults for converting a note into a hub.
Future<HubPreviewDto> hubConversionPreview({required String pageId});
/// Id of the hub's template page (created empty when missing). Open it like any note to
/// edit the outline new notes of the hub start from.
Future<String> hubTemplate({required String hubId});
/// Every hub with its members, and the root hubs.
Future<HubsDto> hubs();
/// Tab: the block becomes the last child of its previous sibling (no-op for a first child).
Future<List<BlockDto>> indentBlock({required String id});
@@ -56,6 +100,12 @@ abstract class SynapseGraph implements RustOpaqueInterface {
/// journal); otherwise at the newest journal strictly before `before`.
Future<List<PageData>> journals({String? before, required int limit});
/// Pages that are probably leftovers of Logseq: its built-ins and pages with
/// `type:: system`. Only the organisational files (`contents`, `card`, `favorites`,
/// `hls__*`) and empty pages are preselected, and never a hub: a built-in title such as
/// `todo` may hold real content.
Future<List<LegacyCandidate>> legacyCandidates();
/// Pages ordered by last update, most recent first.
Future<List<PageDto>> listPages({
required bool includeJournals,
@@ -95,6 +145,15 @@ abstract class SynapseGraph implements RustOpaqueInterface {
/// Page by title or alias, without creating it.
Future<PageData?> pageByTitle({required String title});
/// Hub and namespace context of a page.
Future<PageStructure> pageStructure({required String pageId});
/// Pages carrying a tag, most recently updated first.
Future<List<PageBrief>> pagesWithTag({required String tag});
/// Deletes pages and their blocks in one transaction. Returns how many existed.
Future<int> purgePages({required List<String> ids});
/// Stores in-memory bytes (clipboard, Android content URIs).
Future<AssetDto> putAssetBytes({
required List<int> bytes,
@@ -116,6 +175,13 @@ abstract class SynapseGraph implements RustOpaqueInterface {
Future<void> removeAlias({required String alias});
/// Takes a page out of a hub (no-op when it is not in it).
Future<void> removeFromHub({required String pageId, required String hubId});
Future<PageDto> removePageTag({required String pageId, required String tag});
Future<PageDto> removePageType({required String pageId, required String ty});
Future<PageDto> renamePage({required String id, required String newTitle});
/// Blocks whose text contains `query` (for `((` autocomplete), most recent first.
@@ -133,12 +199,36 @@ abstract class SynapseGraph implements RustOpaqueInterface {
Future<void> setCollapsed({required String id, required bool collapsed});
Future<PageDto> setHubDescription({
required String hubId,
required String description,
});
/// Replaces the tags of a page (each title gets a tag page if it has none). Journals,
/// templates and tag pages cannot be tagged.
Future<PageDto> setPageTags({
required String pageId,
required List<String> tags,
});
/// Replaces the types of a page. Journals and templates cannot be typed.
Future<PageDto> setPageTypes({
required String pageId,
required List<String> types,
});
/// Every tag page with its number of pages, most used first.
Future<List<TagDto>> tagCatalog();
/// Timeline data for `[from, to]` (oldest first) with titles of every page it mentions.
Future<TimelineDto> timeline({required String from, required String to});
/// Today's date (graph clock) as `YYYY-MM-DD`.
String today();
/// Types in use (most used first) followed by the seeded suggestions not used yet.
Future<List<TagDto>> typeCatalog();
/// Replaces a block's Markdown (the debounced save while typing).
Future<void> updateBlock({required String id, required String content});
}
File diff suppressed because it is too large. Load diff
+115
View File
@@ -115,6 +115,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
GraphNode dco_decode_graph_node(dynamic raw);
@protected
HubDto dco_decode_hub_dto(dynamic raw);
@protected
HubPreviewDto dco_decode_hub_preview_dto(dynamic raw);
@protected
HubsDto dco_decode_hubs_dto(dynamic raw);
@protected
int dco_decode_i_32(dynamic raw);
@@ -124,6 +133,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
LayoutFrame dco_decode_layout_frame(dynamic raw);
@protected
LegacyCandidate dco_decode_legacy_candidate(dynamic raw);
@protected
List<String> dco_decode_list_String(dynamic raw);
@@ -142,6 +154,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<GraphNode> dco_decode_list_graph_node(dynamic raw);
@protected
List<HubDto> dco_decode_list_hub_dto(dynamic raw);
@protected
List<LegacyCandidate> dco_decode_list_legacy_candidate(dynamic raw);
@protected
List<NamespaceEntry> dco_decode_list_namespace_entry(dynamic raw);
@protected
List<PageBrief> dco_decode_list_page_brief(dynamic raw);
@@ -172,12 +193,18 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<RelatedDto> dco_decode_list_related_dto(dynamic raw);
@protected
List<TagDto> dco_decode_list_tag_dto(dynamic raw);
@protected
List<TimelineDayDto> dco_decode_list_timeline_day_dto(dynamic raw);
@protected
List<TitleHit> dco_decode_list_title_hit(dynamic raw);
@protected
NamespaceEntry dco_decode_namespace_entry(dynamic raw);
@protected
String? dco_decode_opt_String(dynamic raw);
@@ -202,6 +229,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
PageDto dco_decode_page_dto(dynamic raw);
@protected
PageStructure dco_decode_page_structure(dynamic raw);
@protected
Place dco_decode_place(dynamic raw);
@@ -214,6 +244,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
RelatedDto dco_decode_related_dto(dynamic raw);
@protected
TagDto dco_decode_tag_dto(dynamic raw);
@protected
TimelineDayDto dco_decode_timeline_day_dto(dynamic raw);
@@ -324,6 +357,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
GraphNode sse_decode_graph_node(SseDeserializer deserializer);
@protected
HubDto sse_decode_hub_dto(SseDeserializer deserializer);
@protected
HubPreviewDto sse_decode_hub_preview_dto(SseDeserializer deserializer);
@protected
HubsDto sse_decode_hubs_dto(SseDeserializer deserializer);
@protected
int sse_decode_i_32(SseDeserializer deserializer);
@@ -333,6 +375,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
LayoutFrame sse_decode_layout_frame(SseDeserializer deserializer);
@protected
LegacyCandidate sse_decode_legacy_candidate(SseDeserializer deserializer);
@protected
List<String> sse_decode_list_String(SseDeserializer deserializer);
@@ -353,6 +398,19 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<GraphNode> sse_decode_list_graph_node(SseDeserializer deserializer);
@protected
List<HubDto> sse_decode_list_hub_dto(SseDeserializer deserializer);
@protected
List<LegacyCandidate> sse_decode_list_legacy_candidate(
SseDeserializer deserializer,
);
@protected
List<NamespaceEntry> sse_decode_list_namespace_entry(
SseDeserializer deserializer,
);
@protected
List<PageBrief> sse_decode_list_page_brief(SseDeserializer deserializer);
@@ -383,6 +441,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<RelatedDto> sse_decode_list_related_dto(SseDeserializer deserializer);
@protected
List<TagDto> sse_decode_list_tag_dto(SseDeserializer deserializer);
@protected
List<TimelineDayDto> sse_decode_list_timeline_day_dto(
SseDeserializer deserializer,
@@ -391,6 +452,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<TitleHit> sse_decode_list_title_hit(SseDeserializer deserializer);
@protected
NamespaceEntry sse_decode_namespace_entry(SseDeserializer deserializer);
@protected
String? sse_decode_opt_String(SseDeserializer deserializer);
@@ -419,6 +483,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
PageDto sse_decode_page_dto(SseDeserializer deserializer);
@protected
PageStructure sse_decode_page_structure(SseDeserializer deserializer);
@protected
Place sse_decode_place(SseDeserializer deserializer);
@@ -433,6 +500,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
RelatedDto sse_decode_related_dto(SseDeserializer deserializer);
@protected
TagDto sse_decode_tag_dto(SseDeserializer deserializer);
@protected
TimelineDayDto sse_decode_timeline_day_dto(SseDeserializer deserializer);
@@ -556,6 +626,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_graph_node(GraphNode self, SseSerializer serializer);
@protected
void sse_encode_hub_dto(HubDto self, SseSerializer serializer);
@protected
void sse_encode_hub_preview_dto(HubPreviewDto self, SseSerializer serializer);
@protected
void sse_encode_hubs_dto(HubsDto self, SseSerializer serializer);
@protected
void sse_encode_i_32(int self, SseSerializer serializer);
@@ -565,6 +644,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_layout_frame(LayoutFrame self, SseSerializer serializer);
@protected
void sse_encode_legacy_candidate(
LegacyCandidate self,
SseSerializer serializer,
);
@protected
void sse_encode_list_String(List<String> self, SseSerializer serializer);
@@ -589,6 +674,21 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer,
);
@protected
void sse_encode_list_hub_dto(List<HubDto> self, SseSerializer serializer);
@protected
void sse_encode_list_legacy_candidate(
List<LegacyCandidate> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_namespace_entry(
List<NamespaceEntry> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_page_brief(
List<PageBrief> self,
@@ -640,6 +740,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer,
);
@protected
void sse_encode_list_tag_dto(List<TagDto> self, SseSerializer serializer);
@protected
void sse_encode_list_timeline_day_dto(
List<TimelineDayDto> self,
@@ -649,6 +752,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_list_title_hit(List<TitleHit> self, SseSerializer serializer);
@protected
void sse_encode_namespace_entry(
NamespaceEntry self,
SseSerializer serializer,
);
@protected
void sse_encode_opt_String(String? self, SseSerializer serializer);
@@ -682,6 +791,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_page_dto(PageDto self, SseSerializer serializer);
@protected
void sse_encode_page_structure(PageStructure self, SseSerializer serializer);
@protected
void sse_encode_place(Place self, SseSerializer serializer);
@@ -697,6 +809,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_related_dto(RelatedDto self, SseSerializer serializer);
@protected
void sse_encode_tag_dto(TagDto self, SseSerializer serializer);
@protected
void sse_encode_timeline_day_dto(
TimelineDayDto self,
+115
View File
@@ -117,6 +117,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
GraphNode dco_decode_graph_node(dynamic raw);
@protected
HubDto dco_decode_hub_dto(dynamic raw);
@protected
HubPreviewDto dco_decode_hub_preview_dto(dynamic raw);
@protected
HubsDto dco_decode_hubs_dto(dynamic raw);
@protected
int dco_decode_i_32(dynamic raw);
@@ -126,6 +135,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
LayoutFrame dco_decode_layout_frame(dynamic raw);
@protected
LegacyCandidate dco_decode_legacy_candidate(dynamic raw);
@protected
List<String> dco_decode_list_String(dynamic raw);
@@ -144,6 +156,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<GraphNode> dco_decode_list_graph_node(dynamic raw);
@protected
List<HubDto> dco_decode_list_hub_dto(dynamic raw);
@protected
List<LegacyCandidate> dco_decode_list_legacy_candidate(dynamic raw);
@protected
List<NamespaceEntry> dco_decode_list_namespace_entry(dynamic raw);
@protected
List<PageBrief> dco_decode_list_page_brief(dynamic raw);
@@ -174,12 +195,18 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<RelatedDto> dco_decode_list_related_dto(dynamic raw);
@protected
List<TagDto> dco_decode_list_tag_dto(dynamic raw);
@protected
List<TimelineDayDto> dco_decode_list_timeline_day_dto(dynamic raw);
@protected
List<TitleHit> dco_decode_list_title_hit(dynamic raw);
@protected
NamespaceEntry dco_decode_namespace_entry(dynamic raw);
@protected
String? dco_decode_opt_String(dynamic raw);
@@ -204,6 +231,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
PageDto dco_decode_page_dto(dynamic raw);
@protected
PageStructure dco_decode_page_structure(dynamic raw);
@protected
Place dco_decode_place(dynamic raw);
@@ -216,6 +246,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
RelatedDto dco_decode_related_dto(dynamic raw);
@protected
TagDto dco_decode_tag_dto(dynamic raw);
@protected
TimelineDayDto dco_decode_timeline_day_dto(dynamic raw);
@@ -326,6 +359,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
GraphNode sse_decode_graph_node(SseDeserializer deserializer);
@protected
HubDto sse_decode_hub_dto(SseDeserializer deserializer);
@protected
HubPreviewDto sse_decode_hub_preview_dto(SseDeserializer deserializer);
@protected
HubsDto sse_decode_hubs_dto(SseDeserializer deserializer);
@protected
int sse_decode_i_32(SseDeserializer deserializer);
@@ -335,6 +377,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
LayoutFrame sse_decode_layout_frame(SseDeserializer deserializer);
@protected
LegacyCandidate sse_decode_legacy_candidate(SseDeserializer deserializer);
@protected
List<String> sse_decode_list_String(SseDeserializer deserializer);
@@ -355,6 +400,19 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<GraphNode> sse_decode_list_graph_node(SseDeserializer deserializer);
@protected
List<HubDto> sse_decode_list_hub_dto(SseDeserializer deserializer);
@protected
List<LegacyCandidate> sse_decode_list_legacy_candidate(
SseDeserializer deserializer,
);
@protected
List<NamespaceEntry> sse_decode_list_namespace_entry(
SseDeserializer deserializer,
);
@protected
List<PageBrief> sse_decode_list_page_brief(SseDeserializer deserializer);
@@ -385,6 +443,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<RelatedDto> sse_decode_list_related_dto(SseDeserializer deserializer);
@protected
List<TagDto> sse_decode_list_tag_dto(SseDeserializer deserializer);
@protected
List<TimelineDayDto> sse_decode_list_timeline_day_dto(
SseDeserializer deserializer,
@@ -393,6 +454,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<TitleHit> sse_decode_list_title_hit(SseDeserializer deserializer);
@protected
NamespaceEntry sse_decode_namespace_entry(SseDeserializer deserializer);
@protected
String? sse_decode_opt_String(SseDeserializer deserializer);
@@ -421,6 +485,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
PageDto sse_decode_page_dto(SseDeserializer deserializer);
@protected
PageStructure sse_decode_page_structure(SseDeserializer deserializer);
@protected
Place sse_decode_place(SseDeserializer deserializer);
@@ -435,6 +502,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
RelatedDto sse_decode_related_dto(SseDeserializer deserializer);
@protected
TagDto sse_decode_tag_dto(SseDeserializer deserializer);
@protected
TimelineDayDto sse_decode_timeline_day_dto(SseDeserializer deserializer);
@@ -558,6 +628,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_graph_node(GraphNode self, SseSerializer serializer);
@protected
void sse_encode_hub_dto(HubDto self, SseSerializer serializer);
@protected
void sse_encode_hub_preview_dto(HubPreviewDto self, SseSerializer serializer);
@protected
void sse_encode_hubs_dto(HubsDto self, SseSerializer serializer);
@protected
void sse_encode_i_32(int self, SseSerializer serializer);
@@ -567,6 +646,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_layout_frame(LayoutFrame self, SseSerializer serializer);
@protected
void sse_encode_legacy_candidate(
LegacyCandidate self,
SseSerializer serializer,
);
@protected
void sse_encode_list_String(List<String> self, SseSerializer serializer);
@@ -591,6 +676,21 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer,
);
@protected
void sse_encode_list_hub_dto(List<HubDto> self, SseSerializer serializer);
@protected
void sse_encode_list_legacy_candidate(
List<LegacyCandidate> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_namespace_entry(
List<NamespaceEntry> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_page_brief(
List<PageBrief> self,
@@ -642,6 +742,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer,
);
@protected
void sse_encode_list_tag_dto(List<TagDto> self, SseSerializer serializer);
@protected
void sse_encode_list_timeline_day_dto(
List<TimelineDayDto> self,
@@ -651,6 +754,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_list_title_hit(List<TitleHit> self, SseSerializer serializer);
@protected
void sse_encode_namespace_entry(
NamespaceEntry self,
SseSerializer serializer,
);
@protected
void sse_encode_opt_String(String? self, SseSerializer serializer);
@@ -684,6 +793,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_page_dto(PageDto self, SseSerializer serializer);
@protected
void sse_encode_page_structure(PageStructure self, SseSerializer serializer);
@protected
void sse_encode_place(Place self, SseSerializer serializer);
@@ -699,6 +811,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_related_dto(RelatedDto self, SseSerializer serializer);
@protected
void sse_encode_tag_dto(TagDto self, SseSerializer serializer);
@protected
void sse_encode_timeline_day_dto(
TimelineDayDto self,
+106 -18
View File
@@ -2,6 +2,9 @@ import 'package:flutter/material.dart';
import '../backend/graph_backend.dart';
import '../graph/network_canvas.dart';
import '../theme/theme.dart';
import 'keymap.dart';
import 'settings.dart';
import 'write_queue.dart';
sealed class AppRoute {
@@ -20,12 +23,15 @@ class AllPagesRoute extends AppRoute {
const AllPagesRoute();
}
class SettingsRoute extends AppRoute {
const SettingsRoute();
}
enum GraphMode {
network('Network', Icons.hub_outlined),
local('Local', Icons.adjust_rounded),
brain('Synapses', Icons.bolt_outlined),
clusters('Clusters', Icons.bubble_chart_outlined),
tree('Namespaces', Icons.account_tree_outlined),
tree('Tree', Icons.account_tree_outlined),
timeline('Timeline', Icons.timeline_rounded);
const GraphMode(this.label, this.icon);
@@ -54,10 +60,56 @@ class PageTarget extends AppRoute {
/// page, so a framework (Riverpod, Bloc) would add a dependency and indirection without
/// paying for itself; rebuilds are scoped with `ListenableBuilder`.
class AppState extends ChangeNotifier {
AppState(this.backend, {WriteQueue? queue})
AppState(this.backend, {WriteQueue? queue, SettingsStore? settings})
: refs = BlockRefCache(backend),
queue = queue ?? WriteQueue() {
queue = queue ?? WriteQueue(),
_settings = settings ?? MemorySettings() {
this.queue.onError = _writeFailed;
final saved = _settings.load();
final id = saved['theme'];
if (id is String && (id == autoThemeId || themeById(id) != null)) {
themeId = id;
}
final keys = saved['keys'];
keymap = Keymap(
keys is Map
? {for (final e in keys.entries) '${e.key}': '${e.value}'}
: {},
);
}
final SettingsStore _settings;
/// Key bindings (defaults plus the user's overrides).
late final Keymap keymap;
/// Selected theme id (`auto` follows the system).
String themeId = autoThemeId;
void _saveSettings() {
_settings.save({'theme': themeId, 'keys': keymap.toJson()});
}
void setTheme(String id) {
themeId = id;
_saveSettings();
notifyListeners();
}
/// Binds `combo` to `action`; returns the action already using it (nothing changes then).
AppAction? bindKey(AppAction action, Combo combo) {
final owner = keymap.bind(action, combo);
if (owner == null) {
_saveSettings();
notifyListeners();
}
return owner;
}
void resetKey(AppAction? action) {
action == null ? keymap.resetAll() : keymap.reset(action);
_saveSettings();
notifyListeners();
}
final GraphBackend backend;
@@ -67,7 +119,6 @@ class AppState extends ChangeNotifier {
AppRoute _route = const JournalsRoute();
final _back = <AppRoute>[];
final _forward = <AppRoute>[];
ThemeMode themeMode = ThemeMode.system;
final List<PageBrief> recent = [];
/// Node positions shared by the graph views (stable layouts across modes and filters).
@@ -79,6 +130,17 @@ class AppState extends ChangeNotifier {
/// Bumped to make the current view reload from the core (failed writes, renames).
int generation = 0;
/// Hubs expanded in the sidebar tree (kept here so it survives sidebar rebuilds).
final expandedHubs = <String>{};
/// Right sidebar of the page editor (local graph + related pages); collapsed by default.
bool pageSidebar = false;
void togglePageSidebar() {
pageSidebar = !pageSidebar;
notifyListeners();
}
/// Last write error, shown once by the shell.
String? writeError;
@@ -107,6 +169,25 @@ class AppState extends ChangeNotifier {
notifyListeners();
}
/// Points the current route and any history entry that opens `oldTitle` at the page `id`,
/// without pushing history (the page was renamed or converted, so its old title no longer
/// exists and opening it would create an empty duplicate).
void replaceWithId(String id, String oldTitle) {
final key = oldTitle.toLowerCase();
AppRoute fix(AppRoute r) =>
r is PageTarget && r.id == null && r.title!.toLowerCase() == key
? PageTarget(id: id)
: r;
if (_route is PageTarget) _route = PageTarget(id: id);
for (final l in [_back, _forward]) {
for (var i = 0; i < l.length; i++) {
l[i] = fix(l[i]);
}
}
generation++;
notifyListeners();
}
void back() {
if (_back.isEmpty) return;
_forward.add(_route);
@@ -132,15 +213,19 @@ class AppState extends ChangeNotifier {
queue.run(() => backend.recordVisit(from, page.id)).ignore();
}
recent.removeWhere((p) => p.id == page.id);
recent.insert(
0,
PageBrief(
id: page.id,
title: page.title,
isJournal: page.journalDate != null,
),
);
if (recent.length > 12) recent.removeLast();
// Hubs are folders, not pages: they never show up in recents.
if (!page.isHub) {
recent.insert(
0,
PageBrief(
id: page.id,
title: page.title,
isJournal: page.journalDate != null,
isHub: false,
),
);
if (recent.length > 12) recent.removeLast();
}
notifyListeners();
}
@@ -148,8 +233,10 @@ class AppState extends ChangeNotifier {
Future<void> loadRecent() async {
final pages = await backend.listPages(limit: 8);
for (final p in pages) {
if (!recent.any((r) => r.id == p.id)) {
recent.add(PageBrief(id: p.id, title: p.title, isJournal: false));
if (!p.isHub && !recent.any((r) => r.id == p.id)) {
recent.add(
PageBrief(id: p.id, title: p.title, isJournal: false, isHub: p.isHub),
);
}
}
notifyListeners();
@@ -162,14 +249,15 @@ class AppState extends ChangeNotifier {
id: id,
title: title,
isJournal: recent[i].isJournal,
isHub: recent[i].isHub,
);
}
notifyListeners();
}
/// Top-bar shortcut: flips between the light and dark Paper themes.
void toggleTheme(Brightness current) {
themeMode = current == Brightness.dark ? ThemeMode.light : ThemeMode.dark;
notifyListeners();
setTheme(current == Brightness.dark ? 'paper' : 'paper-dark');
}
}
+151
View File
@@ -0,0 +1,151 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
/// A key plus modifiers. Ctrl also matches Cmd on macOS.
@immutable
class Combo {
const Combo(
this.key, {
this.ctrl = false,
this.shift = false,
this.alt = false,
});
final LogicalKeyboardKey key;
final bool ctrl;
final bool shift;
final bool alt;
/// `ctrl+shift+<keyId>`: stable across platforms and keyboard layouts.
String encode() =>
'${ctrl ? 'ctrl+' : ''}${shift ? 'shift+' : ''}${alt ? 'alt+' : ''}${key.keyId}';
static Combo? decode(String s) {
final parts = s.split('+');
final id = int.tryParse(parts.last);
if (id == null) return null;
final mods = parts.sublist(0, parts.length - 1);
if (mods.any((m) => m != 'ctrl' && m != 'shift' && m != 'alt')) return null;
return Combo(
LogicalKeyboardKey.findKeyByKeyId(id) ?? LogicalKeyboardKey(id),
ctrl: mods.contains('ctrl'),
shift: mods.contains('shift'),
alt: mods.contains('alt'),
);
}
/// A key that is only a modifier cannot be bound on its own.
bool get isModifierOnly => const {
'Control Left',
'Control Right',
'Shift Left',
'Shift Right',
'Alt Left',
'Alt Right',
'Meta Left',
'Meta Right',
}.contains(key.keyLabel);
String get label {
final k = key.keyLabel.isEmpty ? 'Key ${key.keyId}' : key.keyLabel;
return [if (ctrl) 'Ctrl', if (shift) 'Shift', if (alt) 'Alt', k].join('+');
}
@override
bool operator ==(Object other) =>
other is Combo &&
other.key == key &&
other.ctrl == ctrl &&
other.shift == shift &&
other.alt == alt;
@override
int get hashCode => Object.hash(key, ctrl, shift, alt);
}
/// Everything that can be bound to a key. `editor` actions apply inside a focused block;
/// the others anywhere in the app.
enum AppAction {
quickSwitcher('Quick switcher', false),
journals('Journals', false),
graph('Graph view', false),
timeline('Timeline', false),
sidebar('Toggle sidebar', false),
pageSidebar('Toggle graph sidebar', false),
settings('Settings', false),
back('Back', false),
forward('Forward', false),
bold('Bold', true),
italic('Italic', true),
strike('Strikethrough', true),
highlight('Highlight', true),
code('Inline code', true),
link('Page link', true);
const AppAction(this.label, this.editor);
final String label;
final bool editor;
Combo get defaultCombo => switch (this) {
quickSwitcher => Combo(LogicalKeyboardKey.keyK, ctrl: true),
journals => Combo(LogicalKeyboardKey.keyJ, ctrl: true, shift: true),
graph => Combo(LogicalKeyboardKey.keyG, ctrl: true, shift: true),
timeline => Combo(LogicalKeyboardKey.keyT, ctrl: true, shift: true),
sidebar => Combo(LogicalKeyboardKey.backslash, ctrl: true),
pageSidebar => Combo(LogicalKeyboardKey.backslash, ctrl: true, shift: true),
settings => Combo(LogicalKeyboardKey.comma, ctrl: true),
back => Combo(LogicalKeyboardKey.arrowLeft, alt: true),
forward => Combo(LogicalKeyboardKey.arrowRight, alt: true),
bold => Combo(LogicalKeyboardKey.keyB, ctrl: true),
italic => Combo(LogicalKeyboardKey.keyI, ctrl: true),
strike => Combo(LogicalKeyboardKey.keyS, ctrl: true, shift: true),
highlight => Combo(LogicalKeyboardKey.keyH, ctrl: true, shift: true),
code => Combo(LogicalKeyboardKey.keyE, ctrl: true),
link => Combo(LogicalKeyboardKey.keyL, ctrl: true),
};
}
/// Default bindings plus the user's overrides. Combos are unique across all actions; binding
/// one that another action holds is refused (the caller shows which one).
class Keymap {
Keymap([Map<String, String> overrides = const {}]) {
for (final e in overrides.entries) {
final action = AppAction.values.asNameMap()[e.key];
final combo = Combo.decode(e.value);
if (action != null && combo != null) _custom[action] = combo;
}
}
final _custom = <AppAction, Combo>{};
Combo of(AppAction a) => _custom[a] ?? a.defaultCombo;
bool isCustom(AppAction a) => _custom.containsKey(a);
/// The action bound to `c`, if any.
AppAction? actionFor(Combo c, {bool? editor}) {
for (final a in AppAction.values) {
if ((editor == null || a.editor == editor) && of(a) == c) return a;
}
return null;
}
/// Binds `c` to `a`. Returns the action that already holds `c`, leaving the map unchanged.
AppAction? bind(AppAction a, Combo c) {
final owner = actionFor(c);
if (owner != null && owner != a) return owner;
if (c == a.defaultCombo) {
_custom.remove(a);
} else {
_custom[a] = c;
}
return null;
}
void reset(AppAction a) => _custom.remove(a);
void resetAll() => _custom.clear();
Map<String, String> toJson() => {
for (final e in _custom.entries) e.key.name: e.value.encode(),
};
}
+42
View File
@@ -0,0 +1,42 @@
import 'dart:convert';
import 'dart:io';
/// Where user preferences (theme, key bindings) are kept between runs.
abstract class SettingsStore {
Map<String, dynamic> load();
void save(Map<String, dynamic> data);
}
/// Keeps nothing (tests, previews).
class MemorySettings implements SettingsStore {
Map<String, dynamic> data = {};
@override
Map<String, dynamic> load() => data;
@override
void save(Map<String, dynamic> d) => data = d;
}
/// A small JSON file; unreadable or corrupt files just mean defaults.
class FileSettings implements SettingsStore {
FileSettings(this.path);
final String path;
@override
Map<String, dynamic> load() {
try {
final v = jsonDecode(File(path).readAsStringSync());
return v is Map<String, dynamic> ? v : {};
} catch (_) {
return {};
}
}
@override
void save(Map<String, dynamic> data) {
try {
File(path).writeAsStringSync(jsonEncode(data));
} catch (_) {}
}
}
+84 -4
View File
@@ -70,6 +70,52 @@ class SynapseColors extends ThemeExtension<SynapseColors> {
highlight: Color(0x55B89B2E),
);
/// "Sweet" (the KDE/GTK theme): deep indigo surfaces, magenta accent, mint for done tasks.
static const sweet = SynapseColors(
paper: Color(0xFF1B1D2B),
surface: Color(0xFF151722),
ink: Color(0xFFC9CDDA),
muted: Color(0xFF8E93AB),
faint: Color(0xFF555A78),
line: Color(0xFF2A2D42),
accent: Color(0xFFD05CE3),
accentSoft: Color(0x33D05CE3),
ref: Color(0xFFF2A65A),
done: Color(0xFF4DDBA7),
codeBg: Color(0xFF12141D),
highlight: Color(0x55D05CE3),
);
static const sweetLight = SynapseColors(
paper: Color(0xFFF8F6FB),
surface: Color(0xFFEFEBF5),
ink: Color(0xFF2B2D42),
muted: Color(0xFF6A6E88),
faint: Color(0xFFA8ABC0),
line: Color(0xFFE1DCEB),
accent: Color(0xFFB21FC2),
accentSoft: Color(0x1AB21FC2),
ref: Color(0xFFC77A1A),
done: Color(0xFF2FA37A),
codeBg: Color(0xFFEBE6F2),
highlight: Color(0x66F2C26B),
);
static const nord = SynapseColors(
paper: Color(0xFF2E3440),
surface: Color(0xFF272C36),
ink: Color(0xFFD8DEE9),
muted: Color(0xFF9AA5B8),
faint: Color(0xFF616E88),
line: Color(0xFF3B4252),
accent: Color(0xFF88C0D0),
accentSoft: Color(0x2288C0D0),
ref: Color(0xFFEBCB8B),
done: Color(0xFFA3BE8C),
codeBg: Color(0xFF242933),
highlight: Color(0x55EBCB8B),
);
@override
SynapseColors copyWith() => this;
@@ -107,10 +153,44 @@ extension SynapseThemeX on BuildContext {
SynapseColors get colors => Theme.of(this).extension<SynapseColors>()!;
}
ThemeData buildTheme(Brightness brightness) {
final c = brightness == Brightness.light
? SynapseColors.light
: SynapseColors.dark;
/// A selectable palette. `auto` follows the system between Paper light and Paper dark.
class AppTheme {
const AppTheme(this.id, this.label, this.brightness, this.colors);
final String id;
final String label;
final Brightness brightness;
final SynapseColors colors;
}
const autoThemeId = 'auto';
const appThemes = [
AppTheme('paper', 'Paper', Brightness.light, SynapseColors.light),
AppTheme('paper-dark', 'Paper dark', Brightness.dark, SynapseColors.dark),
AppTheme('sweet', 'Sweet', Brightness.dark, SynapseColors.sweet),
AppTheme(
'sweet-light',
'Sweet light',
Brightness.light,
SynapseColors.sweetLight,
),
AppTheme('nord', 'Nord', Brightness.dark, SynapseColors.nord),
];
/// The theme with `id`, or null for `auto` and unknown ids.
AppTheme? themeById(String id) {
for (final t in appThemes) {
if (t.id == id) return t;
}
return null;
}
ThemeData buildTheme(Brightness brightness, {SynapseColors? colors}) {
final c =
colors ??
(brightness == Brightness.light
? SynapseColors.light
: SynapseColors.dark);
final scheme =
ColorScheme.fromSeed(
seedColor: c.accent,
+234 -70
View File
@@ -6,7 +6,17 @@ import '../theme/theme.dart';
import '../widgets/common.dart';
import '../widgets/dates.dart';
/// Every non-journal page, most recently edited first, loaded in pages of 100.
enum PageSort {
edited('Edited'),
created('Created'),
title('Title');
const PageSort(this.label);
final String label;
}
/// Every non-journal note (hubs are folders, not pages), sortable. The whole list is loaded in
/// batches of 200 and sorted on the client; the list itself is built lazily.
class AllPagesView extends StatefulWidget {
const AllPagesView({super.key});
@@ -16,96 +26,250 @@ class AllPagesView extends StatefulWidget {
class _AllPagesViewState extends State<AllPagesView> {
final _pages = <PageDto>[];
bool _loading = false;
bool _done = false;
PageSort _sort = PageSort.edited;
bool _ascending = false;
@override
void initState() {
super.initState();
_more();
_load();
}
Future<void> _more() async {
if (_loading || _done) return;
_loading = true;
final batch = await AppScope.read(context).backend
.listPages(limit: 100, offset: _pages.length);
if (!mounted) return;
setState(() {
_pages.addAll(batch);
_done = batch.length < 100;
_loading = false;
Future<void> _load() async {
final backend = AppScope.read(context).backend;
var offset = 0;
while (true) {
final batch = await backend.listPages(limit: 200, offset: offset);
if (!mounted) return;
offset += batch.length;
setState(() => _pages.addAll(batch.where((p) => !p.isHub)));
if (batch.length < 200) return;
}
}
List<PageDto> get _sorted {
final list = [..._pages];
int cmp(PageDto a, PageDto b) => switch (_sort) {
PageSort.edited => a.updatedAt.compareTo(b.updatedAt),
PageSort.created => a.createdAt.compareTo(b.createdAt),
PageSort.title => a.title.toLowerCase().compareTo(b.title.toLowerCase()),
};
list.sort((a, b) {
final c = cmp(a, b);
// Time sorts default to newest first, so "descending" is the natural direction there.
final flip = _sort == PageSort.title ? _ascending : !_ascending;
return flip ? c : -c;
});
return list;
}
Future<void> _cleanUp() async {
final app = AppScope.read(context);
final candidates = await app.backend.legacyCandidates();
if (!mounted) return;
final removed = await showDialog<List<String>>(
context: context,
builder: (_) => CleanupDialog(candidates: candidates),
);
if (removed == null || removed.isEmpty) return;
await app.queue.run(() => app.backend.purgePages(removed));
app.recent.removeWhere((p) => removed.contains(p.id));
app.reload();
}
@override
Widget build(BuildContext context) {
final app = AppScope.read(context);
final colors = context.colors;
final pages = _sorted;
return LayoutBuilder(
builder: (context, box) => NotificationListener<ScrollNotification>(
onNotification: (n) {
if (n.metrics.extentAfter < 600) _more();
return false;
},
child: ListView.builder(
padding: EdgeInsets.fromLTRB(
sidePadding(box.maxWidth),
36,
sidePadding(box.maxWidth),
80,
),
itemCount: _pages.length + 1,
itemBuilder: (context, i) {
if (i == 0) {
return Padding(
padding: const EdgeInsets.only(bottom: 20),
child: Text(
'All pages',
style: Theme.of(context).textTheme.headlineLarge,
),
);
}
final p = _pages[i - 1];
final edited = DateTime.fromMillisecondsSinceEpoch(
p.updatedAt.toInt(),
);
return InkWell(
borderRadius: BorderRadius.circular(8),
onTap: () => app.openId(p.id),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 9, horizontal: 8),
child: Row(
children: [
Expanded(
builder: (context, box) => ListView.builder(
padding: EdgeInsets.fromLTRB(
sidePadding(box.maxWidth),
36,
sidePadding(box.maxWidth),
80,
),
itemCount: pages.length + 1,
itemBuilder: (context, i) {
if (i == 0) {
return Padding(
padding: const EdgeInsets.only(bottom: 20),
child: Row(
children: [
Expanded(
child: Text(
'All pages',
style: Theme.of(context).textTheme.headlineLarge,
),
),
PopupMenuButton<PageSort>(
key: const ValueKey('page-sort'),
tooltip: 'Sort by',
initialValue: _sort,
onSelected: (v) => setState(() {
_sort = v;
_ascending = false;
}),
itemBuilder: (_) => [
for (final v in PageSort.values)
PopupMenuItem(value: v, child: Text(v.label)),
],
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Text(
p.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 14.5, color: colors.ink),
_sort.label,
style: TextStyle(fontSize: 13, color: colors.muted),
),
),
if (p.originJournal != null)
Text(
'born ${shortDate(parseDay(p.originJournal!))}',
style: TextStyle(fontSize: 12, color: colors.faint),
),
const SizedBox(width: 16),
SizedBox(
width: 70,
child: Text(
shortDate(edited),
textAlign: TextAlign.right,
style: TextStyle(fontSize: 12, color: colors.muted),
),
),
IconButton(
key: const ValueKey('page-sort-direction'),
tooltip: _ascending ? 'Ascending' : 'Descending',
visualDensity: VisualDensity.compact,
iconSize: 18,
color: colors.muted,
icon: Icon(
_ascending
? Icons.arrow_upward_rounded
: Icons.arrow_downward_rounded,
),
],
),
onPressed: () => setState(() => _ascending = !_ascending),
),
const SizedBox(width: 8),
TextLink(
'Clean up',
icon: Icons.cleaning_services_outlined,
onTap: _cleanUp,
),
],
),
);
},
),
}
final p = pages[i - 1];
final edited = DateTime.fromMillisecondsSinceEpoch(
p.updatedAt.toInt(),
);
return InkWell(
borderRadius: BorderRadius.circular(8),
onTap: () => app.openId(p.id),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 9, horizontal: 8),
child: Row(
children: [
Expanded(
child: Text(
p.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 14.5, color: colors.ink),
),
),
if (p.originJournal != null)
Text(
'born ${shortDate(parseDay(p.originJournal!))}',
style: TextStyle(fontSize: 12, color: colors.faint),
),
const SizedBox(width: 16),
SizedBox(
width: 70,
child: Text(
shortDate(edited),
textAlign: TextAlign.right,
style: TextStyle(fontSize: 12, color: colors.muted),
),
),
],
),
),
);
},
),
);
}
}
/// Lists legacy Logseq pages with checkboxes; pops with the ids to delete (or null).
class CleanupDialog extends StatefulWidget {
const CleanupDialog({super.key, required this.candidates});
final List<LegacyCandidate> candidates;
@override
State<CleanupDialog> createState() => _CleanupDialogState();
}
class _CleanupDialogState extends State<CleanupDialog> {
late final Set<String> _checked = {
for (final c in widget.candidates)
if (c.preselected) c.id,
};
@override
Widget build(BuildContext context) {
final colors = context.colors;
final items = widget.candidates;
return AlertDialog(
title: const Text('Remove legacy Logseq pages'),
content: SizedBox(
width: 460,
child: items.isEmpty
? Text(
'No legacy pages found.',
style: TextStyle(color: colors.muted),
)
: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'This deletes the selected pages and their blocks.',
style: TextStyle(fontSize: 13, color: colors.muted),
),
const SizedBox(height: 8),
Flexible(
child: ListView(
shrinkWrap: true,
children: [
for (final c in items)
CheckboxListTile(
dense: true,
contentPadding: EdgeInsets.zero,
controlAffinity: ListTileControlAffinity.leading,
value: _checked.contains(c.id),
onChanged: (v) => setState(
() => v == true
? _checked.add(c.id)
: _checked.remove(c.id),
),
title: Text(c.title),
subtitle: Text(
'${c.reason} · ${c.blocks} '
'${c.blocks == 1 ? 'block' : 'blocks'}',
style: TextStyle(
fontSize: 12,
color: colors.faint,
),
),
),
],
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
if (items.isNotEmpty)
TextButton(
onPressed: _checked.isEmpty
? null
: () => Navigator.pop(context, _checked.toList()),
child: Text('Delete (${_checked.length})'),
),
],
);
}
}
+227
View File
@@ -0,0 +1,227 @@
import 'package:flutter/material.dart';
import '../backend/graph_backend.dart';
import '../state/app_state.dart';
import '../theme/theme.dart';
import '../widgets/pickers.dart';
/// "Convert to hub": title, description, member checklist and what to do with the outline.
/// Pops `true` once the page has been converted.
class ConvertToHubDialog extends StatefulWidget {
const ConvertToHubDialog({super.key, required this.page});
final PageDto page;
@override
State<ConvertToHubDialog> createState() => _ConvertToHubDialogState();
}
class _ConvertToHubDialogState extends State<ConvertToHubDialog> {
HubPreviewDto? _preview;
final _title = TextEditingController();
final _description = TextEditingController();
final _noteTitle = TextEditingController();
final _checked = <String>{};
bool _keep = false;
bool _busy = false;
String? _error;
Object? _loadError;
@override
void initState() {
super.initState();
_load();
}
@override
void dispose() {
_title.dispose();
_description.dispose();
_noteTitle.dispose();
super.dispose();
}
Future<void> _load() async {
final app = AppScope.read(context);
try {
final p = await app.backend.hubConversionPreview(widget.page.id);
if (!mounted) return;
setState(() {
_preview = p;
_title.text = p.suggestedTitle;
_description.text = p.suggestedDescription;
_noteTitle.text = p.suggestedNoteTitle;
_checked.addAll(p.members.map((m) => m.id));
_keep = p.proseBlocks > 0;
});
} catch (e) {
if (mounted) setState(() => _loadError = e);
}
}
Future<void> _convert() async {
final p = _preview!;
final app = AppScope.read(context);
setState(() {
_busy = true;
_error = null;
});
try {
await app.queue.run(
() => app.backend.convertToHub(
widget.page.id,
_title.text.trim(),
_description.text.trim(),
[
for (final m in p.members)
if (_checked.contains(m.id)) m.id,
],
keepOutlineAs: _keep ? _noteTitle.text.trim() : null,
),
report: false,
);
if (mounted) Navigator.pop(context, true);
} catch (e) {
if (mounted) {
setState(() {
_busy = false;
_error = errorText(e);
});
}
}
}
@override
Widget build(BuildContext context) {
final colors = context.colors;
final p = _preview;
return AlertDialog(
title: const Text('Convert to hub'),
content: SizedBox(
width: 480,
child: _loadError != null
? Text(errorText(_loadError!))
: p == null
? const SizedBox(
height: 80,
child: Center(child: CircularProgressIndicator()),
)
: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
key: const ValueKey('convert-title'),
controller: _title,
onChanged: (_) => setState(() {}),
decoration: const InputDecoration(labelText: 'Title'),
),
const SizedBox(height: 12),
TextField(
key: const ValueKey('convert-description'),
controller: _description,
minLines: 1,
maxLines: 3,
decoration: const InputDecoration(
labelText: 'Description',
),
),
const SizedBox(height: 16),
Text(
'MEMBERS (${_checked.length}/${p.members.length})',
style: Theme.of(context).textTheme.labelSmall,
),
if (p.members.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Text(
'No candidates found. Add notes from the hub afterwards.',
style: TextStyle(fontSize: 13, color: colors.muted),
),
),
ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 220),
child: ListView(
shrinkWrap: true,
children: [
for (final m in p.members)
CheckboxListTile(
key: ValueKey('member-${m.id}'),
dense: true,
contentPadding: EdgeInsets.zero,
controlAffinity: ListTileControlAffinity.leading,
value: _checked.contains(m.id),
title: Text(m.title),
onChanged: (v) => setState(
() => v == true
? _checked.add(m.id)
: _checked.remove(m.id),
),
),
],
),
),
const SizedBox(height: 8),
CheckboxListTile(
key: const ValueKey('keep-outline'),
dense: true,
contentPadding: EdgeInsets.zero,
controlAffinity: ListTileControlAffinity.leading,
value: _keep,
title: const Text('Keep the original outline in a note'),
subtitle: p.blocks == 0
? null
: Text(
_keep
? '${p.blocks} blocks move to the note'
: '${p.blocks} blocks will be deleted',
style: TextStyle(color: colors.faint),
),
onChanged: (v) => setState(() => _keep = v == true),
),
if (_keep)
TextField(
key: const ValueKey('convert-note-title'),
controller: _noteTitle,
onChanged: (_) => setState(() {}),
decoration: InputDecoration(
labelText: 'Note title',
errorText: _noteTitle.text.trim().isEmpty
? 'A title is required to keep the outline'
: null,
),
),
if (_error != null)
Padding(
padding: const EdgeInsets.only(top: 12),
child: Text(
_error!,
key: const ValueKey('convert-error'),
style: TextStyle(
color: Theme.of(context).colorScheme.error,
fontSize: 13,
),
),
),
],
),
),
),
actions: [
TextButton(
onPressed: _busy ? null : () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
onPressed:
p == null ||
_busy ||
_title.text.trim().isEmpty ||
(_keep && _noteTitle.text.trim().isEmpty)
? null
: _convert,
child: const Text('Convert'),
),
],
);
}
}
+77 -55
View File
@@ -22,23 +22,25 @@ class GraphView extends StatefulWidget {
const GraphView({super.key, this.mode = GraphMode.network, this.focusId});
final GraphMode mode;
/// Page to focus in the local and synapse modes.
/// Page to focus in the synapse mode.
final String? focusId;
@override
State<GraphView> createState() => _GraphViewState();
}
/// How the clusters mode groups pages.
enum ClusterBy { hubs, tags, communities }
class _GraphViewState extends State<GraphView> {
late GraphMode _mode = widget.mode;
GraphModel? _model;
Object? _error;
GraphFilter _filter = const GraphFilter();
ColorBy _colorBy = ColorBy.cluster;
int _depth = 2;
/// Journals are context for a neighbourhood, so the local mode shows them by default.
bool _localJournals = true;
/// Clusters mode grouping; null = hubs when the graph has any, else communities.
ClusterBy? _clusterBy;
int? _focus;
BrainOverlay? _brain;
SubGraph? _sub;
@@ -82,6 +84,10 @@ class _GraphViewState extends State<GraphView> {
}
}
ClusterBy get _grouping =>
_clusterBy ??
((_model?.hasHubs ?? false) ? ClusterBy.hubs : ClusterBy.communities);
void _setMode(GraphMode m) {
setState(() => _mode = m);
_rebuildSub();
@@ -102,16 +108,18 @@ class _GraphViewState extends State<GraphView> {
if (m == null) return;
switch (_mode) {
case GraphMode.network || GraphMode.clusters:
setState(() => _sub = m.subgraph(_filter.apply(m), _filter.kinds));
case GraphMode.local:
final f = _focus;
if (f == null) return;
final kinds = _filter.kinds;
final hood = m.neighbourhood(f, _depth, kinds);
final nodes = hood.keys
.where((i) => i == f || _localJournals || !m.isJournal(i))
.toList();
setState(() => _sub = m.subgraph(nodes, kinds));
final nodes = _filter.apply(m);
// Hub grouping: layout-only springs to the home hub so folders cluster spatially.
final springs = _mode != GraphMode.clusters
? const <(int, int, double)>[]
: switch (_grouping) {
ClusterBy.hubs => m.hubSprings(nodes),
ClusterBy.tags => m.tagSprings(nodes),
ClusterBy.communities => const <(int, int, double)>[],
};
setState(
() => _sub = m.subgraph(nodes, _filter.kinds, springs: springs),
);
case GraphMode.brain:
final f = _focus;
if (f == null) return;
@@ -348,39 +356,25 @@ class _GraphViewState extends State<GraphView> {
items: const {
ColorBy.cluster: 'Colour: cluster',
ColorBy.tag: 'Colour: tag',
ColorBy.hub: 'Colour: hub',
ColorBy.none: 'Colour: none',
},
onChanged: (c) => setState(() => _colorBy = c ?? ColorBy.cluster),
),
];
case GraphMode.local:
return [
search,
_Labeled(
'Depth $_depth',
SizedBox(
width: 120,
child: Slider(
key: const ValueKey('depth'),
value: _depth.toDouble(),
min: 1,
max: 3,
divisions: 2,
onChanged: (v) {
setState(() => _depth = v.round());
_rebuildSub();
},
),
),
),
chip('Journals', _localJournals, (v) {
setState(() => _localJournals = v);
_rebuildSub();
}),
if (_focus != null)
_FocusLink(
title: m.node(_focus!).title,
onTap: () => _open(_focus!),
if (_mode == GraphMode.clusters)
_Dropdown<ClusterBy>(
key: const ValueKey('cluster-group'),
value: _grouping,
hint: 'Group',
items: const {
ClusterBy.hubs: 'Group: hubs',
ClusterBy.tags: 'Group: tags',
ClusterBy.communities: 'Group: communities',
},
onChanged: (v) {
_clusterBy = v;
_rebuildSub();
},
),
];
case GraphMode.brain:
@@ -426,11 +420,17 @@ class _GraphViewState extends State<GraphView> {
),
);
}
if (_mode == GraphMode.tree) return TreeCanvas(model: m, onTap: _open);
if (_mode == GraphMode.tree) {
return TreeCanvas(
model: m,
onTap: _open,
name: AppScope.read(context).backend.graphName,
);
}
final sub = _sub;
if (sub == null) return const SizedBox.shrink();
final app = AppScope.read(context);
final explore = _mode == GraphMode.local || _mode == GraphMode.brain;
final explore = _mode == GraphMode.brain;
return Stack(
children: [
Positioned.fill(
@@ -438,7 +438,13 @@ class _GraphViewState extends State<GraphView> {
key: ValueKey(_mode),
sub: sub,
cache: app.graphPositions,
colorBy: _mode == GraphMode.clusters ? ColorBy.cluster : _colorBy,
colorBy: _mode == GraphMode.clusters
? switch (_grouping) {
ClusterBy.hubs => ColorBy.hub,
ClusterBy.tags => ColorBy.tagGroup,
ClusterBy.communities => ColorBy.cluster,
}
: _colorBy,
hulls: _mode == GraphMode.clusters,
focus: explore ? _focus : null,
brain: _mode == GraphMode.brain ? _brain : null,
@@ -485,6 +491,7 @@ class _Labeled extends StatelessWidget {
class _Dropdown<T> extends StatelessWidget {
const _Dropdown({
super.key,
required this.value,
required this.hint,
required this.items,
@@ -566,17 +573,39 @@ class _Legend extends StatelessWidget {
],
),
);
Widget hubMark() => Padding(
padding: const EdgeInsets.only(right: 14),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 11,
height: 11,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: colors.muted,
border: Border.all(color: colors.ink, width: 1.6),
),
),
const SizedBox(width: 5),
Text('Hub', style: TextStyle(fontSize: 11.5, color: colors.muted)),
],
),
);
final items = mode == GraphMode.brain
? [
line(palette[3], 'Synapse (thicker = stronger)', w: 3),
line(colors.accent, 'Activation pulse', w: 3),
hubMark(),
]
: [
line(colors.muted, 'Link'),
line(colors.accent, 'Tag'),
line(palette[2], 'Property'),
line(colors.ref, 'Block ref / embed'),
line(colors.ink, 'Contains (hub → note)', w: 1),
line(colors.faint, 'Mention', dashed: true),
hubMark(),
];
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
@@ -679,6 +708,8 @@ class _LocalGraphPanelState extends State<LocalGraphPanel> {
EdgeKind.blockRef,
EdgeKind.embed,
EdgeKind.mention,
EdgeKind.contains,
EdgeKind.tagged,
};
final hood = m.neighbourhood(f, _depth, kinds).keys.toList();
setState(() => _sub = m.subgraph(hood, kinds));
@@ -721,15 +752,6 @@ class _LocalGraphPanelState extends State<LocalGraphPanel> {
),
),
),
IconButton(
tooltip: 'Open in graph view',
visualDensity: VisualDensity.compact,
iconSize: 15,
color: colors.muted,
icon: const Icon(Icons.open_in_full_rounded),
onPressed: () =>
app.go(GraphRoute(GraphMode.local, focusId: widget.pageId)),
),
],
),
const SizedBox(height: 6),
+334
View File
@@ -0,0 +1,334 @@
import 'package:flutter/material.dart';
import '../backend/graph_backend.dart';
import '../state/app_state.dart';
import '../theme/theme.dart';
import '../widgets/common.dart';
import '../widgets/dates.dart';
import '../widgets/pickers.dart';
import '../widgets/tags.dart';
import 'graph_view.dart';
import 'page_screen.dart';
/// A hub: title, short description and its members (sub-hubs first, then notes). It has no
/// outline. Membership is stored on the member, so adding/removing edits the member.
class HubScreen extends StatefulWidget {
const HubScreen({
super.key,
required this.page,
required this.aliases,
required this.structure,
required this.hubSizes,
});
final PageDto page;
final List<String> aliases;
final PageStructure? structure;
final Map<String, int> hubSizes;
@override
State<HubScreen> createState() => _HubScreenState();
}
class _HubScreenState extends State<HubScreen> {
late final _desc = TextEditingController(text: widget.page.description);
late final _focus = FocusNode()..addListener(_blur);
late String _committed = widget.page.description;
AppState? _app;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_app = AppScope.read(context);
}
@override
void dispose() {
_commit();
_desc.dispose();
_focus.dispose();
super.dispose();
}
void _blur() {
if (!_focus.hasFocus) _commit();
}
void _commit() {
final text = _desc.text.trim();
if (text == _committed) return;
_committed = text;
final app = _app!;
app.queue
.run(() => app.backend.setHubDescription(widget.page.id, text))
.ignore();
}
Future<void> _add() async {
final app = AppScope.read(context);
final hub = widget.page;
final st = widget.structure;
final taken = {hub.id, ...?st?.members.map((m) => m.id)};
final messenger = ScaffoldMessenger.of(context);
final r = await showPagePicker(
context,
heading: 'Add to ${hub.title}',
canCreateNote: true,
canCreateHub: true,
search: (q) async {
if (q.isEmpty) {
final l = await app.backend.listPages(limit: 20);
return [
for (final p in l)
if (!taken.contains(p.id))
PickItem(id: p.id, title: p.title, isHub: p.isHub),
];
}
final hits = await app.backend.searchTitles(q);
return [
for (final h in hits)
if (!taken.contains(h.pageId))
PickItem(id: h.pageId, title: h.title),
];
},
);
if (r == null || !mounted) return;
try {
await app.queue.run(() async {
final String id;
if (r.item != null) {
id = r.item!.id;
} else if (r.newHub) {
id = (await app.backend.createHub(r.newTitle!, '')).id;
} else {
id = (await app.backend.createPageFromTemplate(
hub.id,
r.newTitle!,
)).id;
}
await app.backend.addToHub(id, hub.id);
}, report: false);
app.reload();
} catch (e) {
messenger.showSnackBar(SnackBar(content: Text(errorText(e))));
}
}
Future<void> _openTemplate() async {
final app = AppScope.read(context);
final messenger = ScaffoldMessenger.of(context);
try {
app.openId(await app.backend.hubTemplate(widget.page.id));
} catch (e) {
messenger.showSnackBar(SnackBar(content: Text(errorText(e))));
}
}
Future<void> _remove(PageBrief m) async {
final app = AppScope.read(context);
final messenger = ScaffoldMessenger.of(context);
try {
await app.queue.run(
() => app.backend.removeFromHub(m.id, widget.page.id),
report: false,
);
app.reload();
} catch (e) {
messenger.showSnackBar(SnackBar(content: Text(errorText(e))));
}
}
@override
Widget build(BuildContext context) {
final colors = context.colors;
final app = AppScope.read(context);
final st = widget.structure;
final page = widget.page;
final members = st?.members ?? const <PageBrief>[];
return LayoutBuilder(
builder: (context, box) {
final pad = sidePadding(box.maxWidth);
return ListView(
padding: EdgeInsets.fromLTRB(pad, 36, pad, 120),
children: [
if (st != null && st.nsPath.isNotEmpty) ...[
Breadcrumb(path: st.nsPath),
const SizedBox(height: 6),
],
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: TitleField(page: page)),
PageMenu(page: page, structure: st),
],
),
const SizedBox(height: 8),
TextField(
key: const ValueKey('hub-description'),
controller: _desc,
focusNode: _focus,
minLines: 1,
maxLines: 3,
style: TextStyle(fontSize: 14.5, color: colors.muted),
decoration: const InputDecoration.collapsed(
hintText: 'Add a short description',
),
),
const SizedBox(height: 10),
Wrap(
spacing: 14,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
if (st != null && st.inHubs.isNotEmpty)
InHubs(pageId: page.id, hubs: st.inHubs),
if (page.originJournal != null)
TextLink(
'Born ${longDate(page.originJournal!)}',
icon: Icons.spa_outlined,
onTap: () => app.openTitle(page.originJournal!),
style: const TextStyle(fontSize: 12),
),
],
),
const SizedBox(height: 8),
TagBar(page: page),
const SizedBox(height: 28),
Row(
children: [
Expanded(
child: SectionLabel(
'Members',
trailing: Text(
'${members.length}',
style: TextStyle(fontSize: 11, color: colors.faint),
),
),
),
TextLink(
'Template',
icon: Icons.article_outlined,
onTap: _openTemplate,
style: const TextStyle(fontSize: 12.5),
),
const SizedBox(width: 14),
TextLink(
'Add',
icon: Icons.add_rounded,
onTap: _add,
style: const TextStyle(fontSize: 12.5),
),
],
),
const SizedBox(height: 8),
if (st != null && members.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Text(
'Empty. Add notes or sub-hubs to organise them here.',
style: TextStyle(fontSize: 13, color: colors.muted),
),
),
for (final m in members)
_MemberRow(
key: ValueKey('member-${m.id}'),
member: m,
count: widget.hubSizes[m.id],
onOpen: () => app.openId(m.id),
onRemove: () => _remove(m),
),
const SizedBox(height: 36),
LocalGraphPanel(key: ValueKey('local-${page.id}'), pageId: page.id),
],
);
},
);
}
}
class _MemberRow extends StatefulWidget {
const _MemberRow({
super.key,
required this.member,
required this.count,
required this.onOpen,
required this.onRemove,
});
final PageBrief member;
final int? count;
final VoidCallback onOpen;
final VoidCallback onRemove;
@override
State<_MemberRow> createState() => _MemberRowState();
}
class _MemberRowState extends State<_MemberRow> {
bool _hover = false;
Future<void> _menu(Offset at) async {
final r = await showMenu<bool>(
context: context,
position: RelativeRect.fromLTRB(at.dx, at.dy, at.dx, at.dy),
items: const [PopupMenuItem(value: true, child: Text('Remove from hub'))],
);
if (r == true) widget.onRemove();
}
@override
Widget build(BuildContext context) {
final colors = context.colors;
final m = widget.member;
return MouseRegion(
onEnter: (_) => setState(() => _hover = true),
onExit: (_) => setState(() => _hover = false),
child: GestureDetector(
onLongPressStart: (d) => _menu(d.globalPosition),
child: InkWell(
borderRadius: BorderRadius.circular(8),
onTap: widget.onOpen,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
child: Row(
children: [
Icon(
m.isHub ? Icons.folder_outlined : Icons.description_outlined,
size: 17,
color: colors.accent.withAlpha(0xCC),
),
const SizedBox(width: 10),
Expanded(
child: Text(
m.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 14.5, color: colors.ink),
),
),
if (m.isHub && widget.count != null)
Text(
'${widget.count}',
style: TextStyle(fontSize: 11.5, color: colors.faint),
),
SizedBox(
width: 28,
child: _hover
? InkResponse(
key: ValueKey('remove-${m.id}'),
radius: 14,
onTap: widget.onRemove,
child: Icon(
Icons.close_rounded,
size: 15,
color: colors.faint,
),
)
: null,
),
],
),
),
),
),
);
}
}
+273
View File
@@ -0,0 +1,273 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../backend/graph_backend.dart';
import '../state/app_state.dart';
import '../theme/theme.dart';
import '../widgets/pickers.dart';
/// Sidebar "HUBS" section: a collapsible folder tree (root hubs, their sub-hubs and pages).
/// Always visible, with a "+" to create a hub; root hubs start expanded.
class HubsSection extends StatefulWidget {
const HubsSection({super.key, required this.onOpen, this.selectedId});
final void Function(String id) onOpen;
final String? selectedId;
@override
State<HubsSection> createState() => _HubsSectionState();
}
class _HubsSectionState extends State<HubsSection> {
HubsDto? _data;
Map<String, HubDto> _byId = const {};
int? _generation;
AppState? _app;
Timer? _refresh;
@override
void didChangeDependencies() {
super.didChangeDependencies();
final app = AppScope.of(context);
if (_app != app) {
_app?.queue.revision.removeListener(_edited);
_app = app..queue.revision.addListener(_edited);
}
if (_generation != app.generation) {
_generation = app.generation;
_load();
}
}
@override
void dispose() {
_refresh?.cancel();
_app?.queue.revision.removeListener(_edited);
super.dispose();
}
void _edited() {
_refresh?.cancel();
_refresh = Timer(const Duration(milliseconds: 1500), _load);
}
Future<void> _load() async {
final app = _app;
if (app == null) return;
try {
final d = await app.backend.hubs();
if (!mounted) return;
setState(() {
_data = d;
_byId = {for (final h in d.hubs) h.id: h};
});
} catch (e) {
debugPrint('hubs load failed: $e');
}
}
Future<void> _create() async {
final app = AppScope.read(context);
final hub = await showNameDialog<PageDto>(
context,
heading: 'New hub',
confirm: 'Create',
submit: (t) =>
app.queue.run(() => app.backend.createHub(t, ''), report: false),
);
if (hub == null) return;
app.reload();
app.openId(hub.id);
}
void _toggle(String id) {
final open = AppScope.read(context).expandedHubs;
setState(() => open.contains(id) ? open.remove(id) : open.add(id));
}
/// Rows of a hub's subtree. `path` holds the hubs above, which guards against cycles.
void _rows(
List<Widget> out,
HubDto hub,
int depth,
Set<String> path,
Set<String> open,
) {
final expanded = open.contains(hub.id);
// Keys use the full path: a sub-hub can sit in several hubs.
final inner = {...path, hub.id};
final at = inner.join('/');
out.add(
_TreeRow(
key: ValueKey('hub-$at'),
label: hub.title,
depth: depth,
isHub: true,
expanded: expanded,
selected: widget.selectedId == hub.id,
onToggle: () => _toggle(hub.id),
onTap: () => widget.onOpen(hub.id),
),
);
if (!expanded) return;
// Only sub-hubs are children here; notes are listed on the hub's own screen.
for (final m in hub.members) {
final sub = hub.subHubs.contains(m.id) ? _byId[m.id] : null;
if (sub != null && !inner.contains(sub.id)) {
_rows(out, sub, depth + 1, inner, open);
}
}
}
@override
Widget build(BuildContext context) {
final data = _data;
final open = AppScope.read(context).expandedHubs;
final rows = <Widget>[];
for (final id in data?.roots ?? const <String>[]) {
final h = _byId[id];
if (h != null) _rows(rows, h, 0, const {}, open);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 6),
child: Row(
children: [
Expanded(
child: Text(
'HUBS',
style: Theme.of(context).textTheme.labelSmall,
),
),
InkResponse(
key: const ValueKey('new-hub'),
radius: 12,
onTap: _create,
child: Icon(
Icons.add_rounded,
size: 16,
color: context.colors.faint,
),
),
],
),
),
...rows,
const SizedBox(height: 22),
],
);
}
}
class _TreeRow extends StatefulWidget {
const _TreeRow({
super.key,
required this.label,
required this.depth,
required this.isHub,
required this.selected,
required this.onTap,
this.expanded = false,
this.onToggle,
});
final String label;
final int depth;
final bool isHub;
final bool expanded;
final bool selected;
final VoidCallback onTap;
/// Non-null for hubs that can be expanded.
final VoidCallback? onToggle;
@override
State<_TreeRow> createState() => _TreeRowState();
}
class _TreeRowState extends State<_TreeRow> {
bool _hover = false;
@override
Widget build(BuildContext context) {
final colors = context.colors;
final active = widget.selected;
final toggle = widget.onToggle;
return MouseRegion(
cursor: SystemMouseCursors.click,
onEnter: (_) => setState(() => _hover = true),
onExit: (_) => setState(() => _hover = false),
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 1),
padding: EdgeInsets.only(left: 4.0 + 14 * widget.depth, right: 8),
decoration: BoxDecoration(
color: active
? colors.accentSoft
: _hover
? colors.line.withAlpha(0x66)
: null,
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
SizedBox(
width: 22,
height: 28,
child: toggle == null
? null
: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: toggle,
child: Icon(
widget.expanded
? Icons.expand_more_rounded
: Icons.chevron_right_rounded,
size: 16,
color: colors.faint,
),
),
),
Expanded(
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: widget.onTap,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(
children: [
Icon(
widget.isHub
? (widget.expanded
? Icons.folder_open_outlined
: Icons.folder_outlined)
: Icons.description_outlined,
size: 14,
color: active ? colors.accent : colors.faint,
),
const SizedBox(width: 8),
Expanded(
child: Text(
widget.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
fontWeight: active
? FontWeight.w600
: FontWeight.w500,
color: active ? colors.ink : colors.muted,
),
),
),
],
),
),
),
),
],
),
),
);
}
}
+334 -13
View File
@@ -7,7 +7,11 @@ import '../state/outline_controller.dart';
import '../theme/theme.dart';
import '../widgets/common.dart';
import '../widgets/dates.dart';
import '../widgets/pickers.dart';
import '../widgets/tags.dart';
import 'convert_dialog.dart';
import 'graph_view.dart';
import 'hub_screen.dart';
import 'journals_view.dart';
/// A single page: title, aliases, outline, linked references and related notes.
@@ -24,6 +28,8 @@ class _PageScreenState extends State<PageScreen> {
OutlineController? _outline;
List<BacklinkGroup>? _backlinks;
List<RelatedDto>? _related;
PageStructure? _structure;
Map<String, int> _hubSizes = const {};
Object? _error;
@override
@@ -69,6 +75,8 @@ class _PageScreenState extends State<PageScreen> {
app.pageShown(view.page);
// Make sure pending writes (e.g. a link just typed elsewhere) are visible.
await app.queue.idle;
if (view.page.journalDate == null) await _loadStructure();
if (view.page.isHub) return;
final results = await Future.wait([
app.backend.backlinks(view.page.id),
app.backend.related(view.page.id),
@@ -83,6 +91,27 @@ class _PageScreenState extends State<PageScreen> {
}
}
/// Hub and namespace context of the page (not shown for journals).
Future<void> _loadStructure() async {
final app = AppScope.read(context);
final id = _view!.page.id;
try {
final st = await app.backend.pageStructure(id);
var sizes = const <String, int>{};
if (st.isHub && st.members.any((m) => m.isHub)) {
final hubs = await app.backend.hubs();
sizes = {for (final h in hubs.hubs) h.id: h.members.length};
}
if (!mounted) return;
setState(() {
_structure = st;
_hubSizes = sizes;
});
} catch (e) {
debugPrint('page structure failed: $e');
}
}
@override
Widget build(BuildContext context) {
if (_error != null) {
@@ -92,10 +121,20 @@ class _PageScreenState extends State<PageScreen> {
}
final view = _view;
if (view == null) return const SizedBox.shrink();
if (view.page.isHub) {
return HubScreen(
page: view.page,
aliases: view.aliases,
structure: _structure,
hubSizes: _hubSizes,
);
}
return LayoutBuilder(
builder: (context, box) {
final wide = box.maxWidth >= 1180;
final mainWidth = wide ? box.maxWidth - 300 : box.maxWidth;
final open = AppScope.of(context).pageSidebar;
final wide = box.maxWidth >= 900;
final side = open && wide;
final mainWidth = side ? box.maxWidth - 300 : box.maxWidth;
final pad = sidePadding(mainWidth);
final scroll = CustomScrollView(
slivers: [
@@ -104,12 +143,18 @@ class _PageScreenState extends State<PageScreen> {
padding: EdgeInsets.symmetric(horizontal: pad),
sliver: SliverMainAxisGroup(
slivers: [
SliverToBoxAdapter(child: _Header(view: view)),
SliverToBoxAdapter(
child: _Header(view: view, structure: _structure),
),
if (_structure != null)
SliverToBoxAdapter(
child: _NamespaceSection(structure: _structure!),
),
OutlineSliver(controller: _outline!),
SliverToBoxAdapter(
child: _LinkedReferences(groups: _backlinks),
),
if (!wide) ...[
if (open && !wide) ...[
SliverToBoxAdapter(child: RelatedPanel(related: _related)),
SliverToBoxAdapter(
child: Padding(
@@ -124,7 +169,7 @@ class _PageScreenState extends State<PageScreen> {
),
],
);
if (!wide) return scroll;
if (!side) return scroll;
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@@ -154,8 +199,9 @@ class _PageScreenState extends State<PageScreen> {
}
class _Header extends StatelessWidget {
const _Header({required this.view});
const _Header({required this.view, required this.structure});
final PageData view;
final PageStructure? structure;
@override
Widget build(BuildContext context) {
@@ -185,13 +231,38 @@ class _Header extends StatelessWidget {
],
),
] else ...[
_TitleField(page: page),
if (structure != null && structure!.nsPath.isNotEmpty) ...[
Breadcrumb(path: structure!.nsPath),
const SizedBox(height: 6),
],
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: TitleField(page: page)),
IconButton(
key: const ValueKey('page-sidebar-toggle'),
tooltip: AppScope.of(context).pageSidebar
? 'Hide graph sidebar'
: 'Show graph sidebar',
visualDensity: VisualDensity.compact,
iconSize: 20,
color: AppScope.of(context).pageSidebar
? colors.accent
: colors.muted,
icon: const Icon(Icons.view_sidebar_outlined),
onPressed: AppScope.read(context).togglePageSidebar,
),
PageMenu(page: page, structure: structure),
],
),
const SizedBox(height: 6),
Wrap(
spacing: 14,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
if (structure != null && structure!.inHubs.isNotEmpty)
InHubs(pageId: page.id, hubs: structure!.inHubs),
if (page.originJournal != null)
TextLink(
'Born ${longDate(page.originJournal!)}',
@@ -202,6 +273,9 @@ class _Header extends StatelessWidget {
_Aliases(page: page, initial: view.aliases),
],
),
const SizedBox(height: 8),
TagBar(page: page),
if (page.isTag) TaggedNotes(tag: page.title),
],
],
),
@@ -210,15 +284,15 @@ class _Header extends StatelessWidget {
}
/// Page title; editing it renames the page (and rewrites every link to it).
class _TitleField extends StatefulWidget {
const _TitleField({required this.page});
class TitleField extends StatefulWidget {
const TitleField({super.key, required this.page});
final PageDto page;
@override
State<_TitleField> createState() => _TitleFieldState();
State<TitleField> createState() => TitleFieldState();
}
class _TitleFieldState extends State<_TitleField> {
class TitleFieldState extends State<TitleField> {
late final _text = TextEditingController(text: widget.page.title);
late final _focus = FocusNode()..addListener(_blur);
late String _committed = widget.page.title;
@@ -244,10 +318,12 @@ class _TitleFieldState extends State<_TitleField> {
final messenger = ScaffoldMessenger.of(context);
try {
await app.queue.run(() => app.backend.renamePage(widget.page.id, title));
final old = _committed;
_committed = title;
app.renamed(widget.page.id, title);
// The core rewrote links in other blocks, possibly on this page: reload them.
app.reload();
// The core rewrote links in other blocks, possibly on this page: reload them. The
// route must not keep opening the old title (that would create a duplicate page).
app.replaceWithId(widget.page.id, old);
} catch (e) {
_text.text = _committed;
messenger.showSnackBar(SnackBar(content: Text('Rename failed: $e')));
@@ -494,3 +570,248 @@ class RelatedPanel extends StatelessWidget {
);
}
}
/// Namespace ancestors of the page, `A / B` above the title. Segments open their page
/// (virtual ones are created on open, like links).
class Breadcrumb extends StatelessWidget {
const Breadcrumb({super.key, required this.path});
final List<NamespaceEntry> path;
@override
Widget build(BuildContext context) {
final colors = context.colors;
final app = AppScope.read(context);
return Wrap(
spacing: 6,
runSpacing: 2,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Icon(Icons.account_tree_outlined, size: 14, color: colors.faint),
for (var i = 0; i < path.length; i++) ...[
if (i > 0)
Text('/', style: TextStyle(fontSize: 12, color: colors.faint)),
TextLink(
path[i].title.split('/').last,
onTap: () => path[i].id != null
? app.openId(path[i].id!)
: app.openTitle(path[i].title),
style: const TextStyle(fontSize: 12.5),
),
],
],
);
}
}
/// "In: hub, hub" chips for the hubs containing the page; each has a remove button.
class InHubs extends StatelessWidget {
const InHubs({super.key, required this.pageId, required this.hubs});
final String pageId;
final List<PageBrief> hubs;
@override
Widget build(BuildContext context) {
final colors = context.colors;
final app = AppScope.read(context);
return Wrap(
spacing: 8,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Text('In', style: TextStyle(fontSize: 12, color: colors.faint)),
for (final h in hubs)
Row(
mainAxisSize: MainAxisSize.min,
children: [
TextLink(
h.title,
icon: Icons.folder_outlined,
onTap: () => app.openId(h.id),
style: const TextStyle(fontSize: 12),
),
InkResponse(
key: ValueKey('leave-${h.id}'),
radius: 10,
onTap: () async {
final messenger = ScaffoldMessenger.of(context);
try {
await app.queue.run(
() => app.backend.removeFromHub(pageId, h.id),
report: false,
);
app.reload();
} catch (e) {
messenger.showSnackBar(
SnackBar(content: Text(errorText(e))),
);
}
},
child: Padding(
padding: const EdgeInsets.all(3),
child: Icon(
Icons.close_rounded,
size: 12,
color: colors.faint,
),
),
),
],
),
],
);
}
}
/// The page's "⋯" menu: hub conversion and hub membership.
class PageMenu extends StatelessWidget {
const PageMenu({super.key, required this.page, required this.structure});
final PageDto page;
final PageStructure? structure;
Future<void> _addToHub(BuildContext context) async {
final app = AppScope.read(context);
final messenger = ScaffoldMessenger.of(context);
final taken = {page.id, ...?structure?.inHubs.map((h) => h.id)};
final r = await showPagePicker(
context,
heading: 'Add to hub',
canCreateHub: true,
search: (q) async {
final all = await app.backend.hubs();
return [
for (final h in all.hubs)
if (!taken.contains(h.id) &&
h.title.toLowerCase().contains(q.toLowerCase()))
PickItem(id: h.id, title: h.title, isHub: true),
];
},
);
if (r == null) return;
try {
await app.queue.run(() async {
final id =
r.item?.id ?? (await app.backend.createHub(r.newTitle!, '')).id;
await app.backend.addToHub(page.id, id);
}, report: false);
app.reload();
} catch (e) {
messenger.showSnackBar(SnackBar(content: Text(errorText(e))));
}
}
Future<void> _toHub(BuildContext context) async {
final app = AppScope.read(context);
final ok = await showDialog<bool>(
context: context,
builder: (_) => ConvertToHubDialog(page: page),
);
if (ok == true) {
app.recent.removeWhere((p) => p.id == page.id);
app.replaceWithId(page.id, page.title);
}
}
Future<void> _toNote(BuildContext context) async {
final app = AppScope.read(context);
final messenger = ScaffoldMessenger.of(context);
try {
await app.queue.run(
() => app.backend.convertToNote(page.id),
report: false,
);
app.reload();
} catch (e) {
messenger.showSnackBar(SnackBar(content: Text(errorText(e))));
}
}
@override
Widget build(BuildContext context) => PopupMenuButton<String>(
key: const ValueKey('page-menu'),
icon: Icon(Icons.more_horiz_rounded, color: context.colors.faint),
tooltip: 'More',
onSelected: (v) => switch (v) {
'hub' => _toHub(context),
'note' => _toNote(context),
_ => _addToHub(context),
},
itemBuilder: (_) => [
if (!page.isHub)
const PopupMenuItem(value: 'hub', child: Text('Convert to hub…')),
if (page.isHub)
const PopupMenuItem(value: 'note', child: Text('Convert to note')),
const PopupMenuItem(value: 'add', child: Text('Add to hub…')),
],
);
}
/// "Namespace" listing (title-kin children) under the header.
class _NamespaceSection extends StatelessWidget {
const _NamespaceSection({required this.structure});
final PageStructure structure;
@override
Widget build(BuildContext context) {
final colors = context.colors;
final app = AppScope.read(context);
final st = structure;
if (st.nsChildren.isEmpty) return const SizedBox.shrink();
return Padding(
padding: const EdgeInsets.only(bottom: 18),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SectionLabel(
'Namespace',
trailing: Text(
'${st.nsChildren.length}',
style: TextStyle(fontSize: 11, color: colors.faint),
),
),
const SizedBox(height: 8),
Wrap(
children: [
for (final c in st.nsChildren)
SizedBox(
width: 230,
child: InkWell(
borderRadius: BorderRadius.circular(8),
onTap: () => c.id != null
? app.openId(c.id!)
: app.openTitle(c.title),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 6,
),
child: Row(
children: [
Icon(
Icons.account_tree_outlined,
size: 16,
color: colors.accent.withAlpha(0xCC),
),
const SizedBox(width: 8),
Expanded(
child: Text(
c.title.split('/').last,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13.5,
color: colors.ink,
),
),
),
],
),
),
),
),
],
),
],
),
);
}
}
+273
View File
@@ -0,0 +1,273 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../state/app_state.dart';
import '../state/keymap.dart';
import '../theme/theme.dart';
import '../widgets/common.dart';
/// Theme picker and key bindings.
class SettingsView extends StatelessWidget {
const SettingsView({super.key});
@override
Widget build(BuildContext context) {
final app = AppScope.of(context);
final colors = context.colors;
return LayoutBuilder(
builder: (context, box) => ListView(
padding: EdgeInsets.fromLTRB(
sidePadding(box.maxWidth),
36,
sidePadding(box.maxWidth),
80,
),
children: [
Text('Settings', style: Theme.of(context).textTheme.headlineLarge),
const SizedBox(height: 28),
_Heading('Theme'),
Wrap(
spacing: 12,
runSpacing: 12,
children: [
_ThemeCard(
id: autoThemeId,
label: 'System',
swatch: [
SynapseColors.light.paper,
SynapseColors.dark.paper,
SynapseColors.light.accent,
SynapseColors.dark.accent,
],
selected: app.themeId == autoThemeId,
),
for (final t in appThemes)
_ThemeCard(
id: t.id,
label: t.label,
swatch: [
t.colors.paper,
t.colors.surface,
t.colors.accent,
t.colors.ref,
],
selected: app.themeId == t.id,
),
],
),
const SizedBox(height: 36),
Row(
children: [
Expanded(child: _Heading('Keyboard shortcuts')),
TextLink(
'Reset all',
icon: Icons.restart_alt_rounded,
onTap: () => app.resetKey(null),
),
],
),
Text(
'Click a shortcut, then press the new combination. Esc cancels.',
style: TextStyle(fontSize: 13, color: colors.muted),
),
const SizedBox(height: 10),
for (final editor in [false, true]) ...[
Padding(
padding: const EdgeInsets.only(top: 14, bottom: 4),
child: Text(
editor ? 'EDITOR' : 'APP',
style: Theme.of(context).textTheme.labelSmall,
),
),
for (final a in AppAction.values.where((a) => a.editor == editor))
_BindingRow(action: a),
],
const SizedBox(height: 28),
Text(
'Type "/" in a block for commands (link, bold, headings, todo, ...). '
'Prefix a character with a backslash to show it literally: \\*not italic\\*.',
style: TextStyle(fontSize: 13, color: colors.muted),
),
],
),
);
}
}
class _Heading extends StatelessWidget {
const _Heading(this.text);
final String text;
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Text(text, style: Theme.of(context).textTheme.headlineSmall),
);
}
class _ThemeCard extends StatelessWidget {
const _ThemeCard({
required this.id,
required this.label,
required this.swatch,
required this.selected,
});
final String id;
final String label;
final List<Color> swatch;
final bool selected;
@override
Widget build(BuildContext context) {
final colors = context.colors;
return InkWell(
key: ValueKey('theme-$id'),
borderRadius: BorderRadius.circular(10),
onTap: () => AppScope.read(context).setTheme(id),
child: Container(
width: 132,
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: selected ? colors.accent : colors.line,
width: selected ? 2 : 1,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Row(
children: [
for (final c in swatch)
Expanded(child: Container(height: 28, color: c)),
],
),
),
const SizedBox(height: 8),
Text(
label,
style: TextStyle(
fontSize: 13,
fontWeight: selected ? FontWeight.w600 : FontWeight.w400,
color: colors.ink,
),
),
],
),
),
);
}
}
class _BindingRow extends StatefulWidget {
const _BindingRow({required this.action});
final AppAction action;
@override
State<_BindingRow> createState() => _BindingRowState();
}
class _BindingRowState extends State<_BindingRow> {
final _focus = FocusNode();
bool _listening = false;
String? _conflict;
@override
void dispose() {
_focus.dispose();
super.dispose();
}
KeyEventResult _onKey(FocusNode _, KeyEvent e) {
if (!_listening || e is! KeyDownEvent) return KeyEventResult.ignored;
if (e.logicalKey == LogicalKeyboardKey.escape) {
setState(() => _listening = false);
return KeyEventResult.handled;
}
final kb = HardwareKeyboard.instance;
final combo = Combo(
e.logicalKey,
ctrl: kb.isControlPressed || kb.isMetaPressed,
shift: kb.isShiftPressed,
alt: kb.isAltPressed,
);
if (combo.isModifierOnly) return KeyEventResult.handled;
final owner = AppScope.read(context).bindKey(widget.action, combo);
setState(() {
_listening = false;
_conflict = owner == null ? null : 'Already used by "${owner.label}"';
});
return KeyEventResult.handled;
}
@override
Widget build(BuildContext context) {
final app = AppScope.of(context);
final colors = context.colors;
final a = widget.action;
return Focus(
focusNode: _focus,
onKeyEvent: _onKey,
onFocusChange: (f) {
if (!f && _listening) setState(() => _listening = false);
},
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 3),
child: Row(
children: [
Expanded(
child: Text(
a.label,
style: TextStyle(fontSize: 14, color: colors.ink),
),
),
if (_conflict != null)
Padding(
padding: const EdgeInsets.only(right: 12),
child: Text(
_conflict!,
style: TextStyle(fontSize: 12, color: colors.ref),
),
),
OutlinedButton(
key: ValueKey('bind-${a.name}'),
style: OutlinedButton.styleFrom(
minimumSize: const Size(120, 32),
side: BorderSide(
color: _listening ? colors.accent : colors.line,
),
foregroundColor: colors.ink,
),
onPressed: () {
setState(() {
_listening = true;
_conflict = null;
});
_focus.requestFocus();
},
child: Text(
_listening ? 'Press keys…' : app.keymap.of(a).label,
style: TextStyle(
fontSize: 12.5,
color: app.keymap.isCustom(a) ? colors.accent : colors.ink,
),
),
),
IconButton(
tooltip: 'Reset',
iconSize: 16,
visualDensity: VisualDensity.compact,
color: colors.faint,
onPressed: app.keymap.isCustom(a) ? () => app.resetKey(a) : null,
icon: const Icon(Icons.restart_alt_rounded),
),
],
),
),
);
}
}
+72 -50
View File
@@ -1,14 +1,17 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../state/app_state.dart';
import '../state/keymap.dart';
import '../theme/theme.dart';
import '../widgets/dates.dart';
import 'all_pages_view.dart';
import 'journals_view.dart';
import 'page_screen.dart';
import 'hubs_tree.dart';
import 'quick_switcher.dart';
import 'graph_view.dart';
import 'settings_view.dart';
/// App frame: sidebar (navigation, recents, theme), top bar and the current view.
class Shell extends StatefulWidget {
@@ -39,39 +42,21 @@ class _ShellState extends State<Shell> {
);
});
}
final actions = <AppAction, VoidCallback>{
AppAction.quickSwitcher: () => showQuickSwitcher(context),
AppAction.journals: () => app.go(const JournalsRoute()),
AppAction.graph: () => app.go(const GraphRoute(GraphMode.network)),
AppAction.timeline: () => app.go(const TimelineRoute()),
AppAction.sidebar: () => setState(() => _sidebar = !_sidebar),
AppAction.pageSidebar: app.togglePageSidebar,
AppAction.settings: () => app.go(const SettingsRoute()),
AppAction.back: app.back,
AppAction.forward: app.forward,
};
return CallbackShortcuts(
bindings: {
const SingleActivator(LogicalKeyboardKey.keyK, control: true): () =>
showQuickSwitcher(context),
const SingleActivator(LogicalKeyboardKey.keyK, meta: true): () =>
showQuickSwitcher(context),
const SingleActivator(
LogicalKeyboardKey.keyJ,
control: true,
shift: true,
): () =>
app.go(const JournalsRoute()),
const SingleActivator(
LogicalKeyboardKey.keyG,
control: true,
shift: true,
): () =>
app.go(const GraphRoute(GraphMode.network)),
const SingleActivator(
LogicalKeyboardKey.keyT,
control: true,
shift: true,
): () =>
app.go(const TimelineRoute()),
const SingleActivator(
LogicalKeyboardKey.backslash,
control: true,
): () =>
setState(() => _sidebar = !_sidebar),
const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true):
app.back,
const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true):
app.forward,
for (final e in actions.entries)
...Map.fromEntries(activators(app.keymap.of(e.key), e.value)),
},
child: Focus(
autofocus: true,
@@ -125,6 +110,7 @@ class _ShellState extends State<Shell> {
focusId: route.focusId,
),
AllPagesRoute() => const AllPagesView(),
SettingsRoute() => const SettingsView(),
PageTarget() => PageScreen(target: route),
},
),
@@ -164,15 +150,19 @@ class _TopBar extends StatelessWidget {
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Row(
children: [
icon(Icons.menu_rounded, 'Toggle sidebar (Ctrl+\\)', onMenu),
icon(
Icons.menu_rounded,
'Toggle sidebar (${app.keymap.of(AppAction.sidebar).label})',
onMenu,
),
icon(
Icons.arrow_back_rounded,
'Back (Alt+←)',
'Back (${app.keymap.of(AppAction.back).label})',
app.canGoBack ? app.back : null,
),
icon(
Icons.arrow_forward_rounded,
'Forward (Alt+→)',
'Forward (${app.keymap.of(AppAction.forward).label})',
app.canGoForward ? app.forward : null,
),
const Spacer(),
@@ -214,7 +204,10 @@ class _SearchPill extends StatelessWidget {
const SizedBox(width: 8),
Text('Search', style: TextStyle(fontSize: 13, color: colors.muted)),
const SizedBox(width: 18),
Text('Ctrl K', style: TextStyle(fontSize: 11, color: colors.faint)),
Text(
AppScope.of(context).keymap.of(AppAction.quickSwitcher).label,
style: TextStyle(fontSize: 11, color: colors.faint),
),
],
),
),
@@ -275,31 +268,34 @@ class _Sidebar extends StatelessWidget {
selected: route is GraphRoute,
onTap: () => go(const GraphRoute(GraphMode.network)),
),
_NavItem(
icon: Icons.timeline_rounded,
label: 'Timeline',
selected: route is TimelineRoute,
onTap: () => go(const TimelineRoute()),
),
_NavItem(
icon: Icons.description_outlined,
label: 'All pages',
selected: route is AllPagesRoute,
onTap: () => go(const AllPagesRoute()),
),
const SizedBox(height: 22),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Text(
'RECENT',
style: Theme.of(context).textTheme.labelSmall,
),
_NavItem(
icon: Icons.settings_outlined,
label: 'Settings',
selected: route is SettingsRoute,
onTap: () => go(const SettingsRoute()),
),
const SizedBox(height: 6),
const SizedBox(height: 22),
Expanded(
child: ListView(
padding: EdgeInsets.zero,
children: [
HubsSection(
selectedId: route is PageTarget ? route.id : null,
onOpen: (id) => go(PageTarget(id: id)),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 6),
child: Text(
'RECENT',
style: Theme.of(context).textTheme.labelSmall,
),
),
for (final p in app.recent)
_NavItem(
label: p.isJournal ? longDate(p.title) : p.title,
@@ -418,3 +414,29 @@ class _Logo extends CustomPainter {
@override
bool shouldRepaint(_Logo old) => old.color != color;
}
/// The shortcut activators for `combo` (Ctrl also answers to Cmd on macOS).
List<MapEntry<ShortcutActivator, VoidCallback>> activators(
Combo combo,
VoidCallback run,
) => [
MapEntry(
SingleActivator(
combo.key,
control: combo.ctrl,
shift: combo.shift,
alt: combo.alt,
),
run,
),
if (combo.ctrl && defaultTargetPlatform == TargetPlatform.macOS)
MapEntry(
SingleActivator(
combo.key,
meta: true,
shift: combo.shift,
alt: combo.alt,
),
run,
),
];
+251
View File
@@ -0,0 +1,251 @@
import 'package:flutter/material.dart';
import '../theme/theme.dart';
/// A page offered by [showPagePicker].
class PickItem {
const PickItem({required this.id, required this.title, this.isHub = false});
final String id;
final String title;
final bool isHub;
}
/// The outcome of [showPagePicker]: an existing page, or a title to create.
class PickResult {
const PickResult.existing(PickItem this.item)
: newTitle = null,
newHub = false;
const PickResult.create(String this.newTitle, {required this.newHub})
: item = null;
final PickItem? item;
final String? newTitle;
final bool newHub;
}
/// Search-as-you-type page picker. [search] returns candidates for the query (empty
/// query included). Creation rows are offered for a non-empty query without an exact match.
Future<PickResult?> showPagePicker(
BuildContext context, {
required String heading,
required Future<List<PickItem>> Function(String query) search,
bool canCreateNote = false,
bool canCreateHub = false,
}) => showDialog<PickResult>(
context: context,
builder: (_) => _PagePicker(
heading: heading,
search: search,
canCreateNote: canCreateNote,
canCreateHub: canCreateHub,
),
);
class _PagePicker extends StatefulWidget {
const _PagePicker({
required this.heading,
required this.search,
required this.canCreateNote,
required this.canCreateHub,
});
final String heading;
final Future<List<PickItem>> Function(String) search;
final bool canCreateNote;
final bool canCreateHub;
@override
State<_PagePicker> createState() => _PagePickerState();
}
class _PagePickerState extends State<_PagePicker> {
final _text = TextEditingController();
List<PickItem> _items = const [];
int _seq = 0;
@override
void initState() {
super.initState();
_query('');
}
@override
void dispose() {
_text.dispose();
super.dispose();
}
Future<void> _query(String q) async {
final n = ++_seq;
final r = await widget.search(q.trim());
if (mounted && n == _seq) setState(() => _items = r);
}
@override
Widget build(BuildContext context) {
final colors = context.colors;
final q = _text.text.trim();
final exact = _items.any((i) => i.title.toLowerCase() == q.toLowerCase());
final create = q.isNotEmpty && !exact;
Widget row(IconData icon, String label, VoidCallback onTap, {Key? key}) =>
ListTile(
key: key,
dense: true,
leading: Icon(icon, size: 18, color: colors.accent),
title: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis),
onTap: onTap,
);
return AlertDialog(
title: Text(widget.heading),
content: SizedBox(
width: 420,
height: 380,
child: Column(
children: [
TextField(
controller: _text,
autofocus: true,
decoration: const InputDecoration(hintText: 'Search pages'),
onChanged: _query,
),
const SizedBox(height: 8),
Expanded(
child: ListView(
children: [
if (create && widget.canCreateNote)
row(
Icons.add_rounded,
'Create note "$q"',
() => Navigator.pop(
context,
PickResult.create(q, newHub: false),
),
),
if (create && widget.canCreateHub)
row(
Icons.create_new_folder_outlined,
'Create hub "$q"',
() => Navigator.pop(
context,
PickResult.create(q, newHub: true),
),
),
for (final i in _items)
row(
i.isHub
? Icons.folder_outlined
: Icons.description_outlined,
i.title,
() => Navigator.pop(context, PickResult.existing(i)),
key: ValueKey('pick-${i.id}'),
),
],
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
],
);
}
}
/// Asks for a name. [submit] runs on confirm; when it throws, the message is shown inline
/// and the dialog stays open. Returns what [submit] returned.
Future<T?> showNameDialog<T>(
BuildContext context, {
required String heading,
required String confirm,
required Future<T> Function(String name) submit,
String hint = 'Title',
}) => showDialog<T>(
context: context,
builder: (_) => _NameDialog<T>(
heading: heading,
confirm: confirm,
submit: submit,
hint: hint,
),
);
class _NameDialog<T> extends StatefulWidget {
const _NameDialog({
required this.heading,
required this.confirm,
required this.submit,
required this.hint,
});
final String heading;
final String confirm;
final String hint;
final Future<T> Function(String) submit;
@override
State<_NameDialog<T>> createState() => _NameDialogState<T>();
}
class _NameDialogState<T> extends State<_NameDialog<T>> {
final _text = TextEditingController();
String? _error;
bool _busy = false;
@override
void dispose() {
_text.dispose();
super.dispose();
}
Future<void> _go() async {
final name = _text.text.trim();
if (name.isEmpty || _busy) return;
setState(() {
_busy = true;
_error = null;
});
try {
final r = await widget.submit(name);
if (mounted) Navigator.pop(context, r);
} catch (e) {
if (mounted) {
setState(() {
_busy = false;
_error = errorText(e);
});
}
}
}
@override
Widget build(BuildContext context) => AlertDialog(
title: Text(widget.heading),
content: SizedBox(
width: 380,
child: TextField(
controller: _text,
autofocus: true,
decoration: InputDecoration(hintText: widget.hint, errorText: _error),
onSubmitted: (_) => _go(),
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(onPressed: _go, child: Text(widget.confirm)),
],
);
}
/// A readable message for an exception coming back from the core.
String errorText(Object e) {
var s = '$e';
for (final p in ['Exception: ', 'AnyhowException(', 'PanicException(']) {
if (s.startsWith(p)) s = s.substring(p.length);
}
if (s.endsWith(')') && !s.contains('(')) s = s.substring(0, s.length - 1);
return s.trim();
}
+365
View File
@@ -0,0 +1,365 @@
import 'package:flutter/material.dart';
import '../backend/graph_backend.dart';
import '../state/app_state.dart';
import '../theme/theme.dart';
import 'common.dart';
import 'pickers.dart';
/// Type and tag chips of a page, each with a remove button, and "Type" / "Tag" links that open
/// a picker. Types are plain names; tags are pages (tapping one opens it). Tag pages cannot
/// be tagged, so they only get types.
class TagBar extends StatelessWidget {
const TagBar({super.key, required this.page});
final PageDto page;
Future<void> _run(
BuildContext context,
Future<PageDto> Function(GraphBackend b) op,
) async {
final app = AppScope.read(context);
final messenger = ScaffoldMessenger.of(context);
try {
await app.queue.run(() => op(app.backend), report: false);
app.reload();
} catch (e) {
messenger.showSnackBar(SnackBar(content: Text(errorText(e))));
}
}
Future<void> _add(BuildContext context, {required bool type}) async {
final app = AppScope.read(context);
final catalog = type
? await app.backend.typeCatalog()
: await app.backend.tagCatalog();
if (!context.mounted) return;
final name = await showDialog<String>(
context: context,
builder: (_) => _TagPicker(
catalog: catalog,
taken: type ? page.types : page.tags,
label: type ? 'type' : 'tag',
),
);
if (name == null || !context.mounted) return;
await _run(
context,
(b) => type ? b.addPageType(page.id, name) : b.addPageTag(page.id, name),
);
}
Widget _chip(
BuildContext context,
String keyId,
String name, {
VoidCallback? onTap,
required VoidCallback onRemove,
}) {
final colors = context.colors;
return Container(
key: ValueKey(keyId),
padding: const EdgeInsets.only(left: 9, right: 3),
decoration: BoxDecoration(
color: colors.surface,
borderRadius: BorderRadius.circular(20),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 3),
child: Text(
name,
style: TextStyle(fontSize: 12, color: colors.muted),
),
),
),
InkResponse(
key: ValueKey('un$keyId'),
radius: 10,
onTap: onRemove,
child: Padding(
padding: const EdgeInsets.all(4),
child: Icon(Icons.close_rounded, size: 12, color: colors.faint),
),
),
],
),
);
}
Widget _row(
BuildContext context,
IconData icon,
String label,
List<Widget> chips,
Widget add,
) {
final colors = context.colors;
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 76,
child: Padding(
padding: const EdgeInsets.only(top: 4),
child: Row(
children: [
Icon(icon, size: 13, color: colors.faint),
const SizedBox(width: 5),
Text(
label,
style: TextStyle(fontSize: 12, color: colors.faint),
),
],
),
),
),
Expanded(
child: Wrap(
spacing: 6,
runSpacing: 6,
crossAxisAlignment: WrapCrossAlignment.center,
children: [...chips, add],
),
),
],
);
}
@override
Widget build(BuildContext context) {
final app = AppScope.read(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_row(
context,
Icons.category_outlined,
'Type',
[
for (final t in page.types)
_chip(
context,
'type-$t',
t,
onRemove: () =>
_run(context, (b) => b.removePageType(page.id, t)),
),
],
TextLink(
'+ add',
key: const ValueKey('add-type'),
onTap: () => _add(context, type: true),
style: const TextStyle(fontSize: 12),
),
),
if (!page.isTag) ...[
const SizedBox(height: 6),
_row(
context,
Icons.sell_outlined,
'Tags',
[
for (final t in page.tags)
_chip(
context,
'tag-$t',
'#$t',
onTap: () => app.openTitle(t),
onRemove: () =>
_run(context, (b) => b.removePageTag(page.id, t)),
),
],
TextLink(
'+ add',
key: const ValueKey('add-tag'),
onTap: () => _add(context, type: false),
style: const TextStyle(fontSize: 12),
),
),
],
],
);
}
}
/// Notes carrying the tag page `tag`, as links under the header of the tag page.
class TaggedNotes extends StatelessWidget {
const TaggedNotes({super.key, required this.tag});
final String tag;
@override
Widget build(BuildContext context) {
final app = AppScope.read(context);
final colors = context.colors;
return FutureBuilder<List<PageBrief>>(
future: app.backend.pagesWithTag(tag),
builder: (context, snap) {
final pages = snap.data ?? const <PageBrief>[];
if (pages.isEmpty) return const SizedBox.shrink();
return Padding(
padding: const EdgeInsets.only(top: 10),
child: Wrap(
key: const ValueKey('tagged-notes'),
spacing: 14,
runSpacing: 4,
children: [
Text(
'Tagged',
style: TextStyle(fontSize: 12, color: colors.faint),
),
for (final p in pages)
TextLink(
p.title,
icon: Icons.description_outlined,
onTap: () => app.openId(p.id),
style: const TextStyle(fontSize: 12),
),
],
),
);
},
);
}
}
/// Lists the pages carrying `tag`; picking one opens it.
Future<void> showTagPages(BuildContext context, String tag) async {
final app = AppScope.read(context);
final pages = await app.backend.pagesWithTag(tag);
if (!context.mounted) return;
await showDialog<void>(
context: context,
builder: (ctx) => AlertDialog(
title: Text(tag),
content: SizedBox(
width: 360,
child: pages.isEmpty
? const Text('No notes with this tag yet.')
: ListView(
shrinkWrap: true,
children: [
for (final p in pages)
ListTile(
dense: true,
leading: Icon(
p.isHub
? Icons.folder_outlined
: Icons.description_outlined,
size: 18,
),
title: Text(p.title),
onTap: () {
Navigator.pop(ctx);
app.openId(p.id);
},
),
],
),
),
),
);
}
class _TagPicker extends StatefulWidget {
const _TagPicker({
required this.catalog,
required this.taken,
required this.label,
});
final List<TagDto> catalog;
final List<String> taken;
final String label;
@override
State<_TagPicker> createState() => _TagPickerState();
}
class _TagPickerState extends State<_TagPicker> {
final _text = TextEditingController();
@override
void dispose() {
_text.dispose();
super.dispose();
}
String get _query => _text.text.trim().replaceFirst(RegExp(r'^#+'), '');
@override
Widget build(BuildContext context) {
final colors = context.colors;
final taken = {for (final t in widget.taken) t.toLowerCase()};
final q = _query.toLowerCase();
final options = [
for (final t in widget.catalog)
if (!taken.contains(t.name.toLowerCase()) &&
t.name.toLowerCase().contains(q))
t,
];
final exact = widget.catalog.any((t) => t.name.toLowerCase() == q);
return AlertDialog(
title: Text('Add ${widget.label}'),
content: SizedBox(
width: 360,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
key: ValueKey('${widget.label}-input'),
controller: _text,
autofocus: true,
decoration: InputDecoration(
hintText: 'Search or type a new ${widget.label}',
),
onChanged: (_) => setState(() {}),
onSubmitted: (_) {
if (_query.isNotEmpty) Navigator.pop(context, _query);
},
),
const SizedBox(height: 12),
Flexible(
child: SingleChildScrollView(
child: Wrap(
spacing: 6,
runSpacing: 6,
children: [
if (_query.isNotEmpty && !exact && !taken.contains(q))
ActionChip(
key: ValueKey('${widget.label}-create'),
avatar: const Icon(Icons.add_rounded, size: 14),
label: Text('Create "$_query"'),
onPressed: () => Navigator.pop(context, _query),
),
for (final t in options)
ActionChip(
key: ValueKey('${widget.label}-opt-${t.name}'),
label: Text(
t.count > 0 ? '${t.name} · ${t.count}' : t.name,
style: TextStyle(
fontSize: 12.5,
color: t.count > 0 ? colors.ink : colors.muted,
),
),
onPressed: () => Navigator.pop(context, t.name),
),
],
),
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
],
);
}
}
+1 -1
View File
@@ -7,7 +7,7 @@ project(runner LANGUAGES CXX)
set(BINARY_NAME "synapse")
# The unique GTK application identifier for this application. See:
# https://wiki.gnome.org/HowDoI/ChooseApplicationID
set(APPLICATION_ID "es.zenvairo.synapse")
set(APPLICATION_ID "dev.dasemu.synapse")
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
+195 -36
View File
@@ -1,5 +1,9 @@
import 'package:flutter/material.dart';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:synapse/src/backend/graph_backend.dart';
import 'package:synapse/src/graph/graph_model.dart';
import 'package:synapse/src/graph/network_canvas.dart';
import 'package:synapse/src/graph/tree_canvas.dart';
@@ -99,10 +103,6 @@ void main() {
testWidgets('switches between every mode', (tester) async {
await pumpGraph(tester, demo());
await mode(tester, 'Local');
expect(find.byKey(const ValueKey('depth')), findsOneWidget);
expect(find.byType(NetworkCanvas), findsOneWidget);
await mode(tester, 'Synapses');
expect(find.text('Pulse'), findsOneWidget);
expect(find.byType(NetworkCanvas), findsOneWidget);
@@ -111,7 +111,7 @@ void main() {
await mode(tester, 'Clusters');
expect(find.byType(NetworkCanvas), findsOneWidget);
await mode(tester, 'Namespaces');
await mode(tester, 'Tree');
expect(find.byType(TreeCanvas), findsOneWidget);
expect(find.byType(NetworkCanvas), findsNothing);
@@ -123,43 +123,88 @@ void main() {
await tester.pump(const Duration(seconds: 1));
});
testWidgets('local mode follows the depth slider', (tester) async {
final b = demo();
// Chain Alpha – Beta – Gamma – Delta.
final g = b.createPage('Gamma');
b.seed(g.id, [(0, '[[Beta]] [[Delta]]')]);
await pumpGraph(tester, b);
await mode(tester, 'Local');
// Focus is the highest-degree page until the user picks one; pick Delta.
await tester.enterText(find.byType(TextField), 'Delta');
await tester.testTextInput.receiveAction(TextInputAction.done);
await settle(tester);
expect(
canvas(tester).nodeCount,
3,
reason: 'Delta, Gamma, Beta at depth 2',
);
final slider = tester.widget<Slider>(find.byKey(const ValueKey('depth')));
slider.onChanged!(1);
await settle(tester);
expect(canvas(tester).nodeCount, 2);
slider.onChanged!(3);
await settle(tester);
expect(canvas(tester).nodeCount, 5, reason: 'adds Alpha and topic');
});
test('namespace tree groups a/b titles and tags', () async {
test('tree groups a/b titles and tags', () async {
final model = GraphModel(await demo().graphData());
final root = buildNamespaceTree(model);
final labels = root.children.map((c) => c.label).toList();
expect(labels, ['Namespaces', 'Tags']);
expect(root.children[0].children.single.label, 'proj');
expect(root.children[0].children.single.children.single.label, 'one');
final topic = root.children[1].children.single;
TreeItem branch(String l) => root.children.firstWhere((c) => c.label == l);
// Hubs are covered by the hubs group below; notes in no hub hang off the centre.
// Namespaces have no node of their own: `proj` hangs off the centre.
expect(root.children.map((c) => c.label), [
'Alpha',
'Beta',
'Lonely',
'proj',
'Tags',
'topic',
]);
expect(branch('proj').children.single.label, 'one');
final topic = branch('Tags').children.single;
expect(topic.label, '#topic');
expect(topic.children.map((c) => c.label).toSet(), {'Alpha', 'Beta'});
});
test(
'tree centre carries the store name; sibling branches get distinct hues',
() async {
final model = GraphModel(await demo().graphData());
final root = buildNamespaceTree(model, name: 'Mi almacén');
expect(root.label, 'Mi almacén');
final arms = root.children;
expect(arms.length, greaterThan(1));
// Arms are evenly spread over the hue circle.
final gap = arms[1].hue - arms[0].hue;
expect(gap, closeTo(360 / arms.length, 1e-9));
// Children split their parent's sector evenly and stay inside it.
for (final a in arms) {
final k = a.children.length;
for (var j = 1; j < k; j++) {
expect(
a.children[j].hue - a.children[j - 1].hue,
closeTo(a.span / k, 1e-9),
);
}
for (final c in a.children) {
expect((c.hue - a.hue).abs(), lessThanOrEqualTo(a.span / 2));
}
}
},
);
test('tag grouping uses each page\'s most used tag', () {
GraphNode n(String t, List<String> tags) => GraphNode(
id: t,
title: t,
createdAt: 0,
degree: 1,
backlinks: 0,
cluster: 0,
isHub: false,
tags: tags,
);
final m = GraphModel(
GraphData(
nodes: [
n('a', ['Tecnología', 'idea']),
n('b', ['tecnología']),
n('c', ['idea', 'lugar']),
n('d', []),
],
sources: Uint32List(0),
targets: Uint32List(0),
kinds: Uint8List(0),
weights: Float32List(0),
seq: 0,
),
);
// Tie (two pages each): alphabetical.
expect(m.homeTag(0), 'idea');
expect(m.homeTag(2), 'idea');
expect(m.homeTag(3), isNull);
expect(m.tagGroups, ['idea', 'tecnología']);
expect(m.tagLabel('tecnología'), 'Tecnología');
expect(m.tagSprings([0, 1, 2, 3]).map((s) => (s.$1, s.$2)), [(2, 0)]);
});
test('filter by tag, query and min degree', () async {
final model = GraphModel(await demo().graphData());
String t(int i) => model.node(i).title;
@@ -212,4 +257,118 @@ void main() {
expect(hull.length, 4);
expect(hull.contains(const Offset(5, 5)), isFalse);
});
group('hubs', () {
// Media (hub) -> TV (hub) -> Anime (page); Media -> Books; Notes (page) in Media;
// a TV -> Media CONTAINS edge (a cycle the tree must survive); a journal (never a member).
GraphData hubData() {
GraphNode n(
String id,
String title, {
bool hub = false,
int? home,
String? journal,
}) => GraphNode(
id: id,
title: title,
journalDate: journal,
createdAt: 0,
degree: 1,
backlinks: 0,
cluster: 0,
isHub: hub,
homeHub: home,
tags: const [],
);
final nodes = [
n('0', 'Media', hub: true, home: 0),
n('1', 'TV', hub: true, home: 1),
n('2', 'Anime', home: 1),
n('3', 'Books', home: 0),
n('4', 'Notes', home: 0),
n('5', '2024-01-01', journal: '2024-01-01'),
];
// (source, target, kind)
final edges = [
(0, 1, 7), // Media contains TV
(0, 3, 7), // Media contains Books
(0, 4, 7), // Media contains Notes
(1, 2, 7), // TV contains Anime
(1, 0, 7), // TV contains Media (cycle)
(0, 5, 0), // Media -> journal link: a link never makes a member
];
return GraphData(
nodes: nodes,
sources: Uint32List.fromList([for (final e in edges) e.$1]),
targets: Uint32List.fromList([for (final e in edges) e.$2]),
kinds: Uint8List.fromList([for (final e in edges) e.$3]),
weights: Float32List.fromList([for (final _ in edges) 1.0]),
seq: 1,
);
}
GraphModel hubModel() => GraphModel(hubData());
test('hub members are the CONTAINS targets', () {
final m = hubModel();
expect(EdgeKind.values[7], EdgeKind.contains);
expect(EdgeKind.contains.structural, isTrue);
expect(EdgeKind.values[8], EdgeKind.tagged);
expect(const GraphFilter().kinds, contains(EdgeKind.tagged));
expect(m.hubMembers[0], {1, 3, 4});
expect(m.hubMembers[1], {2, 0});
expect(m.hubOrder.first, 0, reason: 'Media is home hub of most pages');
expect(m.hubRank[1], 1);
});
test('contains is a default filter kind', () {
expect(const GraphFilter().kinds, contains(EdgeKind.contains));
});
test('hub springs pull members to their home hub', () {
final m = hubModel();
expect(m.hubSprings([0, 1, 2, 3, 4, 5]), [
(2, 1, 0.6),
(3, 0, 0.6),
(4, 0, 0.6),
]);
});
test('tree hubs hang off the centre, cycle-safe', () {
final root = buildNamespaceTree(hubModel());
// Media is a member of TV and TV of Media: no root hub, both still placed once.
expect(root.children.where((c) => c.label == 'Hubs'), isEmpty);
final media = root.children.firstWhere((c) => c.label == 'Media');
expect(media.isHub, isTrue);
expect(media.children.map((c) => c.label).toSet(), {
'TV',
'Books',
'Notes',
});
final tv = media.children.firstWhere((c) => c.label == 'TV');
expect(tv.isHub, isTrue);
// Media already on the path: a leaf, not an endless loop.
expect(tv.children.map((c) => c.label).toSet(), {'Anime', 'Media'});
expect(
tv.children.firstWhere((c) => c.label == 'Media').children,
isEmpty,
);
});
testWidgets('clusters mode groups by hub by default', (tester) async {
await pumpGraph(tester, _HubBackend(hubData()));
await mode(tester, 'Clusters');
expect(find.byKey(const ValueKey('cluster-group')), findsOneWidget);
expect(find.text('Group: hubs'), findsOneWidget);
});
});
}
/// A memory backend whose graph data is fixed (so tests don't depend on its demo graph).
class _HubBackend extends MemoryBackend {
_HubBackend(this._data);
final GraphData _data;
@override
Future<GraphData> graphData() async => _data;
}
+576
View File
@@ -0,0 +1,576 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:synapse/src/backend/graph_backend.dart';
import 'package:synapse/src/state/app_state.dart';
import 'package:synapse/src/theme/theme.dart';
import 'package:synapse/src/views/all_pages_view.dart';
import 'package:synapse/src/views/graph_view.dart';
import 'package:synapse/src/views/shell.dart';
import 'support/memory_backend.dart';
/// Fun (hub) -> Fun/TV (sub-hub) -> Anime, Movies, Shows; Fun also holds Games and Books.
MemoryBackend demo() {
final b = MemoryBackend();
final fun = b.addHub('Fun', 'Things for the weekend');
final tv = b.addHub('Fun/TV');
b.hubsOfPage[tv.id] = {fun.id};
for (final t in ['Games', 'Books']) {
b.hubsOfPage[b.createPage(t).id] = {fun.id};
}
for (final t in ['Anime', 'Movies', 'Shows']) {
b.hubsOfPage[b.createPage(t).id] = {tv.id};
}
return b;
}
PageDto byTitle(MemoryBackend b, String t) =>
b.pages.values.firstWhere((p) => p.title == t);
Future<AppState> pump(
WidgetTester tester,
MemoryBackend b, {
Widget home = const Shell(),
AppRoute? route,
}) async {
tester.view.physicalSize = const Size(1600, 1000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final app = AppState(b);
if (route != null) app.go(route);
await tester.pumpWidget(
AppScope(
state: app,
child: MaterialApp(theme: buildTheme(Brightness.light), home: home),
),
);
await settle(tester);
return app;
}
Future<void> settle(WidgetTester tester) async {
for (var i = 0; i < 6; i++) {
await tester.pump(const Duration(milliseconds: 50));
}
}
void main() {
tagTests();
testWidgets('all pages hides hubs and sorts by title', (tester) async {
await pump(tester, demo(), home: const Scaffold(body: AllPagesView()));
expect(find.text('Fun'), findsNothing);
expect(find.text('Games'), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('page-sort')));
await settle(tester);
await tester.tap(find.text('Title').last);
await settle(tester);
// Title sort is A-Z by default... descending arrow means newest/Z-A; flip to A-Z first.
await tester.tap(find.byKey(const ValueKey('page-sort-direction')));
await settle(tester);
final ys = [
for (final t in ['Anime', 'Books', 'Games', 'Movies', 'Shows'])
tester.getTopLeft(find.text(t)).dy,
];
expect(ys, [...ys]..sort());
});
testWidgets('page sidebar with the local graph toggles', (tester) async {
final b = demo();
final app = await pump(tester, b);
app.openId(byTitle(b, 'Games').id);
await settle(tester);
expect(find.byType(LocalGraphPanel), findsNothing);
await tester.tap(find.byKey(const ValueKey('page-sidebar-toggle')));
await settle(tester);
expect(find.byType(LocalGraphPanel), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('page-sidebar-toggle')));
await settle(tester);
expect(find.byType(LocalGraphPanel), findsNothing);
});
testWidgets('sidebar hubs start collapsed and only list sub-hubs', (
tester,
) async {
await pump(tester, demo());
expect(find.text('HUBS'), findsOneWidget);
expect(find.text('Fun'), findsOneWidget);
expect(find.text('Fun/TV'), findsNothing);
await tester.tap(find.byIcon(Icons.chevron_right_rounded));
await settle(tester);
expect(find.text('Fun/TV'), findsOneWidget);
// Notes are never children in the sidebar.
expect(find.text('Games'), findsNothing);
expect(find.text('Anime'), findsNothing);
});
testWidgets('new note from a hub starts from its template', (tester) async {
final b = demo();
final hub = byTitle(b, 'Fun');
final t = await b.hubTemplate(hub.id);
b.seed(t, [(0, 'Rating'), (1, 'Notes')]);
final p = await b.createPageFromTemplate(hub.id, 'Chess');
expect(b.outlines[p.id]!.map((n) => n.content), ['Rating', 'Notes']);
expect(b.hubsOfPage[p.id], contains(hub.id));
});
testWidgets(
'sidebar shows HUBS with a plus even without hubs; plus creates',
(tester) async {
final b = MemoryBackend()..createPage('Solo');
await pump(tester, b);
expect(find.text('HUBS'), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('new-hub')));
await settle(tester);
await tester.enterText(find.byType(TextField), 'Projects');
await tester.tap(find.text('Create'));
await settle(tester);
final hub = byTitle(b, 'Projects');
expect(hub.isHub, isTrue);
// The new hub opens as a hub screen.
expect(find.byKey(const ValueKey('hub-description')), findsOneWidget);
},
);
testWidgets('new hub with a taken title shows the error inline', (
tester,
) async {
await pump(tester, demo());
await tester.tap(find.byKey(const ValueKey('new-hub')));
await settle(tester);
await tester.enterText(find.byType(TextField), 'Games');
await tester.tap(find.text('Create'));
await settle(tester);
expect(find.textContaining('already exists'), findsOneWidget);
});
testWidgets(
'hub screen lists sub-hubs first, removes members, saves description',
(tester) async {
final b = demo();
final fun = byTitle(b, 'Fun');
await pump(tester, b, route: PageTarget(id: fun.id));
expect(find.byKey(const ValueKey('hub-description')), findsOneWidget);
expect(find.text('Things for the weekend'), findsOneWidget);
expect(find.text('MEMBERS'), findsOneWidget);
// Sub-hub row comes before the notes.
final rows = find.byWidgetPredicate(
(w) =>
w.key is ValueKey &&
'${(w.key as ValueKey).value}'.startsWith('member-'),
);
expect(rows, findsNWidgets(3));
final ys = [
for (final t in ['Fun/TV', 'Books', 'Games'])
tester
.getTopLeft(find.descendant(of: rows, matching: find.text(t)))
.dy,
];
expect(ys, orderedEquals([...ys]..sort()));
// Remove Books (the × shows on hover).
final books = byTitle(b, 'Books');
final gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: Offset.zero);
addTearDown(gesture.removePointer);
await gesture.moveTo(
tester.getCenter(
find.descendant(
of: find.byKey(ValueKey('member-${books.id}')),
matching: find.text('Books'),
),
),
);
await settle(tester);
await tester.tap(find.byKey(ValueKey('remove-${books.id}')));
await settle(tester);
expect(b.hubsOfPage[books.id], isEmpty);
expect(find.text('Books'), findsNothing);
// Description is saved on blur.
await tester.enterText(
find.byKey(const ValueKey('hub-description')),
'New text',
);
await tester.testTextInput.receiveAction(TextInputAction.done);
FocusManager.instance.primaryFocus?.unfocus();
await settle(tester);
expect(b.pages[fun.id]!.description, 'New text');
},
);
testWidgets('hub screen adds an existing note and creates a sub-hub', (
tester,
) async {
final b = demo();
final lone = b.createPage('Lonely');
final fun = byTitle(b, 'Fun');
await pump(tester, b, route: PageTarget(id: fun.id));
await tester.tap(find.text('Add'));
await settle(tester);
await tester.enterText(find.byType(TextField).last, 'Lone');
await settle(tester);
await tester.tap(find.byKey(ValueKey('pick-${lone.id}')));
await settle(tester);
expect(b.hubsOfPage[lone.id], {fun.id});
await tester.tap(find.text('Add'));
await settle(tester);
await tester.enterText(find.byType(TextField).last, 'Music');
await settle(tester);
await tester.tap(find.text('Create hub "Music"'));
await settle(tester);
final music = byTitle(b, 'Music');
expect(music.isHub, isTrue);
expect(b.hubsOfPage[music.id], {fun.id});
});
testWidgets('a hub cannot be added below itself (cycle error shown)', (
tester,
) async {
final b = demo();
final fun = byTitle(b, 'Fun');
final tv = byTitle(b, 'Fun/TV');
await pump(tester, b, route: PageTarget(id: tv.id));
await tester.tap(find.byKey(const ValueKey('page-menu')));
await settle(tester);
await tester.tap(find.text('Add to hub…'));
await settle(tester);
// Fun is already a parent, so it is not offered; the hub itself neither.
expect(find.byKey(ValueKey('pick-${fun.id}')), findsNothing);
await tester.tap(find.text('Cancel'));
await settle(tester);
// Adding Fun under Fun/TV is rejected by the backend.
expect(() => b.addToHub(fun.id, tv.id), throwsException);
});
testWidgets('note page: In chips can be removed, no hub pill', (
tester,
) async {
final b = demo();
final games = byTitle(b, 'Games');
final fun = byTitle(b, 'Fun');
await pump(tester, b, route: PageTarget(id: games.id));
expect(find.text('Hub'), findsNothing);
expect(find.text('In'), findsOneWidget);
await tester.tap(find.byKey(ValueKey('leave-${fun.id}')));
await settle(tester);
expect(b.hubsOfPage[games.id], isEmpty);
expect(find.text('In'), findsNothing);
});
testWidgets('note page: Add to hub picks a hub', (tester) async {
final b = demo();
final lone = b.createPage('Lonely');
final tv = byTitle(b, 'Fun/TV');
await pump(tester, b, route: PageTarget(id: lone.id));
await tester.tap(find.byKey(const ValueKey('page-menu')));
await settle(tester);
await tester.tap(find.text('Add to hub…'));
await settle(tester);
await tester.tap(find.byKey(ValueKey('pick-${tv.id}')));
await settle(tester);
expect(b.hubsOfPage[lone.id], {tv.id});
expect(find.text('Fun/TV'), findsWidgets);
});
testWidgets('convert to hub: shortened title, members, keep outline', (
tester,
) async {
final b = demo();
final anime = b.createPage('Entretenimiento/TV/Anime');
b.seed(anime.id, [
(0, 'A long list of shows I like'),
(0, '[[Naruto]]'),
(0, '[[Bleach]]'),
]);
final naruto = b.createPage('Naruto');
b.createPage('Bleach');
await pump(tester, b, route: PageTarget(id: anime.id));
await tester.tap(find.byKey(const ValueKey('page-menu')));
await settle(tester);
await tester.tap(find.text('Convert to hub…'));
await settle(tester);
expect(find.text('Convert to hub'), findsOneWidget);
final title = tester.widget<TextField>(
find.byKey(const ValueKey('convert-title')),
);
expect(title.controller!.text, 'Anime');
expect(find.text('MEMBERS (2/2)'), findsOneWidget);
// Uncheck Bleach; the outline has prose, so "keep" is on by default.
await tester.tap(find.byKey(ValueKey('member-${byTitle(b, 'Bleach').id}')));
await settle(tester);
expect(find.text('MEMBERS (1/2)'), findsOneWidget);
expect(
tester
.widget<CheckboxListTile>(find.byKey(const ValueKey('keep-outline')))
.value,
isTrue,
);
await tester.tap(find.text('Convert'));
await settle(tester);
// "Anime" already exists in the demo: the error is shown inline.
expect(find.byKey(const ValueKey('convert-error')), findsOneWidget);
await tester.enterText(
find.byKey(const ValueKey('convert-title')),
'Anime (TV)',
);
await tester.tap(find.text('Convert'));
await settle(tester);
final hub = b.pages[anime.id]!;
expect(hub.isHub, isTrue);
expect(hub.title, 'Anime (TV)');
expect(hub.description, 'A long list of shows I like');
expect(b.outlines[anime.id], isEmpty);
expect(b.hubsOfPage[naruto.id], {anime.id});
final note = byTitle(b, 'Anime (notes)');
expect(b.outlines[note.id], hasLength(3));
expect(b.hubsOfPage[note.id], {anime.id});
// The page now renders as a hub.
expect(find.byKey(const ValueKey('hub-description')), findsOneWidget);
});
testWidgets('convert is disabled while "keep outline" has no note title', (
tester,
) async {
final b = demo();
final p = b.createPage('Area of Work');
b.seed(p.id, [(0, 'Some prose')]);
await pump(tester, b, route: PageTarget(id: p.id));
await tester.tap(find.byKey(const ValueKey('page-menu')));
await settle(tester);
await tester.tap(find.text('Convert to hub…'));
await settle(tester);
FilledButton convert() => tester.widget<FilledButton>(
find.widgetWithText(FilledButton, 'Convert'),
);
expect(convert().onPressed, isNotNull);
await tester.enterText(
find.byKey(const ValueKey('convert-note-title')),
'',
);
await settle(tester);
expect(convert().onPressed, isNull);
expect(
find.text('A title is required to keep the outline'),
findsOneWidget,
);
// Unticking "keep" re-enables it (the outline is then dropped on purpose).
await tester.tap(find.byKey(const ValueKey('keep-outline')));
await settle(tester);
expect(convert().onPressed, isNotNull);
expect(b.outlines[p.id], isNotEmpty);
});
testWidgets('converting a page opened by title does not recreate the title', (
tester,
) async {
final b = demo();
final p = b.createPage('Area of Work');
b.seed(p.id, [(0, 'Some prose')]);
final app = await pump(tester, b, route: PageTarget(title: 'Area of Work'));
await tester.tap(find.byKey(const ValueKey('page-menu')));
await settle(tester);
await tester.tap(find.text('Convert to hub…'));
await settle(tester);
await tester.enterText(find.byKey(const ValueKey('convert-title')), 'Area');
await tester.tap(find.text('Convert'));
await settle(tester);
expect(find.byKey(const ValueKey('hub-description')), findsOneWidget);
expect(b.pages[p.id]!.title, 'Area');
expect(b.pages.values.where((q) => q.title == 'Area of Work'), isEmpty);
expect((app.route as PageTarget).id, p.id);
});
testWidgets('renaming rewrites history entries that open the old title', (
tester,
) async {
final b = demo();
final p = b.createPage('Old name');
final app = await pump(tester, b, route: PageTarget(title: 'Old name'));
app.go(PageTarget(id: byTitle(b, 'Games').id));
await settle(tester);
app.back();
await settle(tester);
await tester.enterText(find.byType(TextField).first, 'New name');
FocusManager.instance.primaryFocus?.unfocus();
await settle(tester);
expect(b.pages[p.id]!.title, 'New name');
expect(b.pages.values.where((q) => q.title == 'Old name'), isEmpty);
expect((app.route as PageTarget).id, p.id);
app.go(PageTarget(id: byTitle(b, 'Games').id));
app.back();
await settle(tester);
expect((app.route as PageTarget).id, p.id);
});
testWidgets('adding a note to another hub moves it', (tester) async {
final b = demo();
final other = b.addHub('Other');
final tv = byTitle(b, 'Fun/TV');
await b.addToHub(tv.id, other.id);
expect(b.hubsOfPage[tv.id], {other.id});
});
testWidgets('cleanup never preselects hubs or pages with content', (
tester,
) async {
final b = demo();
final todo = b.createPage('todo');
b.seed(todo.id, [(0, 'real tasks')]);
final hub = b.addHub('later');
final empty = b.createPage('now');
final contents = b.createPage('contents');
b.seed(contents.id, [(0, 'x')]);
for (final p in [todo, hub, empty, contents]) {
b.legacy[p.id] = 'Logseq built-in';
}
final c = {for (final x in await b.legacyCandidates()) x.title: x};
expect(c['todo']!.preselected, isFalse);
expect(c['later']!.preselected, isFalse);
expect(c['now']!.preselected, isTrue);
expect(c['contents']!.preselected, isTrue);
});
testWidgets('memory backend: inHubs only lists hubs, keep title is checked', (
tester,
) async {
final b = demo();
final p = b.createPage('Plain');
final notHub = b.createPage('NotHub');
b.hubsOfPage[p.id] = {byTitle(b, 'Fun').id, notHub.id};
final st = await b.pageStructure(p.id);
expect(st.inHubs.map((h) => h.title), ['Fun']);
b.seed(p.id, [(0, 'x')]);
await expectLater(
b.convertToHub(p.id, 'Same', '', [], keepOutlineAs: 'same'),
throwsException,
);
await expectLater(
b.convertToHub(p.id, 'Same', '', [], keepOutlineAs: ' '),
throwsException,
);
expect(b.pages[p.id]!.isHub, isFalse);
});
testWidgets('convert to note turns members into links', (tester) async {
final b = demo();
final tv = byTitle(b, 'Fun/TV');
await pump(tester, b, route: PageTarget(id: tv.id));
await tester.tap(find.byKey(const ValueKey('page-menu')));
await settle(tester);
await tester.tap(find.text('Convert to note'));
await settle(tester);
expect(b.pages[tv.id]!.isHub, isFalse);
expect(b.outlines[tv.id]!.map((n) => n.content), [
'[[Anime]]',
'[[Movies]]',
'[[Shows]]',
]);
});
testWidgets('page screen shows the namespace breadcrumb and children', (
tester,
) async {
final b = demo();
final a = b.createPage('Claude/Code');
b.createPage('Claude');
await pump(tester, b, route: PageTarget(id: a.id));
expect(find.byIcon(Icons.account_tree_outlined), findsWidgets);
final c = byTitle(b, 'Claude');
await pump(tester, b, route: PageTarget(id: c.id));
expect(find.text('NAMESPACE'), findsOneWidget);
});
testWidgets('cleanup deletes only the checked pages', (tester) async {
final b = demo();
final a = b.createPage('contents');
final c = b.createPage('Keep me');
b.seed(c.id, [(0, 'real content')]);
final d = b.createPage('card');
b.legacy[a.id] = 'Logseq built-in';
b.legacy[c.id] = 'type:: system';
b.legacy[d.id] = 'Logseq built-in';
await pump(tester, b, home: const Scaffold(body: AllPagesView()));
await tester.tap(find.text('Clean up'));
await settle(tester);
expect(find.text('Remove legacy Logseq pages'), findsOneWidget);
expect(find.text('Delete (2)'), findsOneWidget);
// Uncheck "card".
await tester.tap(
find.descendant(
of: find.byType(AlertDialog),
matching: find.text('card'),
),
);
await settle(tester);
expect(find.text('Delete (1)'), findsOneWidget);
await tester.tap(find.text('Delete (1)'));
await settle(tester);
expect(b.purged, [a.id]);
expect(b.pages.containsKey(a.id), isFalse);
expect(b.pages.containsKey(c.id), isTrue);
expect(b.pages.containsKey(d.id), isTrue);
});
testWidgets('cleanup with nothing to remove says so', (tester) async {
await pump(tester, demo(), home: const Scaffold(body: AllPagesView()));
await tester.tap(find.text('Clean up'));
await settle(tester);
expect(find.text('No legacy pages found.'), findsOneWidget);
});
}
void tagTests() {
testWidgets('tags are pages: pick one, create one, remove', (tester) async {
final b = demo();
final note = byTitle(b, 'Games');
await b.setPageTags(note.id, ['tema']);
await pump(tester, b, route: PageTarget(id: note.id));
expect(find.byKey(const ValueKey('tag-tema')), findsOneWidget);
expect(byTitle(b, 'tema').isTag, isTrue);
await tester.tap(find.byKey(const ValueKey('add-tag')));
await settle(tester);
// Tags already on the page are not offered again; a new name creates a tag page.
expect(find.byKey(const ValueKey('tag-opt-tema')), findsNothing);
await tester.enterText(find.byKey(const ValueKey('tag-input')), '#ocio');
await settle(tester);
await tester.tap(find.byKey(const ValueKey('tag-create')));
await settle(tester);
expect(byTitle(b, 'Games').tags, ['tema', 'ocio']);
expect(byTitle(b, 'ocio').isTag, isTrue);
await tester.tap(find.byKey(const ValueKey('untag-tema')));
await settle(tester);
expect(byTitle(b, 'Games').tags, ['ocio']);
// The tag page survives losing its last member.
expect(byTitle(b, 'tema').isTag, isTrue);
});
testWidgets('types: pick a suggestion, create a new one, remove', (
tester,
) async {
final b = demo();
final note = byTitle(b, 'Games');
await pump(tester, b, route: PageTarget(id: note.id));
await tester.tap(find.byKey(const ValueKey('add-type')));
await settle(tester);
expect(find.byKey(const ValueKey('type-opt-persona')), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('type-opt-lugar')));
await settle(tester);
expect(find.byKey(const ValueKey('type-lugar')), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('add-type')));
await settle(tester);
expect(find.byKey(const ValueKey('type-opt-lugar')), findsNothing);
await tester.enterText(find.byKey(const ValueKey('type-input')), 'ocio');
await settle(tester);
await tester.tap(find.byKey(const ValueKey('type-create')));
await settle(tester);
expect(byTitle(b, 'Games').types, ['lugar', 'ocio']);
// Types are names, never pages.
expect(b.pages.values.any((p) => p.title == 'ocio'), isFalse);
await tester.tap(find.byKey(const ValueKey('untype-lugar')));
await settle(tester);
expect(byTitle(b, 'Games').types, ['ocio']);
});
}
+174
View File
@@ -0,0 +1,174 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:synapse/src/editor/completion.dart';
import 'package:synapse/src/editor/markdown.dart';
import 'package:synapse/src/state/app_state.dart';
import 'package:synapse/src/state/keymap.dart';
import 'package:synapse/src/state/settings.dart';
import 'package:synapse/src/theme/theme.dart';
import 'package:synapse/src/views/settings_view.dart';
import 'support/memory_backend.dart';
void main() {
group('keymap', () {
test('round-trips combos and refuses duplicates', () {
final c = Combo(LogicalKeyboardKey.keyB, ctrl: true, shift: true);
expect(Combo.decode(c.encode()), c);
expect(c.label, 'Ctrl+Shift+B');
final k = Keymap();
expect(k.of(AppAction.bold), Combo(LogicalKeyboardKey.keyB, ctrl: true));
// Ctrl+K belongs to the quick switcher.
expect(
k.bind(AppAction.bold, AppAction.quickSwitcher.defaultCombo),
AppAction.quickSwitcher,
);
expect(k.bind(AppAction.bold, c), isNull);
expect(k.of(AppAction.bold), c);
expect(Keymap(k.toJson()).of(AppAction.bold), c);
k.reset(AppAction.bold);
expect(k.isCustom(AppAction.bold), isFalse);
});
test('default bindings are unique', () {
final seen = <Combo>{};
for (final a in AppAction.values) {
expect(seen.add(a.defaultCombo), isTrue, reason: a.name);
}
});
test('theme and bindings survive a restart', () {
final store = MemorySettings();
final a = AppState(MemoryBackend(), settings: store);
a.setTheme('sweet');
a.bindKey(AppAction.bold, Combo(LogicalKeyboardKey.keyY, ctrl: true));
final b = AppState(MemoryBackend(), settings: store);
expect(b.themeId, 'sweet');
expect(
b.keymap.of(AppAction.bold),
Combo(LogicalKeyboardKey.keyY, ctrl: true),
);
store.data['theme'] = 'nonsense';
expect(AppState(MemoryBackend(), settings: store).themeId, autoThemeId);
});
});
group('slash commands', () {
test('detects the trigger only at a word start', () {
expect(detectCompletion('/li', 3)!.kind, CompletionKind.command);
expect(detectCompletion('say /li', 7)!.query, 'li');
expect(detectCompletion('see http://x', 12), isNull);
expect(detectCompletion('a/b', 3), isNull);
});
test('/link leaves the caret inside the brackets', () {
final q = detectCompletion('x /li', 5)!;
final v = applyCompletion(
'x /li',
q,
const CompletionItem('/link', 'link'),
);
expect(v.text, 'x [[]]');
expect(v.selection.baseOffset, 4);
});
test('commands match by name, label and keyword', () {
expect(matchCommands('li').first.name, 'link');
expect(matchCommands('strong').map((c) => c.name), contains('bold'));
expect(matchCommands('zzz'), isEmpty);
});
test('wrapSelection wraps, unwraps and pairs at the caret', () {
const sel = TextSelection(baseOffset: 2, extentOffset: 5);
final w = wrapSelection(
const TextEditingValue(text: 'a bcd e', selection: sel),
'**',
'**',
);
expect(w.text, 'a **bcd** e');
expect(w.selection.textInside(w.text), 'bcd');
expect(wrapSelection(w, '**', '**').text, 'a bcd e');
final p = wrapSelection(
const TextEditingValue(
text: 'ab',
selection: TextSelection.collapsed(offset: 1),
),
'==',
'==',
);
expect(p.text, 'a====b');
expect(p.selection.baseOffset, 3);
});
});
test('backslash escapes show the character literally', () {
final r = BlockRenderer(
RenderContext(
colors: SynapseColors.light,
base: const TextStyle(fontSize: 15),
refs: BlockRefCache(MemoryBackend()),
assetPath: (_) => null,
onPage: (_) {},
onBlockRef: (_) {},
onUrl: (_) {},
),
).render(r'\*not italic\* and \[[no link]]');
final t = r.span.toPlainText(includePlaceholders: true);
expect(t, '*not italic* and [[no link]]');
r.dispose();
});
testWidgets('settings: pick a theme and rebind a key', (tester) async {
tester.view.physicalSize = const Size(1200, 1600);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final app = AppState(MemoryBackend());
await tester.pumpWidget(
AppScope(
state: app,
child: ListenableBuilder(
listenable: app,
builder: (_, _) {
final t = themeById(app.themeId);
return MaterialApp(
theme: buildTheme(
t?.brightness ?? Brightness.light,
colors: t?.colors,
),
home: const Scaffold(body: SettingsView()),
);
},
),
),
);
await tester.tap(find.byKey(const ValueKey('theme-sweet')));
await tester.pump();
expect(app.themeId, 'sweet');
final bind = find.byKey(const ValueKey('bind-bold'));
await tester.ensureVisible(bind);
await tester.tap(bind);
await tester.pump();
expect(find.text('Press keys…'), findsOneWidget);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyDownEvent(LogicalKeyboardKey.keyY);
await tester.sendKeyUpEvent(LogicalKeyboardKey.keyY);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
expect(
app.keymap.of(AppAction.bold),
Combo(LogicalKeyboardKey.keyY, ctrl: true),
);
});
test('hubs never enter recents', () {
final b = MemoryBackend();
final hub = b.addHub('Fun');
final note = b.createPage('Note');
final app = AppState(b);
app.pageShown(note);
app.pageShown(hub);
expect(app.recent.map((p) => p.title), ['Note']);
});
}
+614 -6
View File
@@ -11,6 +11,9 @@ class MemoryBackend implements GraphBackend {
MemoryBackend({this.todayDate = '2026-10-21'});
final String todayDate;
@override
String get graphName => 'Test graph';
final pages = <String, PageDto>{};
final outlines = <String, List<OutlineNode>>{};
final aliases = <String, String>{};
@@ -26,6 +29,11 @@ class MemoryBackend implements GraphBackend {
journalDate: journalDate,
createdAt: 0,
updatedAt: 0,
isHub: false,
description: '',
tags: const [],
isTag: false,
types: const [],
);
pages[p.id] = p;
outlines[p.id] = [];
@@ -138,18 +146,55 @@ class MemoryBackend implements GraphBackend {
@override
Future<PageDto> renamePage(String id, String newTitle) async {
final p = pages[id]!;
return pages[id] = PageDto(
id: p.id,
title: newTitle,
createdAt: p.createdAt,
updatedAt: p.updatedAt,
);
final t = newTitle.trim();
final clash = _byTitle(t);
if (clash != null && clash.id != id) {
throw Exception('A page titled "$t" already exists');
}
for (final l in outlines.values) {
for (final n in l) {
n.content = n.content.replaceAll('[[${p.title}]]', '[[$t]]');
}
}
final old = p.title;
_put(p, title: t);
if (p.isTag) {
for (final q in pages.values.toList()) {
if (q.tags.any((x) => _tagKey(x) == _tagKey(old))) {
_put(
q,
tags: [for (final x in q.tags) _tagKey(x) == _tagKey(old) ? t : x],
);
}
}
}
return pages[id]!;
}
@override
Future<void> deletePage(String id) async {
final gone = pages[id];
if (gone != null && gone.isTag) {
for (final q in pages.values.toList()) {
_put(
q,
tags: [
for (final x in q.tags)
if (_tagKey(x) != _tagKey(gone.title)) x,
],
);
}
}
pages.remove(id);
outlines.remove(id);
_forget(id);
}
void _forget(String id) {
hubsOfPage.remove(id);
for (final s in hubsOfPage.values) {
s.remove(id);
}
}
@override
@@ -170,6 +215,7 @@ class MemoryBackend implements GraphBackend {
String content,
) async {
calls.add('insert');
if (_isHub(pageId)) throw Exception('A hub has no blocks');
final n = OutlineNode(id: _id(), depth: 0, content: content);
OutlineOps.insert(
outlines[pageId]!,
@@ -280,6 +326,531 @@ class MemoryBackend implements GraphBackend {
Future<AssetDto> putAssetFile(String path, {String? mime}) =>
throw UnimplementedError();
/// Pages `legacyCandidates` reports, id to reason. Preselection follows the core: not a
/// hub, and empty or one of Logseq's organisational pages.
final legacy = <String, String>{};
/// Ids passed to `purgePages`, in call order.
final purged = <String>[];
/// Parent hubs of each page (membership lives on the member, like the core).
final hubsOfPage = <String, Set<String>>{};
/// Test shortcut: `hubFlags[id] = true` turns a page into a hub whose members are the
/// pages its outline linked to (same as converting it with all candidates kept).
late final hubFlags = _HubFlags(this);
bool _isHub(String id) => pages[id]?.isHub ?? false;
PageBrief _brief(PageDto p) => PageBrief(
id: p.id,
title: p.title,
isJournal: p.journalDate != null,
isHub: p.isHub,
);
void _put(
PageDto p, {
String? title,
bool? isHub,
String? description,
List<String>? tags,
bool? isTag,
List<String>? types,
}) {
pages[p.id] = PageDto(
id: p.id,
title: title ?? p.title,
journalDate: p.journalDate,
originJournal: p.originJournal,
createdAt: p.createdAt,
updatedAt: p.updatedAt,
isHub: isHub ?? p.isHub,
description: description ?? p.description,
tags: tags ?? p.tags,
isTag: isTag ?? p.isTag,
types: types ?? p.types,
);
}
/// Members of a hub: sub-hubs first, then notes, each by title.
List<PageDto> _members(String hubId) {
final out = [
for (final e in hubsOfPage.entries)
if (e.value.contains(hubId) && pages.containsKey(e.key)) pages[e.key]!,
];
out.sort((a, b) {
if (a.isHub != b.isHub) return a.isHub ? -1 : 1;
return a.title.toLowerCase().compareTo(b.title.toLowerCase());
});
return out;
}
/// Whether `target` is `hub` or lies below it.
bool _reaches(String hub, String target) {
if (hub == target) return true;
return _members(hub).any((m) => m.isHub && _reaches(m.id, target));
}
/// Pages a page's outline links to or tags (outline order, journals and self skipped).
List<PageDto> _linked(String id) {
final link = RegExp(r'\[\[([^\]]+)\]\]|(?:^|\s)#(\w+)');
final out = <PageDto>[];
for (final n in outlines[id] ?? const <OutlineNode>[]) {
for (final m in link.allMatches(n.content)) {
final p = _byTitle(m.group(1) ?? m.group(2)!);
if (p == null || p.id == id || p.journalDate != null) continue;
if (!out.any((b) => b.id == p.id)) out.add(p);
}
}
return out;
}
/// Makes `page` a hub, dropping its blocks; `members` are added when valid.
void makeHub(String id, {String? description, List<String>? members}) {
final linked = members ?? [for (final p in _linked(id)) p.id];
outlines[id] = [];
_put(pages[id]!, isHub: true, description: description);
for (final m in linked) {
_tryAdd(m, id);
}
}
bool _tryAdd(String page, String hub) {
final p = pages[page];
if (p == null ||
p.journalDate != null ||
!_isHub(hub) ||
page == hub ||
_reaches(page, hub)) {
return false;
}
(hubsOfPage[page] ??= {}).add(hub);
return true;
}
/// Synchronous `createHub` for test setup.
PageDto addHub(String title, [String description = '']) {
final p = createPage(title);
_put(p, isHub: true, description: description);
return pages[p.id]!;
}
@override
Future<PageDto> createHub(String title, String description) async {
final t = title.trim();
if (t.isEmpty) throw Exception('A title is required');
if (_byTitle(t) != null) {
throw Exception('A page titled "$t" already exists');
}
final p = createPage(t);
_put(p, isHub: true, description: description);
return pages[p.id]!;
}
final templates = <String, String>{};
String _tagKey(String t) => t.trim().toLowerCase();
@override
Future<PageDto> setPageTags(String pageId, List<String> tags) async {
final p = pages[pageId]!;
if (p.journalDate != null) throw Exception('Journals cannot have tags');
final next = <String>[];
for (final raw in tags) {
final t = raw.trim().replaceFirst(RegExp(r'^#+'), '').trim();
if (t.isNotEmpty && !next.any((x) => _tagKey(x) == _tagKey(t))) {
next.add(t);
}
}
final stored = <String>[];
for (final t in next) {
var tp = _byTitle(t);
if (tp == null) {
tp = createPage(t);
_put(tp, isTag: true);
} else if (tp.journalDate != null || tp.isHub) {
throw Exception('"$t" cannot be a tag');
} else if (!tp.isTag) {
_put(tp, isTag: true);
}
stored.add(pages[tp.id]!.title);
}
_put(p, tags: stored);
return pages[pageId]!;
}
static const suggestedTypes = ['persona', 'lugar', 'empresa'];
@override
Future<PageDto> setPageTypes(String pageId, List<String> types) async {
final p = pages[pageId]!;
if (p.journalDate != null) throw Exception('Journals cannot have types');
final next = <String>[];
for (final raw in types) {
final t = raw.trim();
if (t.isNotEmpty && !next.any((x) => _tagKey(x) == _tagKey(t))) {
next.add(t);
}
}
_put(p, types: next);
return pages[pageId]!;
}
@override
Future<PageDto> addPageType(String pageId, String ty) =>
setPageTypes(pageId, [...pages[pageId]!.types, ty]);
@override
Future<PageDto> removePageType(String pageId, String ty) =>
setPageTypes(pageId, [
for (final t in pages[pageId]!.types)
if (_tagKey(t) != _tagKey(ty)) t,
]);
@override
Future<List<TagDto>> typeCatalog() async {
final used = <String, TagDto>{};
for (final p in pages.values) {
for (final t in p.types) {
final k = _tagKey(t);
used[k] = TagDto(
name: used[k]?.name ?? t,
count: (used[k]?.count ?? 0) + 1,
suggested: suggestedTypes.contains(k),
);
}
}
final out = used.values.toList()
..sort((a, b) => b.count.compareTo(a.count));
for (final s in suggestedTypes) {
if (!used.containsKey(s)) {
out.add(TagDto(name: s, count: 0, suggested: true));
}
}
return out;
}
@override
Future<PageDto> addPageTag(String pageId, String tag) =>
setPageTags(pageId, [...pages[pageId]!.tags, tag]);
@override
Future<PageDto> removePageTag(String pageId, String tag) =>
setPageTags(pageId, [
for (final t in pages[pageId]!.tags)
if (_tagKey(t) != _tagKey(tag)) t,
]);
@override
Future<List<TagDto>> tagCatalog() async {
final out = [
for (final t in pages.values)
if (t.isTag)
TagDto(
name: t.title,
count: pages.values
.where((p) => p.tags.any((x) => _tagKey(x) == _tagKey(t.title)))
.length,
suggested: false,
),
]..sort((a, b) => b.count.compareTo(a.count));
return out;
}
@override
Future<List<PageBrief>> pagesWithTag(String tag) async => [
for (final p in pages.values)
if (p.tags.any((t) => _tagKey(t) == _tagKey(tag))) _brief(p),
];
@override
Future<String> hubTemplate(String hubId) async {
if (!_isHub(hubId)) throw Exception('Not a hub');
return templates.putIfAbsent(hubId, () {
final t = createPage('Template: ${pages[hubId]!.title}');
return t.id;
});
}
@override
Future<PageDto> createPageFromTemplate(String hubId, String title) async {
final t = await hubTemplate(hubId);
final name = title.trim();
if (name.isEmpty) throw Exception('A title is required');
if (_byTitle(name) != null) {
throw Exception('A page titled "$name" already exists');
}
final p = createPage(name);
seed(p.id, [for (final n in outlines[t]!) (n.depth, n.content)]);
await addToHub(p.id, hubId);
return pages[p.id]!;
}
@override
Future<PageDto> setHubDescription(String hubId, String description) async {
if (!_isHub(hubId)) throw Exception('Not a hub');
_put(pages[hubId]!, description: description);
return pages[hubId]!;
}
@override
Future<void> addToHub(String pageId, String hubId) async {
if (!_isHub(hubId)) throw Exception('The target is not a hub');
if (pageId == hubId) throw Exception('A hub cannot contain itself');
if (pages[pageId]?.journalDate != null) {
throw Exception('Journals cannot be in a hub');
}
if (_reaches(pageId, hubId)) throw Exception('That would create a cycle');
// A page belongs to one hub: adding it elsewhere moves it.
hubsOfPage[pageId] = {hubId};
}
@override
Future<void> removeFromHub(String pageId, String hubId) async {
hubsOfPage[pageId]?.remove(hubId);
}
@override
Future<HubPreviewDto> hubConversionPreview(String pageId) async {
final p = pages[pageId]!;
final title = p.title.split('/').last.trim();
final strip = RegExp(r'\[\[([^\]]+)\]\]|(?:^|\s)#\w+|^#+\s*|\w+::.*');
var prose = 0;
String? first;
final l = outlines[pageId] ?? const <OutlineNode>[];
for (final n in l) {
final text = n.content
.replaceAllMapped(strip, (m) => m.group(1) ?? '')
.trim();
if (text.isEmpty) continue;
prose++;
first ??= text;
}
final members = [..._linked(pageId)];
final ref = '[[${p.title}]]';
for (final q in pages.values) {
if (q.id == pageId || q.journalDate != null) continue;
final refs = (outlines[q.id] ?? const <OutlineNode>[]).any(
(n) => n.content.contains(ref) || n.content.contains('#${p.title}'),
);
if (refs && !members.any((m) => m.id == q.id)) members.add(q);
}
return HubPreviewDto(
suggestedTitle: title,
suggestedDescription: first ?? '',
members: [for (final m in members) _brief(m)],
proseBlocks: prose,
blocks: l.length,
suggestedNoteTitle: '$title (notes)',
);
}
@override
Future<PageDto> convertToHub(
String pageId,
String title,
String description,
List<String> memberIds, {
String? keepOutlineAs,
}) async {
final p = pages[pageId]!;
if (p.journalDate != null) throw Exception('Journals cannot be hubs');
if (p.isHub) throw Exception('Already a hub');
final t = title.trim();
if (t.isEmpty) throw Exception('A title is required');
final clash = _byTitle(t);
if (clash != null && clash.id != pageId) {
throw Exception('A page titled "$t" already exists');
}
final keep = keepOutlineAs?.trim();
if (keep != null) {
if (keep.isEmpty) {
throw Exception('The note that keeps the outline needs a title');
}
// Checked against the new hub title too, like the core (which rolls back).
// (the old title is free once the page is renamed).
final c = _byTitle(keep);
if ((c != null && c.id != pageId) ||
keep.toLowerCase() == t.toLowerCase()) {
throw Exception('A page titled "$keep" already exists');
}
}
if (t != p.title) {
for (final l in outlines.values) {
for (final n in l) {
n.content = n.content.replaceAll('[[${p.title}]]', '[[$t]]');
}
}
_put(p, title: t);
}
String? noteId;
if (keep != null) {
final note = createPage(keep);
outlines[note.id] = outlines[pageId]!;
noteId = note.id;
}
outlines[pageId] = [];
_put(pages[pageId]!, isHub: true, description: description);
if (noteId != null) _tryAdd(noteId, pageId);
for (final m in memberIds) {
_tryAdd(m, pageId);
}
return pages[pageId]!;
}
@override
Future<PageDto> convertToNote(String pageId) async {
final p = pages[pageId]!;
if (!p.isHub) throw Exception('Not a hub');
final members = _members(pageId);
final l = <OutlineNode>[];
if (p.description.isNotEmpty) {
l.add(OutlineNode(id: _id(), depth: 0, content: p.description));
}
for (final m in members) {
l.add(OutlineNode(id: _id(), depth: 0, content: '[[${m.title}]]'));
hubsOfPage[m.id]?.remove(pageId);
}
OutlineOps.fixParents(l);
outlines[pageId] = l;
_put(p, isHub: false, description: '');
return pages[pageId]!;
}
@override
Future<HubsDto> hubs() async {
final all = [
for (final p in pages.values)
if (p.isHub) p,
]..sort((a, b) => a.title.compareTo(b.title));
final roots = [
for (final p in all)
if (!(hubsOfPage[p.id] ?? const {}).any(_isHub)) p.id,
];
final depth = <String, int>{};
var frontier = roots;
for (var d = 0; frontier.isNotEmpty; d++) {
final next = <String>[];
for (final id in frontier) {
if (depth.containsKey(id)) continue;
depth[id] = d;
next.addAll([
for (final m in _members(id))
if (m.isHub) m.id,
]);
}
frontier = next;
}
return HubsDto(
hubs: [
for (final p in all)
HubDto(
id: p.id,
title: p.title,
description: p.description,
depth: depth[p.id] ?? 0,
members: [for (final m in _members(p.id)) _brief(m)],
subHubs: [
for (final m in _members(p.id))
if (m.isHub) m.id,
],
),
],
roots: roots,
);
}
/// Deepest hub containing each page (ties: fewer members, then title); a hub maps to
/// itself.
Map<String, String> _home(HubsDto h) {
final byId = {for (final x in h.hubs) x.id: x};
final home = <String, String>{};
for (final p in pages.values) {
if (p.isHub) {
home[p.id] = p.id;
continue;
}
final cand = [
for (final id in hubsOfPage[p.id] ?? const <String>{})
if (byId.containsKey(id)) byId[id]!,
];
if (cand.isEmpty) continue;
cand.sort((a, b) {
final d = b.depth.compareTo(a.depth);
if (d != 0) return d;
final m = a.members.length.compareTo(b.members.length);
return m != 0 ? m : a.title.compareTo(b.title);
});
home[p.id] = cand.first.id;
}
return home;
}
@override
Future<PageStructure> pageStructure(String pageId) async {
final p = pages[pageId]!;
final parts = p.title.split('/');
final path = <NamespaceEntry>[];
for (var i = 1; i < parts.length; i++) {
final t = parts.sublist(0, i).join('/');
path.add(NamespaceEntry(title: t, id: _byTitle(t)?.id));
}
final prefix = '${p.title}/';
final children = [
for (final q in pages.values)
if (q.title.startsWith(prefix) &&
!q.title.substring(prefix.length).contains('/'))
NamespaceEntry(title: q.title, id: q.id),
]..sort((a, b) => a.title.compareTo(b.title));
final inHubs = [
for (final id in hubsOfPage[pageId] ?? const <String>{})
if (pages[id] != null && pages[id]!.isHub) pages[id]!,
]..sort((a, b) => a.title.compareTo(b.title));
return PageStructure(
isHub: p.isHub,
description: p.description,
members: p.isHub ? [for (final m in _members(pageId)) _brief(m)] : [],
inHubs: [for (final h in inHubs) _brief(h)],
nsPath: path,
nsChildren: children,
);
}
@override
Future<List<LegacyCandidate>> legacyCandidates() async => [
for (final e in legacy.entries)
if (pages.containsKey(e.key))
LegacyCandidate(
id: e.key,
title: pages[e.key]!.title,
reason: e.value,
blocks: outlines[e.key]?.length ?? 0,
preselected: _preselected(e.key),
),
];
bool _preselected(String id) {
final p = pages[id]!;
final t = p.title.toLowerCase();
return !p.isHub &&
((outlines[id]?.length ?? 0) == 0 ||
const ['contents', 'card', 'favorites'].contains(t) ||
t.startsWith('hls__'));
}
@override
Future<int> purgePages(List<String> ids) async {
var n = 0;
for (final id in ids) {
if (pages.remove(id) != null) n++;
outlines.remove(id);
_forget(id);
purged.add(id);
}
return n;
}
/// Links (`[[x]]`) and tags (`#x`) between pages, built like the Rust side but simpler.
@override
Future<GraphData> graphData() async {
@@ -288,6 +859,13 @@ class MemoryBackend implements GraphBackend {
final s = <int>[], t = <int>[], k = <int>[];
final link = RegExp(r'\[\[([^\]]+)\]\]');
final tag = RegExp(r'(?:^|\s)#(\w+)');
final hubData = await hubs();
final home = _home(hubData);
final containsEdges = <(String, String)>[
for (final e in hubsOfPage.entries)
for (final h in e.value)
if (pages.containsKey(e.key) && pages.containsKey(h)) (h, e.key),
];
final degree = List.filled(ids.length, 0, growable: true);
for (final id in List.of(ids)) {
for (final n in outlines[id]!) {
@@ -306,6 +884,24 @@ class MemoryBackend implements GraphBackend {
}
}
}
for (final (h, m) in containsEdges) {
s.add(index[h]!);
t.add(index[m]!);
k.add(EdgeKind.contains.index);
}
// A note points at each of its tag pages.
for (final p in pages.values) {
final i = index[p.id];
if (i == null) continue;
for (final tg in p.tags) {
final tp = _byTitle(tg);
final j = tp == null ? null : index[tp.id];
if (j == null) continue;
s.add(i);
t.add(j);
k.add(EdgeKind.tagged.index);
}
}
while (degree.length < ids.length) {
degree.add(0);
}
@@ -324,6 +920,9 @@ class MemoryBackend implements GraphBackend {
degree: degree[i],
backlinks: 0,
cluster: 0,
isHub: _isHub(ids[i]),
homeHub: home[ids[i]] == null ? null : index[home[ids[i]]!],
tags: pages[ids[i]]!.tags,
),
],
sources: Uint32List.fromList(s),
@@ -394,3 +993,12 @@ class FakeLayout implements LayoutEngine {
@override
void dispose() => disposed = true;
}
/// Map-like shortcut for tests: assigning `true` converts the page to a hub.
class _HubFlags {
_HubFlags(this._b);
final MemoryBackend _b;
void operator []=(String id, bool hub) {
if (hub && !_b._isHub(id)) _b.makeHub(id);
}
}
+2 -2
View File
@@ -89,11 +89,11 @@ BEGIN
BEGIN
BLOCK "040904e4"
BEGIN
VALUE "CompanyName", "es.zenvairo" "\0"
VALUE "CompanyName", "dasemu" "\0"
VALUE "FileDescription", "synapse" "\0"
VALUE "FileVersion", VERSION_AS_STRING "\0"
VALUE "InternalName", "synapse" "\0"
VALUE "LegalCopyright", "Copyright (C) 2026 es.zenvairo. All rights reserved." "\0"
VALUE "LegalCopyright", "Copyright (C) 2026 dasemu. All rights reserved." "\0"
VALUE "OriginalFilename", "synapse.exe" "\0"
VALUE "ProductName", "synapse" "\0"
VALUE "ProductVersion", VERSION_AS_STRING "\0"
+8
View File
@@ -13,8 +13,16 @@ pub mod parse;
pub mod position;
mod schema;
pub mod store;
pub mod structure;
pub mod synapse;
pub mod tags;
pub mod types;
pub use error::{Error, Result};
pub use model::*;
pub use store::Graph;
pub use structure::{
HubConversion, HubInfo, HubPreview, Structure, is_legacy_page, namespace_parent,
};
pub use tags::{MAX_TAG_CHARS, TagInfo, normalize_tag};
pub use types::SUGGESTED_TYPES;
+60
View File
@@ -11,6 +11,40 @@ pub fn new_id() -> Uuid {
Uuid::now_v7()
}
/// What a page is: a note (an outline of blocks), a hub (a container of pages with a short
/// description and an ordered member list, and no blocks) or a template (the outline that new
/// notes of a hub start from; every hub owns exactly one, see `Graph::hub_template`).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PageKind {
#[default]
Note,
Hub,
Template,
/// A topic page: notes point at it from their `tags`.
Tag,
}
impl PageKind {
pub fn as_str(self) -> &'static str {
match self {
PageKind::Note => "note",
PageKind::Hub => "hub",
PageKind::Template => "template",
PageKind::Tag => "tag",
}
}
/// Unknown values read as notes.
pub fn parse(s: &str) -> Self {
match s {
"hub" => PageKind::Hub,
"template" => PageKind::Template,
"tag" => PageKind::Tag,
_ => PageKind::Note,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Page {
pub id: PageId,
@@ -22,12 +56,38 @@ pub struct Page {
pub properties: Properties,
pub created_at: i64,
pub updated_at: i64,
/// Defaults to `Note` so ops and snapshots from older versions parse.
#[serde(default)]
pub kind: PageKind,
/// Short plain-text description (hubs).
#[serde(default)]
pub description: String,
/// Hubs this page belongs to (its "parents", like tags). Ids may dangle (deleted pages,
/// pages no longer hubs); readers ignore those.
#[serde(default)]
pub hubs: Vec<PageId>,
/// Titles of the tag pages ([`PageKind::Tag`]) this page is filed under, any number; see
/// `tags`. Always in step with the tag pages (created on first use).
#[serde(default)]
pub tags: Vec<String>,
/// What kind of thing this is ("persona", "lugar"...): plain names, not pages; see `types`.
#[serde(default)]
pub types: Vec<String>,
}
impl Page {
pub fn is_journal(&self) -> bool {
self.journal_date.is_some()
}
pub fn is_hub(&self) -> bool {
self.kind == PageKind::Hub
}
pub fn is_template(&self) -> bool {
self.kind == PageKind::Template
}
pub fn is_tag(&self) -> bool {
self.kind == PageKind::Tag
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+1 -1
View File
@@ -126,7 +126,7 @@ fn scan_line(line: &str, is_prop: bool, refs: &mut Refs) {
}
/// Finds the `]]` closing a `[[` that opened before `from`, allowing nested `[[..]]`.
fn find_close(s: &str, from: usize) -> Option<usize> {
pub(crate) fn find_close(s: &str, from: usize) -> Option<usize> {
let mut depth = 0;
let mut i = from;
while i + 1 < s.len() {
+94 -2
View File
@@ -1,4 +1,6 @@
pub const VERSION: i64 = 2;
use rusqlite::OptionalExtension;
pub const VERSION: i64 = 5;
pub const SCHEMA: &str = r#"
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
@@ -12,7 +14,12 @@ CREATE TABLE IF NOT EXISTS pages (
properties TEXT NOT NULL DEFAULT '{}',
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
hlc TEXT NOT NULL
hlc TEXT NOT NULL,
kind TEXT NOT NULL DEFAULT 'note',
description TEXT NOT NULL DEFAULT '',
hubs TEXT NOT NULL DEFAULT '[]',
tags TEXT NOT NULL DEFAULT '[]',
types TEXT NOT NULL DEFAULT '[]'
);
CREATE INDEX IF NOT EXISTS pages_updated ON pages(updated_at);
CREATE INDEX IF NOT EXISTS pages_origin ON pages(origin_journal);
@@ -25,6 +32,23 @@ CREATE TABLE IF NOT EXISTS aliases (
);
CREATE INDEX IF NOT EXISTS aliases_page ON aliases(page_id);
-- Derived index of `pages.hubs` (hub membership lives on the member page), kept in step on
-- every page write like `refs`.
CREATE TABLE IF NOT EXISTS page_hubs (
page_id TEXT NOT NULL,
hub_id TEXT NOT NULL,
PRIMARY KEY (page_id, hub_id)
);
CREATE INDEX IF NOT EXISTS page_hubs_hub ON page_hubs(hub_id);
-- Derived index of `pages.tags` (normalised tag key per page), kept in step on every page write.
CREATE TABLE IF NOT EXISTS page_tags (
page_id TEXT NOT NULL,
tag_key TEXT NOT NULL,
PRIMARY KEY (page_id, tag_key)
);
CREATE INDEX IF NOT EXISTS page_tags_key ON page_tags(tag_key);
CREATE TABLE IF NOT EXISTS blocks (
id TEXT PRIMARY KEY,
page_id TEXT NOT NULL,
@@ -92,6 +116,44 @@ CREATE TABLE IF NOT EXISTS ops (
);
"#;
/// Rebuilds the `page_tags` index from every page's `tags` column.
pub fn rebuild_page_tags(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
conn.execute("DELETE FROM page_tags", [])?;
let rows: Vec<(String, String)> = {
let mut st = conn.prepare("SELECT id, tags FROM pages WHERE tags != '[]'")?;
st.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
.collect::<rusqlite::Result<_>>()?
};
let mut ins =
conn.prepare("INSERT OR IGNORE INTO page_tags(page_id, tag_key) VALUES (?1, ?2)")?;
for (id, tags) in rows {
let tags: Vec<String> = serde_json::from_str(&tags).unwrap_or_default();
for t in tags {
ins.execute([&id, &crate::model::title_key(&t)])?;
}
}
Ok(())
}
/// Rebuilds the `page_hubs` index from every page's `hubs` column.
pub fn rebuild_page_hubs(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
conn.execute("DELETE FROM page_hubs", [])?;
let rows: Vec<(String, String)> = {
let mut st = conn.prepare("SELECT id, hubs FROM pages WHERE hubs != '[]'")?;
st.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
.collect::<rusqlite::Result<_>>()?
};
let mut ins =
conn.prepare("INSERT OR IGNORE INTO page_hubs(page_id, hub_id) VALUES (?1, ?2)")?;
for (id, hubs) in rows {
let hubs: Vec<uuid::Uuid> = serde_json::from_str(&hubs).unwrap_or_default();
for h in hubs.into_iter().take(1) {
ins.execute([&id, &h.to_string()])?;
}
}
Ok(())
}
/// Upgrades databases created by older versions in place.
pub fn migrate(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
let has_alias_hlc: bool = conn
@@ -100,6 +162,36 @@ pub fn migrate(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
if !has_alias_hlc {
conn.execute_batch("ALTER TABLE aliases ADD COLUMN hlc TEXT NOT NULL DEFAULT ''")?;
}
// v3: page kinds (hubs), descriptions and hub membership; `page_hubs` is created by
// `SCHEMA` and rebuilt from `pages.hubs`.
for (col, ddl) in [
("kind", "kind TEXT NOT NULL DEFAULT 'note'"),
("description", "description TEXT NOT NULL DEFAULT ''"),
("hubs", "hubs TEXT NOT NULL DEFAULT '[]'"),
// v4: free-form tags per page; `page_tags` is created by `SCHEMA`.
("tags", "tags TEXT NOT NULL DEFAULT '[]'"),
// v5: tag pages (kind 'tag') and plain-name types per page.
("types", "types TEXT NOT NULL DEFAULT '[]'"),
] {
let has: bool = conn
.prepare("SELECT 1 FROM pragma_table_info('pages') WHERE name=?1")?
.exists([col])?;
if !has {
conn.execute_batch(&format!("ALTER TABLE pages ADD COLUMN {ddl}"))?;
}
}
let version: Option<i64> = conn
.query_row("SELECT value FROM meta WHERE key='schema'", [], |r| {
r.get::<_, String>(0)
})
.optional()?
.and_then(|v| v.parse().ok());
if version.is_some_and(|v| v < 3) {
rebuild_page_hubs(conn)?;
}
if version.is_some_and(|v| v < 4) {
rebuild_page_tags(conn)?;
}
conn.execute(
"INSERT OR REPLACE INTO meta(key, value) VALUES ('schema', ?1)",
[VERSION.to_string()],
+123 -23
View File
@@ -21,8 +21,7 @@ pub fn journal_id(date: NaiveDate) -> PageId {
Uuid::new_v5(&JOURNAL_NS, journal_title(date).as_bytes())
}
const PAGE_COLS: &str =
"id, title, journal_date, origin_journal, properties, created_at, updated_at";
const PAGE_COLS: &str = "id, title, journal_date, origin_journal, properties, created_at, updated_at, kind, description, hubs, tags, types";
const BLOCK_COLS: &str =
"id, page_id, parent_id, position, content, properties, collapsed, created_at, updated_at";
@@ -76,13 +75,15 @@ impl Graph {
clock.observe(&last);
}
let blobs = BlobStore::open(dir.join("blobs"))?;
Ok(Self {
let graph = Self {
conn,
blobs,
clock,
dir,
now_override: Cell::new(None),
})
};
graph.repair_tag_pages()?;
Ok(graph)
}
/// Runs `f` atomically. Calls nest (SQLite savepoints), so callers such as importers can
@@ -99,12 +100,16 @@ impl Graph {
}
/// `execute` through the statement cache (hot paths run millions of times on imports).
fn exec<P: rusqlite::Params>(&self, sql: &str, params: P) -> rusqlite::Result<usize> {
pub(crate) fn exec<P: rusqlite::Params>(
&self,
sql: &str,
params: P,
) -> rusqlite::Result<usize> {
self.conn.prepare_cached(sql)?.execute(params)
}
/// `query_row` through the statement cache.
fn row<T, P: rusqlite::Params>(
pub(crate) fn row<T, P: rusqlite::Params>(
&self,
sql: &str,
params: P,
@@ -124,7 +129,7 @@ impl Graph {
/// Atomic scope for one graph operation: a savepoint at top level, a no-op when an
/// enclosing transaction already provides atomicity.
fn tx(&self) -> Result<Tx<'_>> {
pub(crate) fn tx(&self) -> Result<Tx<'_>> {
if self.conn.is_autocommit() {
return self.savepoint();
}
@@ -214,7 +219,16 @@ impl Graph {
Ok(page)
}
fn create_page_tx(&self, new: NewPage) -> Result<Page> {
pub(crate) fn create_page_tx(&self, new: NewPage) -> Result<Page> {
self.create_page_kind_tx(new, PageKind::Note, String::new())
}
pub(crate) fn create_page_kind_tx(
&self,
new: NewPage,
kind: PageKind,
description: String,
) -> Result<Page> {
let title = new.title.trim().to_string();
if title.is_empty() {
return Err(Error::Invalid("empty page title".into()));
@@ -238,6 +252,11 @@ impl Graph {
properties: new.properties,
created_at: new.created_at.unwrap_or(now),
updated_at: new.updated_at.unwrap_or(now),
kind,
description,
hubs: Vec::new(),
tags: Vec::new(),
types: Vec::new(),
};
self.write_page(&page, &self.tick())?;
Ok(page)
@@ -270,10 +289,11 @@ impl Graph {
/// Pages ordered by last update (most recent first).
pub fn list_pages(&self, include_journals: bool, limit: u32, offset: u32) -> Result<Vec<Page>> {
// Templates are reached through their hub, never listed as pages.
let filter = if include_journals {
""
"WHERE kind != 'template'"
} else {
"WHERE journal_date IS NULL"
"WHERE journal_date IS NULL AND kind != 'template'"
};
let mut st = self.conn.prepare_cached(&format!(
"SELECT {PAGE_COLS} FROM pages {filter} ORDER BY updated_at DESC LIMIT ?1 OFFSET ?2"
@@ -338,9 +358,12 @@ impl Graph {
st.query_map([&old_key], |r| r.get(0))?
.collect::<std::result::Result<_, _>>()?
};
page.title = new_title.to_string();
let old_title = std::mem::replace(&mut page.title, new_title.to_string());
page.updated_at = self.now_ms();
self.write_page(&page, &self.tick())?;
if page.is_tag() {
self.retitle_tag(&old_title, new_title)?;
}
for bid in referencing {
if let Some(mut b) = self.get_block(parse_id(&bid)?)? {
let rewritten = parse::rewrite_refs(&b.content, &old_key, new_title);
@@ -365,9 +388,34 @@ impl Graph {
Ok(page)
}
/// Deletes a page and all its blocks.
/// Deletes a page and all its blocks; when it is a hub, its members leave it.
pub fn delete_page(&self, id: PageId) -> Result<()> {
let tx = self.tx()?;
if let Some(p) = self.get_page(id)? {
if p.is_template() {
return Err(Error::Invalid(
"a template cannot be deleted on its own; it goes with its hub".into(),
));
}
if p.is_hub() {
for t in self.hub_template_ids(id)? {
self.delete_page_rows(t)?;
}
}
}
self.delete_page_rows(id)?;
tx.commit()?;
Ok(())
}
pub(crate) fn delete_page_rows(&self, id: PageId) -> Result<()> {
// Members of a deleted hub leave it (each member page is rewritten and logged).
self.drop_hub_from_members(id)?;
if let Some(p) = self.get_page(id)?
&& p.is_tag()
{
self.drop_tag_from_members(&p.title)?;
}
let ids: Vec<String> = {
let mut st = self
.conn
@@ -379,7 +427,6 @@ impl Graph {
self.remove_block_row(parse_id(&b)?, &self.tick())?;
}
self.remove_page_row(id, &self.tick())?;
tx.commit()?;
Ok(())
}
@@ -437,6 +484,11 @@ impl Graph {
properties: Properties::new(),
created_at: ms,
updated_at: ms,
kind: PageKind::Note,
description: String::new(),
hubs: Vec::new(),
tags: Vec::new(),
types: Vec::new(),
};
self.write_page(&page, &self.tick())?;
Ok(page)
@@ -593,6 +645,7 @@ impl Graph {
/// Inserts a new block with `content` and indexes its refs.
pub fn insert_block(&self, page: PageId, at: Placement, content: &str) -> Result<Block> {
self.ensure_not_hub(page)?;
let tx = self.tx()?;
let (parent_id, position) = self.resolve_placement(page, at)?;
let now = self.now_ms();
@@ -615,6 +668,7 @@ impl Graph {
/// Writes a fully specified block (importer). Pages referenced by it are created, born in
/// the block's journal when it lives in one. Does not record edit activity.
pub fn put_block(&self, block: &Block) -> Result<()> {
self.ensure_not_hub(block.page_id)?;
let tx = self.tx()?;
self.write_block(block, &self.tick())?;
self.ensure_ref_pages(block)?;
@@ -660,6 +714,7 @@ impl Graph {
/// Moves a block (with its subtree) to a new place, possibly on another page.
pub fn move_block(&self, id: BlockId, page: PageId, at: Placement) -> Result<Block> {
self.ensure_not_hub(page)?;
let tx = self.tx()?;
let mut b = self
.get_block(id)?
@@ -712,6 +767,21 @@ impl Graph {
Ok(())
}
/// Hubs have no outline: block writes into them are refused.
fn ensure_not_hub(&self, page: PageId) -> Result<()> {
let kind: Option<String> = self
.row(
"SELECT kind FROM pages WHERE id=?1",
[page.to_string()],
|r| r.get(0),
)
.optional()?;
if kind.as_deref() == Some(PageKind::Hub.as_str()) {
return Err(Error::Invalid("hubs have no blocks".into()));
}
Ok(())
}
fn descendants(&self, id: BlockId) -> Result<Vec<BlockId>> {
let mut st = self.conn.prepare_cached(
"WITH RECURSIVE d(id) AS (SELECT id FROM blocks WHERE parent_id=?1
@@ -878,7 +948,7 @@ impl Graph {
}
/// Bumps `updated_at` and records today's activity for a page.
fn touch_page(&self, page: PageId) -> Result<()> {
pub(crate) fn touch_page(&self, page: PageId) -> Result<()> {
let now = self.now_ms();
let day = journal_title(day_of(now));
self.exec(
@@ -1110,11 +1180,11 @@ impl Graph {
// ----------------------------------------------------------- raw writes
fn tick(&self) -> String {
pub(crate) fn tick(&self) -> String {
self.clock.tick(self.now_ms())
}
fn log(&self, hlc: &str, op: &Op) -> Result<()> {
pub(crate) fn log(&self, hlc: &str, op: &Op) -> Result<()> {
self.exec(
"INSERT INTO ops(hlc, payload) VALUES (?1, ?2)",
params![hlc, serde_json::to_string(op)?],
@@ -1122,17 +1192,17 @@ impl Graph {
Ok(())
}
fn write_page(&self, page: &Page, hlc: &str) -> Result<()> {
pub(crate) fn write_page(&self, page: &Page, hlc: &str) -> Result<()> {
self.write_page_row(page, hlc)?;
self.log(hlc, &Op::UpsertPage { page: page.clone() })
}
fn write_page_row(&self, p: &Page, hlc: &str) -> Result<()> {
self.exec(
"INSERT INTO pages(id, title, title_key, journal_date, origin_journal, properties, created_at, updated_at, hlc)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
"INSERT INTO pages(id, title, title_key, journal_date, origin_journal, properties, created_at, updated_at, hlc, kind, description, hubs, tags, types)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)
ON CONFLICT(id) DO UPDATE SET title=?2, title_key=?3, journal_date=?4, origin_journal=?5,
properties=?6, created_at=?7, updated_at=?8, hlc=?9",
properties=?6, created_at=?7, updated_at=?8, hlc=?9, kind=?10, description=?11, hubs=?12, tags=?13, types=?14",
params![
p.id.to_string(),
p.title,
@@ -1142,9 +1212,30 @@ impl Graph {
serde_json::to_string(&p.properties)?,
p.created_at,
p.updated_at,
hlc
hlc,
p.kind.as_str(),
p.description,
serde_json::to_string(&p.hubs)?,
serde_json::to_string(&p.tags)?,
serde_json::to_string(&p.types)?
],
)?;
let id = p.id.to_string();
self.exec("DELETE FROM page_tags WHERE page_id=?1", [&id])?;
for t in &p.tags {
self.exec(
"INSERT OR IGNORE INTO page_tags(page_id, tag_key) VALUES (?1, ?2)",
params![id, title_key(t)],
)?;
}
self.exec("DELETE FROM page_hubs WHERE page_id=?1", [&id])?;
// A page belongs to one hub: only the first entry counts (older replicas may sync more).
for h in p.hubs.iter().take(1) {
self.exec(
"INSERT OR IGNORE INTO page_hubs(page_id, hub_id) VALUES (?1, ?2)",
params![id, h.to_string()],
)?;
}
Ok(())
}
@@ -1177,6 +1268,10 @@ impl Graph {
.execute("DELETE FROM page_activity WHERE page_id=?1", [&s])?;
self.conn
.execute("DELETE FROM synapses WHERE a=?1 OR b=?1", [&s])?;
// Only the page's own memberships: rows naming it as a hub mirror other pages'
// `hubs` and dangle until those pages are rewritten.
self.exec("DELETE FROM page_hubs WHERE page_id=?1", [&s])?;
self.exec("DELETE FROM page_tags WHERE page_id=?1", [&s])?;
self.exec(
"INSERT OR REPLACE INTO tombstones(id, hlc) VALUES (?1, ?2)",
params![s, hlc],
@@ -1329,7 +1424,7 @@ impl Graph {
}
/// Savepoint guard: rolled back on drop unless committed.
struct Tx<'a> {
pub(crate) struct Tx<'a> {
conn: &'a Connection,
/// Whether this guard opened a savepoint (false when nested in a transaction).
active: bool,
@@ -1337,7 +1432,7 @@ struct Tx<'a> {
}
impl Tx<'_> {
fn commit(mut self) -> Result<()> {
pub(crate) fn commit(mut self) -> Result<()> {
if self.active {
self.conn.execute_batch("RELEASE graph")?;
}
@@ -1397,6 +1492,11 @@ fn page_row(r: &Row) -> rusqlite::Result<Page> {
properties: props(r.get(4)?),
created_at: r.get(5)?,
updated_at: r.get(6)?,
kind: PageKind::parse(&r.get::<_, String>(7)?),
description: r.get(8)?,
hubs: serde_json::from_str(&r.get::<_, String>(9)?).unwrap_or_default(),
tags: serde_json::from_str(&r.get::<_, String>(10)?).unwrap_or_default(),
types: serde_json::from_str(&r.get::<_, String>(11)?).unwrap_or_default(),
})
}
File diff suppressed because it is too large. Load diff
+226
View File
@@ -0,0 +1,226 @@
//! Tags: topic pages ("neurociencia", "finanzas") that notes are filed under.
//!
//! A tag is a page of kind [`PageKind::Tag`]: it has an outline, backlinks and a place in the
//! graph like any note. A page lists the titles of its tag pages in [`Page::tags`] (synced
//! with the page, last writer wins), any number of them, and a derived `page_tags` index
//! answers "which pages have this tag". Tagging with a title that has no page creates the tag
//! page; tagging with an existing note turns that note into a tag page. Renaming or deleting
//! a tag page keeps its members in step. Names compare case-insensitively ([`title_key`]).
//! What a page *is* ("persona", "lugar") is a different, name-only mechanism: see `types`.
use crate::error::{Error, Result};
use crate::model::{NewPage, Page, PageId, PageKind, title_key};
use crate::store::{Graph, parse_id};
use std::collections::HashMap;
/// Longest tag (or type) name, in characters.
pub const MAX_TAG_CHARS: usize = 48;
/// A tag with the number of pages filed under it (tag pages with no members count 0).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TagInfo {
pub name: String,
pub count: u32,
/// Part of the seeded suggestions (types only; tag pages are never seeded).
pub suggested: bool,
}
/// Cleans a tag name: leading `#` dropped, whitespace collapsed. `None` when nothing is left.
pub fn normalize_tag(raw: &str) -> Option<String> {
let t = raw.trim().trim_start_matches('#');
let t = t.split_whitespace().collect::<Vec<_>>().join(" ");
(!t.is_empty()).then_some(t)
}
impl Graph {
/// The tag page called `name`, created (or made out of a note of that name) on demand.
fn ensure_tag_page(&self, name: &str) -> Result<Page> {
if let Some(mut p) = self.page_by_title(name)? {
return match p.kind {
PageKind::Tag => Ok(p),
PageKind::Note if !p.is_journal() => {
p.kind = PageKind::Tag;
p.updated_at = self.now_ms();
self.write_page(&p, &self.tick())?;
Ok(p)
}
_ => Err(Error::Invalid(format!(
"{name:?} is a hub, template or journal and cannot be a tag"
))),
};
}
self.create_page_kind_tx(NewPage::titled(name), PageKind::Tag, String::new())
}
/// Replaces the tags of `page` (names cleaned, duplicates dropped case-insensitively,
/// order kept; each becomes the title of a tag page). Journals, templates and tag pages
/// cannot be tagged, nor can a page be tagged with itself.
pub fn set_page_tags(&self, page: PageId, tags: Vec<String>) -> Result<Page> {
let tx = self.tx()?;
let mut p = self
.get_page(page)?
.ok_or_else(|| Error::NotFound(page.to_string()))?;
let mut wanted: Vec<String> = Vec::with_capacity(tags.len());
for raw in tags {
let Some(t) = normalize_tag(&raw) else {
continue;
};
if t.chars().count() > MAX_TAG_CHARS {
return Err(Error::Invalid(format!(
"tag {t:?} is longer than {MAX_TAG_CHARS} characters"
)));
}
if !wanted.iter().any(|x| title_key(x) == title_key(&t)) {
wanted.push(t);
}
}
if (p.is_journal() || p.is_template() || p.is_tag()) && !wanted.is_empty() {
return Err(Error::Invalid(
"journals, templates and tag pages cannot have tags".into(),
));
}
if wanted.iter().any(|t| title_key(t) == title_key(&p.title)) {
return Err(Error::Invalid("a page cannot be its own tag".into()));
}
let mut next = Vec::with_capacity(wanted.len());
for t in wanted {
next.push(self.ensure_tag_page(&t)?.title);
}
if next == p.tags {
tx.commit()?;
return Ok(p);
}
p.tags = next;
p.updated_at = self.now_ms();
self.write_page(&p, &self.tick())?;
tx.commit()?;
Ok(p)
}
/// Adds a tag (no-op when the page already has it).
pub fn add_page_tag(&self, page: PageId, tag: &str) -> Result<Page> {
let p = self
.get_page(page)?
.ok_or_else(|| Error::NotFound(page.to_string()))?;
let mut tags = p.tags;
tags.push(tag.to_string());
self.set_page_tags(page, tags)
}
/// Removes a tag (no-op when the page does not have it). The tag page stays.
pub fn remove_page_tag(&self, page: PageId, tag: &str) -> Result<Page> {
let p = self
.get_page(page)?
.ok_or_else(|| Error::NotFound(page.to_string()))?;
let key = title_key(tag);
let tags = p.tags.into_iter().filter(|t| title_key(t) != key).collect();
self.set_page_tags(page, tags)
}
/// Pages carrying `tag`, most recently updated first.
pub fn pages_with_tag(&self, tag: &str) -> Result<Vec<PageId>> {
let mut st = self.conn().prepare_cached(
"SELECT p.id FROM page_tags t JOIN pages p ON p.id = t.page_id
WHERE t.tag_key=?1 ORDER BY p.updated_at DESC, p.id",
)?;
let rows = st.query_map([title_key(tag)], |r| r.get::<_, String>(0))?;
rows.map(|r| parse_id(&r?)).collect()
}
/// Tags of every tagged page, as stored.
pub fn all_page_tags(&self) -> Result<HashMap<PageId, Vec<String>>> {
let mut st = self
.conn()
.prepare_cached("SELECT id, tags FROM pages WHERE tags != '[]'")?;
let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
let mut out = HashMap::new();
for row in rows {
let (id, tags) = row?;
out.insert(
parse_id(&id)?,
serde_json::from_str(&tags).unwrap_or_default(),
);
}
Ok(out)
}
/// Every tag page with the number of pages under it: most used first, then by name.
pub fn tag_catalog(&self) -> Result<Vec<TagInfo>> {
let mut st = self.conn().prepare_cached(
"SELECT p.title, (SELECT COUNT(*) FROM page_tags t WHERE t.tag_key = p.title_key)
FROM pages p WHERE p.kind = 'tag'",
)?;
let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, u32>(1)?)))?;
let mut out = Vec::new();
for row in rows {
let (name, count) = row?;
out.push(TagInfo {
name,
count,
suggested: false,
});
}
out.sort_by(|a, b| {
b.count
.cmp(&a.count)
.then_with(|| title_key(&a.name).cmp(&title_key(&b.name)))
});
Ok(out)
}
/// A tag page was renamed: its members now list the new title.
pub(crate) fn retitle_tag(&self, old: &str, new: &str) -> Result<()> {
for id in self.pages_with_tag(old)? {
if let Some(mut p) = self.get_page(id)? {
let key = title_key(old);
for t in &mut p.tags {
if title_key(t) == key {
*t = new.to_string();
}
}
self.write_page(&p, &self.tick())?;
}
}
Ok(())
}
/// A tag page was deleted: its members stop listing it.
pub(crate) fn drop_tag_from_members(&self, title: &str) -> Result<()> {
let key = title_key(title);
for id in self.pages_with_tag(title)? {
if let Some(mut p) = self.get_page(id)? {
p.tags.retain(|t| title_key(t) != key);
self.write_page(&p, &self.tick())?;
}
}
Ok(())
}
/// Databases from before tag pages (or snapshots of them) list tags that have no page:
/// create the missing pages, keeping the spelling first used.
pub(crate) fn repair_tag_pages(&self) -> Result<()> {
let missing: Vec<String> = {
let mut st = self.conn().prepare_cached(
"SELECT DISTINCT tag_key FROM page_tags
WHERE tag_key NOT IN (SELECT title_key FROM pages)",
)?;
st.query_map([], |r| r.get(0))?
.collect::<std::result::Result<_, _>>()?
};
if missing.is_empty() {
return Ok(());
}
let tx = self.tx()?;
let mut done = std::collections::HashSet::new();
for (_, tags) in self.all_page_tags()? {
for t in tags {
let key = title_key(&t);
if missing.contains(&key) && done.insert(key) {
self.ensure_tag_page(&t)?;
}
}
}
tx.commit()?;
Ok(())
}
}
+128
View File
@@ -0,0 +1,128 @@
//! Types: what kind of thing a page is ("persona", "lugar", "empresa").
//!
//! Types are plain names from a small vocabulary, not pages: a page carries its own list
//! ([`Page::types`], synced with the page, last writer wins). Topics are a different
//! mechanism: see `tags`.
use crate::error::{Error, Result};
use crate::model::{Page, PageId, title_key};
use crate::store::Graph;
use crate::tags::{MAX_TAG_CHARS, TagInfo, normalize_tag};
use std::collections::HashMap;
/// Types offered in pickers before they are used anywhere (the seed of the vocabulary).
pub const SUGGESTED_TYPES: [&str; 10] = [
"persona",
"lugar",
"empresa",
"cliente",
"herramienta",
"concepto",
"idea",
"evento",
"recurso",
"receta",
];
impl Graph {
/// Replaces the types of `page` (names cleaned, duplicates dropped case-insensitively,
/// order kept). Journals and templates cannot be typed.
pub fn set_page_types(&self, page: PageId, types: Vec<String>) -> Result<Page> {
let tx = self.tx()?;
let mut p = self
.get_page(page)?
.ok_or_else(|| Error::NotFound(page.to_string()))?;
let mut next: Vec<String> = Vec::with_capacity(types.len());
for raw in types {
let Some(t) = normalize_tag(&raw) else {
continue;
};
if t.chars().count() > MAX_TAG_CHARS {
return Err(Error::Invalid(format!(
"type {t:?} is longer than {MAX_TAG_CHARS} characters"
)));
}
if !next.iter().any(|x| title_key(x) == title_key(&t)) {
next.push(t);
}
}
if next == p.types {
tx.commit()?;
return Ok(p);
}
if (p.is_journal() || p.is_template()) && !next.is_empty() {
return Err(Error::Invalid(
"journals and templates cannot have types".into(),
));
}
p.types = next;
p.updated_at = self.now_ms();
self.write_page(&p, &self.tick())?;
tx.commit()?;
Ok(p)
}
/// Adds a type (no-op when the page already has it).
pub fn add_page_type(&self, page: PageId, ty: &str) -> Result<Page> {
let p = self
.get_page(page)?
.ok_or_else(|| Error::NotFound(page.to_string()))?;
let mut types = p.types;
types.push(ty.to_string());
self.set_page_types(page, types)
}
/// Removes a type (no-op when the page does not have it).
pub fn remove_page_type(&self, page: PageId, ty: &str) -> Result<Page> {
let p = self
.get_page(page)?
.ok_or_else(|| Error::NotFound(page.to_string()))?;
let key = title_key(ty);
let types = p
.types
.into_iter()
.filter(|t| title_key(t) != key)
.collect();
self.set_page_types(page, types)
}
/// The vocabulary: every type in use (spelling of its first page) plus the suggestions not
/// used yet. Used types first by count then name, then unused suggestions in seed order.
pub fn type_catalog(&self) -> Result<Vec<TagInfo>> {
let mut st = self.conn().prepare_cached(
"SELECT types FROM pages WHERE types != '[]' ORDER BY created_at, id",
)?;
let rows = st.query_map([], |r| r.get::<_, String>(0))?;
let mut used: HashMap<String, (String, u32)> = HashMap::new();
for row in rows {
let types: Vec<String> = serde_json::from_str(&row?).unwrap_or_default();
for t in types {
used.entry(title_key(&t)).or_insert((t, 0)).1 += 1;
}
}
let suggested = |k: &str| SUGGESTED_TYPES.iter().any(|s| title_key(s) == k);
let mut out: Vec<TagInfo> = used
.iter()
.map(|(k, (name, count))| TagInfo {
name: name.clone(),
count: *count,
suggested: suggested(k),
})
.collect();
out.sort_by(|a, b| {
b.count
.cmp(&a.count)
.then_with(|| title_key(&a.name).cmp(&title_key(&b.name)))
});
for s in SUGGESTED_TYPES {
if !used.contains_key(&title_key(s)) {
out.push(TagInfo {
name: s.to_string(),
count: 0,
suggested: true,
});
}
}
Ok(out)
}
}
+806
View File
@@ -0,0 +1,806 @@
use serde_json::json;
use synapse_core::{
Error, Graph, HubConversion, NewPage, Op, PageId, PageKind, Placement, is_legacy_page,
namespace_parent,
};
fn graph() -> (tempfile::TempDir, Graph) {
let dir = tempfile::tempdir().unwrap();
let g = Graph::open(dir.path()).unwrap();
(dir, g)
}
fn page(g: &Graph, title: &str, blocks: &[&str]) -> PageId {
let p = g.ensure_page(title, None).unwrap();
for b in blocks {
g.insert_block(p.id, Placement::LastChildOf(None), b)
.unwrap();
}
p.id
}
fn hub(g: &Graph, title: &str) -> PageId {
g.create_hub(title, "").unwrap().id
}
fn titles(g: &Graph, ids: &[PageId]) -> Vec<String> {
ids.iter()
.map(|&i| g.get_page(i).unwrap().unwrap().title)
.collect()
}
fn texts(g: &Graph, id: PageId) -> Vec<(usize, String)> {
g.page_tree(id)
.unwrap()
.into_iter()
.map(|(d, b)| (d, b.content))
.collect()
}
fn invalid<T: std::fmt::Debug>(r: synapse_core::Result<T>) -> bool {
matches!(r, Err(Error::Invalid(_)))
}
/// Ships every op of `from` newer than `after` to `to`; returns how many applied.
fn ship(from: &Graph, to: &Graph, after: i64) -> usize {
from.ops_since(after, 100_000)
.unwrap()
.iter()
.filter(|r| to.apply_remote(&r.hlc, &r.op).unwrap())
.count()
}
#[test]
fn a_page_belongs_to_at_most_one_hub() {
let (_d, g) = graph();
let media = g.create_hub("Media", " Things I watch ").unwrap();
assert_eq!(media.kind, PageKind::Hub);
assert_eq!(media.description, "Things I watch");
let work = hub(&g, "Work");
let books = hub(&g, "Books");
let zeta = page(&g, "Zeta", &["z"]);
let alpha = page(&g, "Alpha", &["a"]);
g.add_to_hub(zeta, media.id).unwrap();
g.add_to_hub(alpha, media.id).unwrap();
g.add_to_hub(books, media.id).unwrap();
// Duplicates are no-ops.
let seq = g.last_seq().unwrap();
g.add_to_hub(alpha, media.id).unwrap();
assert_eq!(g.last_seq().unwrap(), seq);
// Sub-hubs first, then notes, each by title.
assert_eq!(
titles(&g, &g.hub_members(media.id).unwrap()),
["Books", "Alpha", "Zeta"]
);
assert_eq!(titles(&g, &g.hubs_of(alpha).unwrap()), ["Media"]);
// A page lives in one hub: adding it elsewhere moves it.
g.add_to_hub(alpha, work).unwrap();
assert_eq!(titles(&g, &g.hubs_of(alpha).unwrap()), ["Work"]);
assert_eq!(g.get_page(alpha).unwrap().unwrap().hubs, [work]);
assert_eq!(
titles(&g, &g.hub_members(media.id).unwrap()),
["Books", "Zeta"]
);
assert!(invalid(g.set_page_hubs(zeta, vec![work, media.id])));
let p = g.set_page_hubs(zeta, vec![work, work]).unwrap();
assert_eq!(p.hubs, [work]);
g.remove_from_hub(zeta, work).unwrap();
assert!(g.hubs_of(zeta).unwrap().is_empty());
// A template cannot leave its hub.
let t = g.hub_template(work).unwrap();
assert!(invalid(g.add_to_hub(t, media.id)));
let s = g.set_hub_description(media.id, "Screen and paper").unwrap();
assert_eq!(s.description, "Screen and paper");
assert!(invalid(g.set_hub_description(zeta, "x")));
}
#[test]
fn hubs_have_no_blocks() {
let (_d, g) = graph();
let h = hub(&g, "Hub");
let n = page(&g, "Note", &["one"]);
assert!(invalid(g.insert_block(
h,
Placement::LastChildOf(None),
"x"
)));
let b = g.page_tree(n).unwrap()[0].1.clone();
assert!(invalid(g.move_block(b.id, h, Placement::LastChildOf(None))));
let mut moved = b.clone();
moved.page_id = h;
assert!(invalid(g.put_block(&moved)));
assert!(g.page_tree(h).unwrap().is_empty());
// A date title cannot be a hub.
assert!(invalid(g.create_hub("2024-01-02", "")));
}
#[test]
fn membership_validation_and_cycles() {
let (_d, g) = graph();
let a = hub(&g, "A");
let b = hub(&g, "B");
let c = hub(&g, "C");
let note = page(&g, "Note", &[]);
let j = g
.journal(chrono::NaiveDate::from_ymd_opt(2024, 1, 2).unwrap())
.unwrap();
g.add_to_hub(b, a).unwrap(); // A ⊃ B
g.add_to_hub(c, b).unwrap(); // B ⊃ C
assert!(invalid(g.add_to_hub(a, a)), "self");
assert!(invalid(g.add_to_hub(a, c)), "A inside C would be a cycle");
assert!(invalid(g.add_to_hub(a, b)), "direct cycle");
assert!(invalid(g.add_to_hub(j.id, a)), "journals are never members");
assert!(invalid(g.add_to_hub(note, note)));
assert!(invalid(g.add_to_hub(a, note)), "a note is not a hub");
assert!(matches!(
g.add_to_hub(note, synapse_core::new_id()),
Err(Error::NotFound(_))
));
// A note can be in a hub nested anywhere; a hub can be in two branches (DAG).
g.add_to_hub(note, c).unwrap();
g.add_to_hub(c, a).unwrap();
let s = g.structure().unwrap();
let info = |id| s.hubs.iter().find(|h| h.page == id).unwrap();
assert_eq!(info(a).members, [b, c]);
assert_eq!(info(c).depth, 1, "shortest path from a root");
assert_eq!(s.home[&note], c);
}
#[test]
fn delete_page_cleans_memberships() {
let (_d, g) = graph();
let h = hub(&g, "H");
let other = hub(&g, "Other");
let n = page(&g, "N", &["x"]);
g.add_to_hub(n, h).unwrap();
g.add_to_hub(h, other).unwrap();
let seq = g.last_seq().unwrap();
g.delete_page(h).unwrap();
assert!(g.get_page(n).unwrap().unwrap().hubs.is_empty());
let logged: Vec<_> = g
.ops_since(seq, 100)
.unwrap()
.into_iter()
.filter_map(|r| match r.op {
Op::UpsertPage { page } => Some(page),
_ => None,
})
.collect();
assert!(logged.iter().any(|p| p.id == n && p.hubs.is_empty()));
assert!(g.hub_members(other).unwrap().is_empty());
g.delete_page(n).unwrap();
let s = g.structure().unwrap();
assert_eq!(s.hubs.len(), 1);
assert!(s.hubs[0].members.is_empty());
}
#[test]
fn conversion_preview() {
let (_d, g) = graph();
g.set_now(Some(1_700_000_000_000));
let p = page(
&g,
"Entretenimiento/TV/Anime",
&[
"## Series",
"[[Naruto]]",
"#Bleach, [[2024-01-02]]",
"type:: [[Genre]]",
"My **favourite** ones, see [[One Piece]] and #[[Death Note]]",
"[[Entretenimiento/TV/Anime]]",
"[[Naruto]] again with words",
],
);
// A dangling alias (its page is gone) must not break anything.
let gone = page(&g, "Gone", &[]);
g.set_alias("Ghost", Some(gone)).unwrap();
g.conn()
.execute("DELETE FROM pages WHERE id=?1", [gone.to_string()])
.unwrap();
page(&g, "Uses", &["mentions [[Ghost]]"]);
let prop = page(&g, "Props", &[]);
let mut props = serde_json::Map::new();
props.insert("parent".into(), json!("[[Entretenimiento/TV/Anime]]"));
g.set_page_properties(prop, props).unwrap();
g.set_alias("Animu", Some(p)).unwrap();
page(&g, "Tagger", &["watch #Animu"]);
page(
&g,
"BlockProp",
&["x\ncategory:: [[Entretenimiento/TV/Anime]]"],
);
let j = g
.journal(chrono::NaiveDate::from_ymd_opt(2024, 3, 3).unwrap())
.unwrap();
g.insert_block(j.id, Placement::LastChildOf(None), "#Animu")
.unwrap();
let pv = g.hub_conversion_preview(p).unwrap();
assert_eq!(pv.suggested_title, "Anime");
assert_eq!(
pv.suggested_description,
"My favourite ones, see One Piece and Death Note"
);
assert_eq!(
titles(&g, &pv.members),
[
"Naruto",
"Bleach",
"One Piece",
"Death Note",
"Props",
"BlockProp",
"Tagger"
]
);
assert_eq!(pv.prose_blocks, 2);
assert_eq!(pv.blocks, 7);
let plain = page(&g, "Plain", &[]);
let pv = g.hub_conversion_preview(plain).unwrap();
assert_eq!(pv.suggested_title, "Plain");
assert!(pv.suggested_description.is_empty() && pv.members.is_empty());
assert!(invalid(g.hub_conversion_preview(j.id)));
let h = hub(&g, "Hub");
assert!(invalid(g.hub_conversion_preview(h)));
}
#[test]
fn convert_to_hub_shortens_title_and_keeps_outline() {
let (_d, g) = graph();
let p = page(&g, "Media/Anime", &["Intro text", "[[Naruto]]"]);
let root = g.page_tree(p).unwrap()[0].1.id;
g.insert_block(p, Placement::LastChildOf(Some(root)), "child")
.unwrap();
let parent = hub(&g, "Media");
g.add_to_hub(p, parent).unwrap();
let refr = page(&g, "Elsewhere", &["see [[Media/Anime]]"]);
let naruto = g.page_by_title("Naruto").unwrap().unwrap().id;
let j = g
.journal(chrono::NaiveDate::from_ymd_opt(2024, 1, 2).unwrap())
.unwrap();
let h = g
.convert_to_hub(
p,
&HubConversion {
title: "Anime".into(),
description: " Japanese animation ".into(),
// Journals and cycles (the hub's own parent) are skipped silently.
members: vec![naruto, j.id, parent, naruto],
keep_outline_as: Some("Anime (notes)".into()),
},
)
.unwrap();
assert_eq!(h.title, "Anime");
assert!(h.is_hub() && h.description == "Japanese animation");
assert_eq!(h.hubs, [parent], "the hub stays where it was");
assert!(g.page_tree(p).unwrap().is_empty());
assert_eq!(texts(&g, refr), [(0, "see [[Anime]]".to_string())]);
let note = g.page_by_title("Anime (notes)").unwrap().unwrap();
assert_eq!(
texts(&g, note.id),
[
(0, "Intro text".to_string()),
(1, "child".to_string()),
(0, "[[Naruto]]".to_string())
]
);
assert_eq!(
titles(&g, &g.hub_members(p).unwrap()),
["Anime (notes)", "Naruto"]
);
assert!(g.get_page(parent).unwrap().unwrap().hubs.is_empty());
// Back to a note: description, then one link per member; members leave the hub.
let n = g.convert_to_note(p).unwrap();
assert_eq!(n.kind, PageKind::Note);
assert!(n.description.is_empty());
assert_eq!(
texts(&g, p),
[
(0, "Japanese animation".to_string()),
(0, "[[Anime (notes)]]".to_string()),
(0, "[[Naruto]]".to_string())
]
);
assert!(g.hub_members(p).unwrap().is_empty());
assert!(g.get_page(naruto).unwrap().unwrap().hubs.is_empty());
assert!(invalid(g.convert_to_note(p)));
}
#[test]
fn convert_to_hub_without_outline_and_title_clash() {
let (_d, g) = graph();
let p = page(&g, "Projects/Ideas", &["[[A]]", "some prose"]);
page(&g, "Ideas", &["taken"]);
let before = g.last_seq().unwrap();
let clash = g.convert_to_hub(
p,
&HubConversion {
title: "Ideas".into(),
..Default::default()
},
);
assert!(matches!(clash, Err(Error::Conflict(_))), "{clash:?}");
// Nothing changed.
assert_eq!(g.last_seq().unwrap(), before);
let cur = g.get_page(p).unwrap().unwrap();
assert_eq!(cur.title, "Projects/Ideas");
assert!(!cur.is_hub());
assert_eq!(g.page_tree(p).unwrap().len(), 2);
// An existing title for the kept-outline note is refused too.
let clash = g.convert_to_hub(
p,
&HubConversion {
title: "Projects/Ideas".into(),
keep_outline_as: Some("ideas".into()),
..Default::default()
},
);
assert!(matches!(clash, Err(Error::Conflict(_))));
assert_eq!(g.page_tree(p).unwrap().len(), 2);
let a = g.page_by_title("A").unwrap().unwrap().id;
let h = g
.convert_to_hub(
p,
&HubConversion {
title: "Projects/Ideas".into(),
description: String::new(),
members: vec![a],
keep_outline_as: None,
},
)
.unwrap();
assert_eq!(h.title, "Projects/Ideas");
assert!(g.page_tree(p).unwrap().is_empty());
assert_eq!(g.hub_members(p).unwrap(), [a]);
assert!(invalid(g.convert_to_hub(p, &HubConversion::default())));
}
#[test]
fn structure_depth_home_and_dangling_ids() {
let (_d, g) = graph();
let root = hub(&g, "Root");
let sub = hub(&g, "Sub");
let leaf = page(&g, "Leaf", &[]);
let r1 = page(&g, "R1", &[]);
g.add_to_hub(sub, root).unwrap();
g.add_to_hub(leaf, sub).unwrap();
g.add_to_hub(r1, root).unwrap();
// Dangling ids: a deleted page and a note.
let gone = synapse_core::new_id();
let mut p = g.get_page(r1).unwrap().unwrap();
p.hubs.push(gone);
p.hubs.push(leaf);
g.put_page(&p).unwrap();
let s = g.structure().unwrap();
let info = |id| s.hubs.iter().find(|h| h.page == id).unwrap();
assert_eq!((info(root).depth, info(sub).depth), (0, 1));
assert_eq!(info(root).members, [sub, r1]);
assert_eq!(info(sub).members, [leaf]);
assert_eq!(s.home[&leaf], sub, "deepest wins");
assert_eq!(
(s.home[&sub], s.home[&root], s.home[&r1]),
(sub, root, root)
);
assert_eq!(s.hubs.len(), 2);
assert_eq!(g.hubs_of(r1).unwrap(), [root]);
let alone = page(&g, "Alone", &[]);
assert!(!g.structure().unwrap().home.contains_key(&alone));
}
#[test]
fn replicas_converge_in_any_order_and_break_concurrent_cycles() {
let (_a, a) = graph();
let (_b, b) = graph();
let h = a.create_hub("Hub", "desc").unwrap().id;
let x = hub(&a, "X");
let n = page(&a, "Note", &["text"]);
a.add_to_hub(n, h).unwrap();
a.add_to_hub(x, h).unwrap();
// Out of order: members' pages arrive before the hub page.
let mut ops = a.ops_since(0, 1000).unwrap();
ops.reverse();
for r in &ops {
b.apply_remote(&r.hlc, &r.op).unwrap();
}
let hub_b = b.get_page(h).unwrap().unwrap();
assert!(hub_b.is_hub() && hub_b.description == "desc");
assert_eq!(b.structure().unwrap(), a.structure().unwrap());
assert_eq!(b.hub_members(h).unwrap(), [x, n]);
// Idempotent: replaying applies nothing; applied ops were re-logged on B.
assert_eq!(ship(&a, &b, 0), 0);
assert!(
b.ops_since(0, 1000)
.unwrap()
.iter()
.any(|r| matches!(&r.op, Op::UpsertPage { page } if page.id == n && page.hubs == [h]))
);
// Hub deletion on B reaches A, members included.
let seq_b = b.last_seq().unwrap();
b.delete_page(x).unwrap();
ship(&b, &a, seq_b);
assert!(a.get_page(x).unwrap().is_none());
assert_eq!(a.hub_members(h).unwrap(), [n]);
// Concurrent cycle: A puts Y in Z while B puts Z in Y.
let y = hub(&a, "Y");
let z = hub(&a, "Z");
ship(&a, &b, 0);
let (sa, sb) = (a.last_seq().unwrap(), b.last_seq().unwrap());
a.add_to_hub(y, z).unwrap();
std::thread::sleep(std::time::Duration::from_millis(2));
b.add_to_hub(z, y).unwrap();
ship(&a, &b, sa);
ship(&b, &a, sb);
let (s1, s2) = (a.structure().unwrap(), b.structure().unwrap());
assert_eq!(s1, s2);
let members = |s: &synapse_core::Structure, id| {
s.hubs
.iter()
.find(|h| h.page == id)
.unwrap()
.members
.clone()
};
// The older write (Y in Z) stands; the one closing the cycle is ignored.
assert_eq!(members(&s1, z), [y]);
assert!(members(&s1, y).is_empty());
}
#[test]
fn old_ops_and_v2_databases_load() {
// An op written before page kinds existed.
let id = synapse_core::new_id();
let op: Op = serde_json::from_value(json!({
"type": "upsert_page",
"page": {"id": id, "title": "Old", "journal_date": null, "origin_journal": null,
"properties": {}, "created_at": 1, "updated_at": 2}
}))
.unwrap();
let Op::UpsertPage { page } = op else {
panic!()
};
assert_eq!(page.kind, PageKind::Note);
assert!(page.description.is_empty() && page.hubs.is_empty());
// A database created with the v2 schema.
let dir = tempfile::tempdir().unwrap();
{
let conn = rusqlite::Connection::open(dir.path().join("synapse.db")).unwrap();
conn.execute_batch(
"CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
INSERT INTO meta VALUES ('schema', '2'), ('actor', 'oldactor0001');
CREATE TABLE pages (
id TEXT PRIMARY KEY, title TEXT NOT NULL, title_key TEXT NOT NULL UNIQUE,
journal_date TEXT UNIQUE, origin_journal TEXT,
properties TEXT NOT NULL DEFAULT '{}', created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL, hlc TEXT NOT NULL);
CREATE TABLE aliases (alias_key TEXT PRIMARY KEY, alias TEXT NOT NULL,
page_id TEXT NOT NULL, hlc TEXT NOT NULL DEFAULT '');",
)
.unwrap();
conn.execute(
"INSERT INTO pages VALUES (?1, 'Legacy', 'legacy', NULL, NULL, '{}', 1, 2, '0000000000001-00000-oldactor0001')",
[id.to_string()],
)
.unwrap();
}
let g = Graph::open(dir.path()).unwrap();
let schema: String = g
.conn()
.query_row("SELECT value FROM meta WHERE key='schema'", [], |r| {
r.get(0)
})
.unwrap();
assert_eq!(schema, "5");
let p = g.get_page(id).unwrap().unwrap();
assert_eq!((p.kind, p.title.as_str()), (PageKind::Note, "Legacy"));
let h = g.create_hub("New hub", "").unwrap();
g.add_to_hub(id, h.id).unwrap();
assert_eq!(g.hub_members(h.id).unwrap(), [id]);
g.add_page_tag(id, "idea").unwrap();
assert_eq!(g.pages_with_tag("idea").unwrap(), [id]);
drop(g);
// Reopening keeps everything (migration is idempotent).
let g = Graph::open(dir.path()).unwrap();
assert_eq!(g.hub_members(h.id).unwrap(), [id]);
let n = g.create_page(NewPage::titled("After")).unwrap();
assert_eq!(n.kind, PageKind::Note);
}
#[test]
fn namespace_helpers() {
assert_eq!(namespace_parent("A/B/C"), Some("A/B"));
assert_eq!(namespace_parent("A / B"), Some("A"));
assert_eq!(namespace_parent("A"), None);
assert_eq!(namespace_parent("/A"), None);
assert_eq!(namespace_parent("A/"), None);
assert_eq!(namespace_parent("A//B"), None);
let (_d, g) = graph();
let ab = page(&g, "A/B", &[]);
let abc = page(&g, "A/B/C", &[]);
let ad = page(&g, "A/d", &[]);
page(&g, "X/Y/Z", &[]);
let kids = g.namespace_children("a").unwrap();
assert_eq!(
kids,
vec![("A/B".to_string(), Some(ab)), ("A/d".to_string(), Some(ad))]
);
assert_eq!(
g.namespace_children("A/B").unwrap(),
vec![("A/B/C".to_string(), Some(abc))]
);
// Virtual intermediate levels.
assert_eq!(
g.namespace_children("X").unwrap(),
vec![("X/Y".to_string(), None)]
);
assert_eq!(g.namespace_children("X/Y").unwrap().len(), 1);
assert!(g.namespace_children("nothing").unwrap().is_empty());
}
#[test]
fn legacy_titles() {
for t in [
"contents",
"TODO",
"All pages",
"hls__book_123",
"In-Progress",
] {
assert!(is_legacy_page(t), "{t}");
}
for t in ["Todo list", "Projects", "hls"] {
assert!(!is_legacy_page(t), "{t}");
}
}
#[test]
fn every_hub_has_a_hidden_template_that_seeds_new_notes() {
let (_d, g) = graph();
let h = hub(&g, "Fun");
let t = g.hub_template(h).unwrap();
assert_eq!(g.get_page(t).unwrap().unwrap().kind, PageKind::Template);
assert_eq!(g.hub_template(h).unwrap(), t, "idempotent");
// Hidden from members, listings and the structure.
assert!(g.hub_members(h).unwrap().is_empty());
assert!(
g.list_pages(true, 100, 0)
.unwrap()
.iter()
.all(|p| p.id != t)
);
assert!(g.structure().unwrap().hubs[0].members.is_empty());
let root = g
.insert_block(t, Placement::LastChildOf(None), "Rating")
.unwrap();
g.insert_block(t, Placement::LastChildOf(Some(root.id)), "Notes")
.unwrap();
let n = g.create_page_from_template(h, "Chess").unwrap();
assert_eq!(g.hubs_of(n.id).unwrap(), vec![h]);
assert_eq!(
texts(&g, n.id),
vec![(0, "Rating".to_string()), (1, "Notes".to_string())]
);
// An empty template is fine, and the template cannot be deleted alone.
let h2 = hub(&g, "Empty");
let n2 = g.create_page_from_template(h2, "Blank").unwrap();
assert!(texts(&g, n2.id).is_empty());
assert!(invalid(g.delete_page(t)));
g.delete_page(h).unwrap();
assert!(g.get_page(t).unwrap().is_none());
}
#[test]
fn converting_to_a_hub_creates_a_template_and_back_removes_it() {
let (_d, g) = graph();
let p = page(&g, "Projects", &["a"]);
g.convert_to_hub(
p,
&HubConversion {
title: "Projects".into(),
..Default::default()
},
)
.unwrap();
let t = g.hub_template(p).unwrap();
g.convert_to_note(p).unwrap();
assert!(g.get_page(t).unwrap().is_none());
}
#[test]
fn tags_are_pages_many_per_page() {
let (_d, g) = graph();
let a = page(&g, "Rust", &["x"]);
let b = page(&g, "Madrid", &["y"]);
g.add_page_tag(a, " #Tecnología ").unwrap();
g.add_page_tag(a, "herramientas").unwrap();
g.add_page_tag(a, "TECNOLOGÍA").unwrap(); // same tag, other case
g.add_page_tag(b, "Tecnología").unwrap();
assert_eq!(
g.get_page(a).unwrap().unwrap().tags,
["Tecnología", "herramientas"]
);
// The first use creates the tag page; it is an ordinary page of kind tag.
let tp = g.page_by_title("tecnología").unwrap().unwrap();
assert_eq!(tp.kind, PageKind::Tag);
assert_eq!(tp.title, "Tecnología");
g.insert_block(tp.id, Placement::LastChildOf(None), "About tech")
.unwrap();
assert_eq!(
g.pages_with_tag("tecnologia").unwrap().len(),
0,
"accents matter"
);
let mut with = g.pages_with_tag("Tecnología").unwrap();
with.sort();
let mut want = vec![a, b];
want.sort();
assert_eq!(with, want);
let cat = g.tag_catalog().unwrap();
assert_eq!((cat[0].name.as_str(), cat[0].count), ("Tecnología", 2));
assert_eq!((cat[1].name.as_str(), cat[1].count), ("herramientas", 1));
assert_eq!(cat.len(), 2, "no seeded tags: tags are pages you create");
g.remove_page_tag(a, "TECNOLOGÍA").unwrap();
assert_eq!(g.pages_with_tag("Tecnología").unwrap(), [b]);
assert!(
g.page_by_title("Tecnología").unwrap().is_some(),
"the tag page stays"
);
g.set_page_tags(a, vec![]).unwrap();
assert!(g.get_page(a).unwrap().unwrap().tags.is_empty());
// Rules.
let j = g
.journal(chrono::NaiveDate::from_ymd_opt(2026, 1, 2).unwrap())
.unwrap();
assert!(invalid(g.add_page_tag(j.id, "x")));
let h = hub(&g, "H");
let t = g.hub_template(h).unwrap();
assert!(invalid(g.add_page_tag(t, "x")));
assert!(invalid(g.add_page_tag(a, &"x".repeat(49))));
assert!(invalid(g.add_page_tag(a, "H")), "a hub cannot be a tag");
assert!(invalid(g.add_page_tag(a, "Rust")), "not its own tag");
assert!(
invalid(g.add_page_tag(tp.id, "x")),
"tag pages are not tagged"
);
g.add_page_tag(a, " ").unwrap(); // blank: ignored
assert!(g.get_page(a).unwrap().unwrap().tags.is_empty());
// Deleting a tagged page drops it from the index.
g.delete_page(b).unwrap();
assert!(g.pages_with_tag("Tecnología").unwrap().is_empty());
}
#[test]
fn a_note_becomes_a_tag_page_when_used_as_a_tag() {
let (_d, g) = graph();
let n = page(&g, "Neurociencia", &["brains", "memory"]);
let other = page(&g, "Plasticidad", &["x"]);
g.add_page_tag(other, "neurociencia").unwrap();
let p = g.get_page(n).unwrap().unwrap();
assert_eq!(p.kind, PageKind::Tag);
assert_eq!(texts(&g, n).len(), 2, "its content is kept");
assert_eq!(g.get_page(other).unwrap().unwrap().tags, ["Neurociencia"]);
}
#[test]
fn renaming_or_deleting_a_tag_page_keeps_members_in_step() {
let (_d, g) = graph();
let a = page(&g, "A", &["x"]);
let b = page(&g, "B", &["y"]);
g.add_page_tag(a, "web").unwrap();
g.add_page_tag(b, "Web").unwrap();
g.add_page_tag(b, "otro").unwrap();
let tag = g.page_by_title("web").unwrap().unwrap().id;
g.rename_page(tag, "Sitios web").unwrap();
assert_eq!(g.get_page(a).unwrap().unwrap().tags, ["Sitios web"]);
assert_eq!(g.get_page(b).unwrap().unwrap().tags, ["Sitios web", "otro"]);
assert_eq!(g.pages_with_tag("Sitios web").unwrap().len(), 2);
assert!(g.pages_with_tag("web").unwrap().is_empty());
g.delete_page(tag).unwrap();
assert!(g.get_page(a).unwrap().unwrap().tags.is_empty());
assert_eq!(g.get_page(b).unwrap().unwrap().tags, ["otro"]);
}
#[test]
fn tags_without_a_page_get_one_when_the_graph_opens() {
let dir = tempfile::tempdir().unwrap();
let id = {
let g = Graph::open(dir.path()).unwrap();
let id = page(&g, "Old", &["x"]);
g.add_page_tag(id, "Idea").unwrap();
// Simulate a pre-v5 database: the tag exists only on the note.
let tag = g.page_by_title("Idea").unwrap().unwrap().id;
g.conn()
.execute("DELETE FROM pages WHERE id=?1", [tag.to_string()])
.unwrap();
id
};
let g = Graph::open(dir.path()).unwrap();
let tag = g.page_by_title("idea").unwrap().unwrap();
assert_eq!((tag.kind, tag.title.as_str()), (PageKind::Tag, "Idea"));
assert_eq!(g.pages_with_tag("Idea").unwrap(), [id]);
}
#[test]
fn types_are_names_many_per_page_with_a_seeded_vocabulary() {
let (_d, g) = graph();
let a = page(&g, "Ana", &["x"]);
let b = page(&g, "Madrid", &["y"]);
let pages_before = g.list_pages(true, 100, 0).unwrap().len();
g.add_page_type(a, " Persona ").unwrap();
g.add_page_type(a, "cliente").unwrap();
g.add_page_type(a, "PERSONA").unwrap();
g.add_page_type(b, "lugar").unwrap();
assert_eq!(
g.get_page(a).unwrap().unwrap().types,
["Persona", "cliente"]
);
// Types never become pages.
assert_eq!(g.list_pages(true, 100, 0).unwrap().len(), pages_before);
assert!(g.page_by_title("persona").unwrap().is_none());
let cat = g.type_catalog().unwrap();
assert!(cat.iter().any(|t| t.name == "Persona" && t.count == 1));
let names: Vec<&str> = cat.iter().map(|t| t.name.as_str()).collect();
assert!(names.contains(&"empresa"), "unused suggestions are listed");
assert_eq!(
names
.iter()
.filter(|n| n.to_lowercase() == "persona")
.count(),
1
);
g.remove_page_type(a, "persona").unwrap();
assert_eq!(g.get_page(a).unwrap().unwrap().types, ["cliente"]);
let j = g
.journal(chrono::NaiveDate::from_ymd_opt(2026, 1, 2).unwrap())
.unwrap();
assert!(invalid(g.add_page_type(j.id, "x")));
}
#[test]
fn tags_sync_with_the_page() {
let (_a, a) = graph();
let (_b, b) = graph();
let p = page(&a, "Note", &["x"]);
a.add_page_tag(p, "idea").unwrap();
a.add_page_tag(p, "proyecto").unwrap();
a.add_page_type(p, "concepto").unwrap();
ship(&a, &b, 0);
let q = b.get_page(p).unwrap().unwrap();
assert_eq!(q.tags, ["idea", "proyecto"]);
assert_eq!(q.types, ["concepto"]);
assert_eq!(b.pages_with_tag("IDEA").unwrap(), [p]);
// The tag pages travel with it.
assert_eq!(
b.page_by_title("idea").unwrap().unwrap().kind,
PageKind::Tag
);
}
+111 -1
View File
@@ -14,6 +14,16 @@ pub struct PageDto {
pub origin_journal: Option<String>,
pub created_at: i64,
pub updated_at: i64,
/// The page is a hub (no blocks; members list instead of an outline).
pub is_hub: bool,
/// Hub description (empty for notes).
pub description: String,
/// Titles of the tag pages this page is filed under, in the order they were added.
pub tags: Vec<String>,
/// The page is a tag page (a topic that other pages are filed under).
pub is_tag: bool,
/// Type names ("persona", "lugar"...: plain names, not pages), in the order added.
pub types: Vec<String>,
}
impl From<&Page> for PageDto {
@@ -25,10 +35,25 @@ impl From<&Page> for PageDto {
origin_journal: p.origin_journal.map(journal_title),
created_at: p.created_at,
updated_at: p.updated_at,
is_hub: p.is_hub(),
description: p.description.clone(),
tags: p.tags.clone(),
is_tag: p.is_tag(),
types: p.types.clone(),
}
}
}
/// A tag or type of the vocabulary.
#[derive(Debug, Clone, PartialEq)]
pub struct TagDto {
pub name: String,
/// Pages using it.
pub count: u32,
/// One of the seeded suggestions.
pub suggested: bool,
}
/// One row of the outline, in pre-order.
#[derive(Debug, Clone, PartialEq)]
pub struct BlockDto {
@@ -95,6 +120,7 @@ pub struct PageBrief {
pub id: String,
pub title: String,
pub is_journal: bool,
pub is_hub: bool,
}
impl From<&Page> for PageBrief {
@@ -103,6 +129,7 @@ impl From<&Page> for PageBrief {
id: p.id.to_string(),
title: p.title.clone(),
is_journal: p.is_journal(),
is_hub: p.is_hub(),
}
}
}
@@ -181,6 +208,11 @@ pub mod edge_kind {
pub const MENTION: u8 = 5;
/// Hebbian association (undirected), weight = decayed synapse strength.
pub const SYNAPSE: u8 = 6;
/// Hub membership, hub → member (structural, weight 1).
pub const CONTAINS: u8 = 7;
/// A page filed under a tag page (page → tag page, weight 1). Unlike `TAG` (an inline
/// `#tag` in the text) it comes from the page's own `tags` list.
pub const TAGGED: u8 = 8;
}
#[derive(Debug, Clone, PartialEq)]
@@ -190,7 +222,8 @@ pub struct GraphNode {
pub journal_date: Option<String>,
pub origin_journal: Option<String>,
pub created_at: i64,
/// Distinct neighbours over structural edges (links, tags, properties, block refs).
/// Distinct neighbours over structural edges (links, tags, properties, block refs, hub
/// membership).
pub degree: u32,
/// Distinct pages referencing this one.
pub backlinks: u32,
@@ -198,6 +231,12 @@ pub struct GraphNode {
pub cluster: u32,
/// Node index of the tag this page uses most, if any.
pub primary_tag: Option<u32>,
/// The page is a hub (`PageKind::Hub`).
pub is_hub: bool,
/// Node index of the deepest hub containing this page (a hub: itself).
pub home_hub: Option<u32>,
/// Tag names of the page (see `PageDto::tags`), for grouping by tag.
pub tags: Vec<String>,
}
/// The whole page-level graph, edges as parallel arrays (cheap to move across the FFI).
@@ -223,3 +262,74 @@ pub struct LayoutFrame {
/// Remaining "temperature"; the layout is settled when it reaches 0.
pub alpha: f32,
}
/// A hub (folder-like page) with its members.
#[derive(Debug, Clone, PartialEq)]
pub struct HubDto {
pub id: String,
pub title: String,
pub description: String,
/// 0 for root hubs, one more per level of nesting.
pub depth: u32,
/// Sub-hubs first, then notes, each by title.
pub members: Vec<PageBrief>,
/// Ids of the members that are hubs themselves.
pub sub_hubs: Vec<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct HubsDto {
/// Sorted by title.
pub hubs: Vec<HubDto>,
/// Ids of the hubs that are not a member of any hub, by title.
pub roots: Vec<String>,
}
/// A level of a namespace (`A/B` under `A`); `id` is `None` when only deeper pages exist.
#[derive(Debug, Clone, PartialEq)]
pub struct NamespaceEntry {
pub title: String,
pub id: Option<String>,
}
/// Hub and namespace context of one page.
#[derive(Debug, Clone, PartialEq)]
pub struct PageStructure {
pub is_hub: bool,
/// Hub description (empty for notes).
pub description: String,
/// Empty unless the page is a hub; sub-hubs first, then notes.
pub members: Vec<PageBrief>,
/// Hubs the page belongs to (its own membership list), by title.
pub in_hubs: Vec<PageBrief>,
/// Ancestor namespaces from the root: `A`, `A/B` for `A/B/C` (they may not exist).
pub ns_path: Vec<NamespaceEntry>,
pub ns_children: Vec<NamespaceEntry>,
}
/// Defaults for the "convert to hub" dialog.
#[derive(Debug, Clone, PartialEq)]
pub struct HubPreviewDto {
/// Last namespace segment of the title.
pub suggested_title: String,
/// First prose block as plain text (<= 280 chars).
pub suggested_description: String,
/// Candidate members: pages the outline links or tags (outline order), then pages
/// referencing the note from properties or tags.
pub members: Vec<PageBrief>,
/// Blocks that are prose rather than links (what "keep the outline" would save).
pub prose_blocks: u32,
pub blocks: u32,
/// `"<suggested_title> (notes)"`, for the note receiving the outline.
pub suggested_note_title: String,
}
/// A page the legacy purge offers to delete.
#[derive(Debug, Clone, PartialEq)]
pub struct LegacyCandidate {
pub id: String,
pub title: String,
pub reason: String,
pub blocks: u32,
pub preselected: bool,
}
+3
View File
@@ -18,6 +18,8 @@ pub struct SynapseGraph {
graph: Arc<Mutex<Graph>>,
/// Page-level graph for the graph views, keyed by what invalidates it.
pub(crate) graph_cache: Mutex<Option<(super::graph_view::CacheKey, Arc<GraphData>)>>,
/// Hubs and home hubs, keyed by op-log sequence.
pub(crate) structure_cache: Mutex<Option<(i64, Arc<synapse_core::Structure>)>>,
}
impl SynapseGraph {
@@ -27,6 +29,7 @@ impl SynapseGraph {
Ok(SynapseGraph {
graph: Arc::new(Mutex::new(graph)),
graph_cache: Mutex::new(None),
structure_cache: Mutex::new(None),
})
}
+50
View File
@@ -78,9 +78,15 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
// Nodes.
let mut nodes = Vec::new();
let mut index: HashMap<String, u32> = HashMap::new();
let page_tags: HashMap<String, Vec<String>> = g
.all_page_tags()?
.into_iter()
.map(|(id, t)| (id.to_string(), t))
.collect();
{
let mut st = conn.prepare(
"SELECT id, title, journal_date, origin_journal, created_at FROM pages
WHERE kind != 'template'
ORDER BY journal_date IS NOT NULL, created_at",
)?;
let rows = st.query_map([], |r| {
@@ -94,6 +100,7 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
})?;
for row in rows {
let (id, title, journal_date, origin_journal, created_at) = row?;
let tags = page_tags.get(&id).cloned().unwrap_or_default();
index.insert(id.clone(), nodes.len() as u32);
nodes.push(GraphNode {
id,
@@ -105,6 +112,9 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
backlinks: 0,
cluster: 0,
primary_tag: None,
is_hub: false,
home_hub: None,
tags,
});
}
}
@@ -203,6 +213,22 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
}
}
// Hub membership (hub → member), cycles already broken by `structure()`.
let structure = g.structure()?;
for h in &structure.hubs {
let Some(&hi) = index.get(&h.page.to_string()) else {
continue;
};
nodes[hi as usize].is_hub = true;
for m in &h.members {
if let Some(&mi) = index.get(&m.to_string()) {
b.add(hi, mi, edge_kind::CONTAINS, 1.0);
}
}
}
tagged(g, &index, &by_key, &mut b)?;
// Stable edge order (sources, then targets, then kind).
let mut edges: Vec<((u32, u32, u8), f32)> = b.edges.into_iter().collect();
edges.sort_by_key(|&(k, _)| k);
@@ -234,6 +260,12 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
.map(|(&t, _)| t);
}
for (page, home) in &structure.home {
if let (Some(&i), Some(&h)) = (index.get(&page.to_string()), index.get(&home.to_string())) {
nodes[i as usize].home_hub = Some(h);
}
}
let mut out = GraphData {
nodes,
sources: Vec::with_capacity(edges.len()),
@@ -251,6 +283,24 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
Ok(out)
}
/// A page filed under a tag page gets one `TAGGED` edge to it.
fn tagged(
g: &Graph,
index: &HashMap<String, u32>,
by_key: &HashMap<String, u32>,
b: &mut Builder,
) -> Result<()> {
let mut st = g.conn().prepare("SELECT tag_key, page_id FROM page_tags")?;
let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
for row in rows {
let (tag, page) = row?;
if let (Some(&s), Some(&t)) = (index.get(&page), by_key.get(&tag)) {
b.add(s, t, edge_kind::TAGGED, 1.0);
}
}
Ok(())
}
/// Unlinked references: a non-journal page title (or alias) appearing as whole words in a
/// block of another page that does not already reference it. Titles are indexed by their
/// first word so each block is scanned once.
+4
View File
@@ -4,6 +4,8 @@
//! - `outline`: block editing (insert, update, move, indent/outdent, merge, delete).
//! - `search`: title/block lookup (stopgap until `synapse-search` is wired).
//! - `graph_view`: the whole page-level graph for the graph views (cached by op seq).
//! - `structure`: hubs (folder-like pages), namespaces and the legacy page purge.
//! - `tags`: free-form tags on pages (names, not pages) and their vocabulary.
//! - `layout`: Barnes-Hut force-directed layout, stepped from Dart off the UI thread.
//!
//! Extension points for Phase 2 (one module each, methods on `SynapseGraph` or their own
@@ -17,3 +19,5 @@ pub mod graph_view;
pub mod layout;
pub mod outline;
pub mod search;
pub mod structure;
pub mod tags;
+304
View File
@@ -0,0 +1,304 @@
//! Hubs (folder-like pages), namespaces and the legacy page purge. Rules and membership
//! live in `synapse_core::structure`; this module shapes them for the UI.
use super::dto::{
HubDto, HubPreviewDto, HubsDto, LegacyCandidate, NamespaceEntry, PageBrief, PageDto,
PageStructure,
};
use super::graph::{SynapseGraph, parse_id};
use anyhow::{Result, anyhow};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use synapse_core::{
Graph, HubConversion, PageId, Structure, is_legacy_page, namespace_parent, title_key,
};
impl SynapseGraph {
/// Every hub with its members, and the root hubs.
pub fn hubs(&self) -> Result<HubsDto> {
let g = self.lock();
let s = self.structure_of(&g)?;
let hub_ids: HashSet<PageId> = s.hubs.iter().map(|h| h.page).collect();
let member_of_hub: HashSet<PageId> = s
.hubs
.iter()
.flat_map(|h| h.members.iter().copied())
.collect();
let mut briefs: HashMap<PageId, PageBrief> = HashMap::new();
let mut hubs = Vec::with_capacity(s.hubs.len());
for h in &s.hubs {
let members = h
.members
.iter()
.map(|&m| brief(&g, &mut briefs, m))
.collect::<Result<Vec<_>>>()?;
hubs.push(HubDto {
id: h.page.to_string(),
title: h.title.clone(),
description: h.description.clone(),
depth: h.depth,
sub_hubs: h
.members
.iter()
.filter(|m| hub_ids.contains(m))
.map(|m| m.to_string())
.collect(),
members,
});
}
let roots = s
.hubs
.iter()
.filter(|h| !member_of_hub.contains(&h.page))
.map(|h| h.page.to_string())
.collect();
Ok(HubsDto { hubs, roots })
}
/// Hub and namespace context of a page.
pub fn page_structure(&self, page_id: String) -> Result<PageStructure> {
let g = self.lock();
let id = parse_id(&page_id)?;
let page = g
.get_page(id)?
.ok_or_else(|| anyhow!("page {page_id} not found"))?;
let mut briefs = HashMap::new();
let members = if page.is_hub() {
g.hub_members(id)?
.into_iter()
.map(|m| brief(&g, &mut briefs, m))
.collect::<Result<Vec<_>>>()?
} else {
Vec::new()
};
let in_hubs = g
.hubs_of(id)?
.into_iter()
.map(|h| brief(&g, &mut briefs, h))
.collect::<Result<Vec<_>>>()?;
let mut path = Vec::new();
let mut title = page.title.as_str();
while let Some(parent) = namespace_parent(title) {
path.push(parent);
title = parent;
}
let ns_path = path
.into_iter()
.rev()
.map(|t| entry(&g, t.to_string(), None))
.collect::<Result<Vec<_>>>()?;
let ns_children = g
.namespace_children(&page.title)?
.into_iter()
.map(|(t, id)| entry(&g, t, id))
.collect::<Result<Vec<_>>>()?;
Ok(PageStructure {
is_hub: page.is_hub(),
description: page.description.clone(),
members,
in_hubs,
ns_path,
ns_children,
})
}
/// Creates an empty hub. Fails when the title is taken.
pub fn create_hub(&self, title: String, description: String) -> Result<PageDto> {
Ok(PageDto::from(
&self.lock().create_hub(&title, &description)?,
))
}
/// Id of the hub's template page (created empty when missing). Open it like any note to
/// edit the outline new notes of the hub start from.
pub fn hub_template(&self, hub_id: String) -> Result<String> {
Ok(self.lock().hub_template(parse_id(&hub_id)?)?.to_string())
}
/// Creates a note in the hub, starting from a copy of the hub's template.
pub fn create_page_from_template(&self, hub_id: String, title: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(
&g.create_page_from_template(parse_id(&hub_id)?, &title)?,
))
}
pub fn set_hub_description(&self, hub_id: String, description: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(
&g.set_hub_description(parse_id(&hub_id)?, &description)?,
))
}
/// Puts a page in a hub (no-op when it already is). Fails for journals, non-hub targets,
/// the hub itself and memberships that would create a cycle.
pub fn add_to_hub(&self, page_id: String, hub_id: String) -> Result<()> {
self.lock()
.add_to_hub(parse_id(&page_id)?, parse_id(&hub_id)?)?;
Ok(())
}
/// Takes a page out of a hub (no-op when it is not in it).
pub fn remove_from_hub(&self, page_id: String, hub_id: String) -> Result<()> {
self.lock()
.remove_from_hub(parse_id(&page_id)?, parse_id(&hub_id)?)?;
Ok(())
}
/// Defaults for converting a note into a hub.
pub fn hub_conversion_preview(&self, page_id: String) -> Result<HubPreviewDto> {
let g = self.lock();
let p = g.hub_conversion_preview(parse_id(&page_id)?)?;
let mut briefs = HashMap::new();
let members = p
.members
.iter()
.map(|&m| brief(&g, &mut briefs, m))
.collect::<Result<Vec<_>>>()?;
Ok(HubPreviewDto {
suggested_note_title: format!("{} (notes)", p.suggested_title),
suggested_title: p.suggested_title,
suggested_description: p.suggested_description,
members,
prose_blocks: p.prose_blocks,
blocks: p.blocks,
})
}
/// Turns a note into a hub in one transaction: renames it to `title` (links rewritten),
/// moves its outline to a new note `keep_outline_as` (or deletes it when `None`; a blank title is an error), sets the
/// description and adds `member_ids` (invalid members are skipped).
pub fn convert_to_hub(
&self,
page_id: String,
title: String,
description: String,
member_ids: Vec<String>,
keep_outline_as: Option<String>,
) -> Result<PageDto> {
let members = member_ids
.iter()
.map(|i| parse_id(i))
.collect::<Result<Vec<_>>>()?;
if keep_outline_as
.as_ref()
.is_some_and(|t| t.trim().is_empty())
{
return Err(anyhow!("the note that keeps the outline needs a title"));
}
let c = HubConversion {
title,
description,
members,
keep_outline_as,
};
let g = self.lock();
Ok(PageDto::from(&g.convert_to_hub(parse_id(&page_id)?, &c)?))
}
/// Turns a hub back into a note: description, then one `[[Member]]` block per member.
pub fn convert_to_note(&self, page_id: String) -> Result<PageDto> {
Ok(PageDto::from(
&self.lock().convert_to_note(parse_id(&page_id)?)?,
))
}
/// Pages that are probably leftovers of Logseq: its built-ins and pages with
/// `type:: system`. Only the organisational files (`contents`, `card`, `favorites`,
/// `hls__*`) and empty pages are preselected, and never a hub: a built-in title such as
/// `todo` may hold real content.
pub fn legacy_candidates(&self) -> Result<Vec<LegacyCandidate>> {
let g = self.lock();
let mut out = Vec::new();
for p in g.list_pages(false, u32::MAX, 0)? {
let key = title_key(&p.title);
let reason = if is_legacy_page(&p.title) {
if key.starts_with("hls__") {
"Logseq PDF highlights"
} else {
"Logseq built-in"
}
} else if p.properties.get("type").and_then(|v| v.as_str()) == Some("system") {
"type:: system"
} else {
continue;
};
let blocks = g.page_tree(p.id)?.len() as u32;
let organisational = matches!(key.as_str(), "contents" | "card" | "favorites")
|| key.starts_with("hls__");
out.push(LegacyCandidate {
id: p.id.to_string(),
title: p.title.clone(),
reason: reason.into(),
blocks,
preselected: !p.is_hub() && (blocks == 0 || organisational),
});
}
out.sort_by_key(|c| title_key(&c.title));
Ok(out)
}
/// Deletes pages and their blocks in one transaction. Returns how many existed.
pub fn purge_pages(&self, ids: Vec<String>) -> Result<u32> {
let ids = ids
.iter()
.map(|i| parse_id(i))
.collect::<Result<Vec<_>>>()?;
let n = self.lock().transaction(|g| {
let mut n = 0;
for id in ids {
if g.get_page(id)?.is_some() {
g.delete_page(id)?;
n += 1;
}
}
Ok(n)
})?;
Ok(n)
}
/// Structure of the graph, cached until it changes.
fn structure_of(&self, g: &Graph) -> Result<Arc<Structure>> {
let seq = g.last_seq()?;
let mut cache = self
.structure_cache
.lock()
.unwrap_or_else(|e| e.into_inner());
if let Some((s, data)) = cache.as_ref()
&& *s == seq
{
return Ok(Arc::clone(data));
}
let data = Arc::new(g.structure()?);
*cache = Some((seq, Arc::clone(&data)));
Ok(data)
}
}
fn brief(g: &Graph, cache: &mut HashMap<PageId, PageBrief>, id: PageId) -> Result<PageBrief> {
if let Some(b) = cache.get(&id) {
return Ok(b.clone());
}
let p = g
.get_page(id)?
.ok_or_else(|| anyhow!("page {id} not found"))?;
let b = PageBrief::from(&p);
cache.insert(id, b.clone());
Ok(b)
}
/// Namespace level; looks the page up when the caller does not know it.
fn entry(g: &Graph, title: String, id: Option<PageId>) -> Result<NamespaceEntry> {
let id = match id {
Some(id) => Some(id),
None => g
.page_by_title(&title)?
.filter(|p| !p.is_journal())
.map(|p| p.id),
};
Ok(NamespaceEntry {
title,
id: id.map(|i| i.to_string()),
})
}
+87
View File
@@ -0,0 +1,87 @@
//! Tags (topic pages that notes are filed under) and types (plain names saying what a page
//! is). Rules live in `synapse_core::{tags, types}`; this module shapes them for the UI.
use super::dto::{PageBrief, PageDto, TagDto};
use super::graph::{SynapseGraph, parse_id};
use anyhow::Result;
impl SynapseGraph {
/// Replaces the tags of a page (each title gets a tag page if it has none). Journals,
/// templates and tag pages cannot be tagged.
pub fn set_page_tags(&self, page_id: String, tags: Vec<String>) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(&g.set_page_tags(parse_id(&page_id)?, tags)?))
}
pub fn add_page_tag(&self, page_id: String, tag: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(&g.add_page_tag(parse_id(&page_id)?, &tag)?))
}
pub fn remove_page_tag(&self, page_id: String, tag: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(
&g.remove_page_tag(parse_id(&page_id)?, &tag)?,
))
}
/// Every tag page with its number of pages, most used first.
pub fn tag_catalog(&self) -> Result<Vec<TagDto>> {
Ok(self
.lock()
.tag_catalog()?
.into_iter()
.map(|t| TagDto {
name: t.name,
count: t.count,
suggested: t.suggested,
})
.collect())
}
/// Pages carrying a tag, most recently updated first.
pub fn pages_with_tag(&self, tag: String) -> Result<Vec<PageBrief>> {
let g = self.lock();
let mut out = Vec::new();
for id in g.pages_with_tag(&tag)? {
if let Some(p) = g.get_page(id)? {
out.push(PageBrief::from(&p));
}
}
Ok(out)
}
/// Replaces the types of a page. Journals and templates cannot be typed.
pub fn set_page_types(&self, page_id: String, types: Vec<String>) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(
&g.set_page_types(parse_id(&page_id)?, types)?,
))
}
pub fn add_page_type(&self, page_id: String, ty: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(&g.add_page_type(parse_id(&page_id)?, &ty)?))
}
pub fn remove_page_type(&self, page_id: String, ty: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(
&g.remove_page_type(parse_id(&page_id)?, &ty)?,
))
}
/// Types in use (most used first) followed by the seeded suggestions not used yet.
pub fn type_catalog(&self) -> Result<Vec<TagDto>> {
Ok(self
.lock()
.type_catalog()?
.into_iter()
.map(|t| TagDto {
name: t.name,
count: t.count,
suggested: t.suggested,
})
.collect())
}
}
File diff suppressed because it is too large. Load diff
+278 -1
View File
@@ -1,4 +1,4 @@
use synapse_ffi::api::dto::{BlockDto, Place, PlaceKind};
use synapse_ffi::api::dto::{BlockDto, Place, PlaceKind, edge_kind};
use synapse_ffi::api::graph::SynapseGraph;
fn open() -> (tempfile::TempDir, SynapseGraph) {
@@ -185,3 +185,280 @@ fn assets_round_trip() {
assert_eq!(std::fs::read(path).unwrap(), b"png");
assert!(g.asset_path("zz".into()).is_none());
}
#[test]
fn hubs_structure_and_graph_nodes() {
let (_d, g) = open();
let media = g.create_hub("Media".into(), " All media ".into()).unwrap();
assert!(media.is_hub);
assert_eq!(media.description, "All media");
let media = media.id;
let books = g
.create_hub("Media/Books".into(), String::new())
.unwrap()
.id;
let (novel, _) = page_with(&g, "Novel", &["text"]);
let (film, _) = page_with(&g, "Film", &["text"]);
let (note, _) = page_with(&g, "Note", &["plain text"]);
g.add_to_hub(books.clone(), media.clone()).unwrap();
g.add_to_hub(film.clone(), media.clone()).unwrap();
g.add_to_hub(novel.clone(), books.clone()).unwrap();
g.add_to_hub(novel.clone(), books.clone()).unwrap(); // no-op
// Rules surface as readable errors.
let err = g.add_to_hub(media.clone(), books.clone()).unwrap_err();
assert!(err.to_string().contains("cycle"), "{err}");
assert!(
g.add_to_hub(note.clone(), film.clone()).is_err(),
"not a hub"
);
assert!(g.add_to_hub(media.clone(), media.clone()).is_err(), "self");
let today = g.open_page(g.today()).unwrap().page.id;
assert!(g.add_to_hub(today, media.clone()).is_err(), "journal");
let err = g
.insert_block(
media.clone(),
place(PlaceKind::LastChildOf, None),
"x".into(),
)
.unwrap_err();
assert!(err.to_string().contains("hubs have no blocks"), "{err}");
let hubs = g.hubs().unwrap();
let titles: Vec<&str> = hubs.hubs.iter().map(|h| h.title.as_str()).collect();
assert_eq!(titles, ["Media", "Media/Books"]);
assert_eq!(hubs.roots, std::slice::from_ref(&media));
let m = &hubs.hubs[0];
assert_eq!((m.depth, m.description.as_str()), (0, "All media"));
let names: Vec<&str> = m.members.iter().map(|p| p.title.as_str()).collect();
assert_eq!(names, ["Media/Books", "Film"], "sub-hubs first");
assert!(m.members[0].is_hub && !m.members[1].is_hub);
assert_eq!(m.sub_hubs, std::slice::from_ref(&books));
assert_eq!(hubs.hubs[1].depth, 1);
let s = g.page_structure(novel.clone()).unwrap();
assert!(!s.is_hub && s.members.is_empty());
let in_hubs: Vec<&str> = s.in_hubs.iter().map(|p| p.title.as_str()).collect();
assert_eq!(in_hubs, ["Media/Books"], "one hub per page");
let s = g.page_structure(books.clone()).unwrap();
assert!(s.is_hub);
assert_eq!(s.members.len(), 1);
assert_eq!(s.ns_path.len(), 1);
assert_eq!(s.ns_path[0].id.as_deref(), Some(media.as_str()));
let s = g.page_structure(media.clone()).unwrap();
assert_eq!(s.description, "All media");
assert_eq!(s.ns_children[0].id.as_deref(), Some(books.as_str()));
g.set_hub_description(books.clone(), "Reading".into())
.unwrap();
g.remove_from_hub(film.clone(), media.clone()).unwrap();
assert!(g.page_structure(film.clone()).unwrap().in_hubs.is_empty());
// Graph data: hub flags, home hubs and CONTAINS edges.
let data = g.graph_data().unwrap();
let idx = |id: &str| data.nodes.iter().position(|n| n.id == id).unwrap() as u32;
let node = |id: &str| &data.nodes[idx(id) as usize];
assert!(node(&media).is_hub && node(&books).is_hub && !node(&novel).is_hub);
assert_eq!(node(&books).home_hub, Some(idx(&books)));
assert_eq!(node(&novel).home_hub, Some(idx(&books)), "deepest hub");
assert_eq!(node(&note).home_hub, None);
let contains = |s: &str, t: &str| {
(0..data.kinds.len()).any(|e| {
data.kinds[e] == edge_kind::CONTAINS
&& data.sources[e] == idx(s)
&& data.targets[e] == idx(t)
})
};
assert!(contains(&media, &books) && contains(&books, &novel));
assert!(!contains(&media, &novel));
assert!(!contains(&media, &film));
assert_eq!(node(&novel).backlinks, 1, "membership is structural");
// Converting back to a note: description, then one link per member.
let n = g.convert_to_note(books.clone()).unwrap();
assert!(!n.is_hub);
let page = g.page(books.clone()).unwrap().unwrap();
let texts: Vec<&str> = page.blocks.iter().map(|b| b.content.as_str()).collect();
assert_eq!(texts, ["Reading", "[[Novel]]"]);
let in_hubs = g.page_structure(novel.clone()).unwrap().in_hubs;
assert!(in_hubs.is_empty(), "the old hub is gone from its members");
}
#[test]
fn convert_note_to_hub() {
let (_d, g) = open();
let (area, _) = page_with(
&g,
"Work/Area",
&[
"Everything about **my** area of [[Work]].",
"[[Alpha]]",
"[[Beta]] #Gamma",
],
);
let p = g.hub_conversion_preview(area.clone()).unwrap();
assert_eq!(p.suggested_title, "Area");
assert_eq!(p.suggested_note_title, "Area (notes)");
assert_eq!(p.suggested_description, "Everything about my area of Work.");
let names: Vec<&str> = p.members.iter().map(|m| m.title.as_str()).collect();
assert_eq!(names, ["Work", "Alpha", "Beta", "Gamma"]);
assert_eq!((p.prose_blocks, p.blocks), (1, 3));
let member_ids: Vec<String> = p.members.iter().skip(1).map(|m| m.id.clone()).collect();
let hub = g
.convert_to_hub(
area.clone(),
p.suggested_title.clone(),
p.suggested_description.clone(),
member_ids,
Some(p.suggested_note_title.clone()),
)
.unwrap();
assert!(hub.is_hub);
assert_eq!(
(hub.id.as_str(), hub.title.as_str()),
(area.as_str(), "Area")
);
assert!(g.page(area.clone()).unwrap().unwrap().blocks.is_empty());
let kept = g.page_by_title("Area (notes)".into()).unwrap().unwrap();
assert_eq!(kept.blocks.len(), 3);
let s = g.page_structure(area.clone()).unwrap();
let names: Vec<&str> = s.members.iter().map(|m| m.title.as_str()).collect();
assert_eq!(
names,
["Alpha", "Area (notes)", "Beta", "Gamma"],
"kept note is a member"
);
// A blank keep title is an error (never "delete the outline") and changes nothing.
let (blank, _) = page_with(&g, "Blank", &["keep me"]);
assert!(
g.convert_to_hub(
blank.clone(),
"Blank".into(),
String::new(),
vec![],
Some(" ".into())
)
.is_err()
);
assert!(!g.page(blank.clone()).unwrap().unwrap().page.is_hub);
assert_eq!(g.page(blank).unwrap().unwrap().blocks.len(), 1);
// A title clash is a readable error and changes nothing.
let (other, _) = page_with(&g, "Other", &["[[Alpha]]"]);
let err = g
.convert_to_hub(other.clone(), "Area".into(), String::new(), vec![], None)
.unwrap_err();
assert!(!err.to_string().is_empty());
assert!(!g.page(other.clone()).unwrap().unwrap().page.is_hub);
assert_eq!(g.page(other).unwrap().unwrap().blocks.len(), 1);
}
#[test]
fn legacy_candidates_and_purge() {
let (_d, g) = open();
let (todo, _) = page_with(&g, "TODO", &["a", "b"]);
let (hl, _) = page_with(&g, "hls__book", &[]);
let (sys, _) = page_with(&g, "Template", &["x"]);
let (keep, _) = page_with(&g, "Keep", &["x"]);
page_with(&g, "contents", &["- x"]);
page_with(&g, "now", &[]);
g.create_hub("later".into(), String::new()).unwrap();
{
let shared = g.shared();
let core = shared.lock().unwrap();
let mut props = synapse_core::Properties::new();
props.insert("type".into(), "system".into());
core.set_page_properties(sys.parse().unwrap(), props)
.unwrap();
}
let c = g.legacy_candidates().unwrap();
let by = |t: &str| c.iter().find(|x| x.title == t).unwrap();
assert_eq!(by("TODO").reason, "Logseq built-in");
assert!(
!by("TODO").preselected && by("TODO").blocks == 2,
"has content"
);
assert!(by("contents").preselected, "organisational page");
assert!(by("now").preselected, "empty built-in");
assert!(!by("later").preselected, "hubs are never preselected");
assert_eq!(by("hls__book").reason, "Logseq PDF highlights");
assert!(by("hls__book").preselected);
assert!(!by("Template").preselected);
assert_eq!(by("Template").reason, "type:: system");
assert!(c.iter().all(|x| x.title != "Keep"));
// A bad id rejects the call before anything is deleted.
assert!(g.purge_pages(vec![todo.clone(), "nope".into()]).is_err());
assert!(g.page(todo.clone()).unwrap().is_some());
assert_eq!(g.purge_pages(vec![todo.clone(), hl.clone()]).unwrap(), 2);
assert!(g.page(todo).unwrap().is_none() && g.page(hl).unwrap().is_none());
assert!(g.page(keep).unwrap().is_some());
}
#[test]
fn tags_are_pages_and_their_own_edge_kind() {
let (_d, g) = open();
let (a, _) = page_with(&g, "Rust", &["x"]);
let (b, _) = page_with(&g, "Go", &["y"]);
let (c, _) = page_with(&g, "Madrid", &["z"]);
for (p, tags) in [
(&a, vec!["tecnología", "idea"]),
(&b, vec!["Tecnología", "idea"]),
(&c, vec!["lugar"]),
] {
g.set_page_tags(p.clone(), tags.into_iter().map(String::from).collect())
.unwrap();
}
let data = g.graph_data().unwrap();
let idx = |id: &str| data.nodes.iter().position(|n| n.id == id).unwrap() as u32;
let title = |i: u32| data.nodes[i as usize].title.clone();
let mut tagged: Vec<(String, String)> = (0..data.kinds.len())
.filter(|&e| data.kinds[e] == edge_kind::TAGGED)
.map(|e| (title(data.sources[e]), title(data.targets[e])))
.collect();
tagged.sort();
let pair = |a: &str, b: &str| (a.to_string(), b.to_string());
assert_eq!(
tagged,
[
pair("Go", "idea"),
pair("Go", "tecnología"),
pair("Madrid", "lugar"),
pair("Rust", "idea"),
pair("Rust", "tecnología"),
],
"each page points at its tag pages"
);
// The tag page is a real node that counts backlinks, and the DTOs flag it.
let tp = &data.nodes[data
.nodes
.iter()
.position(|n| n.title == "tecnología")
.unwrap()];
assert_eq!(tp.backlinks, 2);
assert!(g.page(tp.id.clone()).unwrap().unwrap().page.is_tag);
assert_eq!(
idx(&a),
data.nodes.iter().position(|n| n.id == a).unwrap() as u32
);
let cat = g.tag_catalog().unwrap();
assert_eq!((cat[0].name.as_str(), cat[0].count), ("idea", 2));
}
#[test]
fn types_round_trip_through_the_api() {
let (_d, g) = open();
let (a, _) = page_with(&g, "Ana", &["x"]);
let p = g.add_page_type(a.clone(), "persona".into()).unwrap();
assert_eq!(p.types, ["persona"]);
assert!(g.type_catalog().unwrap().iter().any(|t| t.name == "lugar"));
assert!(
g.remove_page_type(a, "PERSONA".into())
.unwrap()
.types
.is_empty()
);
}
+43 -1
View File
@@ -3,7 +3,8 @@
//! Layout: `pages/<encoded title>.md`, `journals/YYYY_MM_DD.md`, `assets.json`.
//! A page file starts with page properties (`key:: value`, aliases as `alias:: a, b`),
//! then one `- ` bullet per block, nested with tabs. Block properties follow the content;
//! blocks referenced by `((uuid))` carry an `id::` property.
//! blocks referenced by `((uuid))` carry an `id::` property. Hubs carry `synapse-kind:: hub`
//! and `synapse-description::`; a page in hubs lists their titles in `synapse-hubs::`.
use crate::Result;
use crate::error::Error;
@@ -15,6 +16,15 @@ use synapse_core::{Block, BlockId, Graph, Page, Properties};
pub const PAGES_DIR: &str = "pages";
pub const JOURNALS_DIR: &str = "journals";
pub const MANIFEST: &str = "assets.json";
/// Page property marking a hub or tag page (`synapse-kind:: hub|tag`); notes omit it.
pub const KIND_PROP: &str = "synapse-kind";
/// Page property holding a hub's description.
pub const DESCRIPTION_PROP: &str = "synapse-description";
/// Page property listing the titles of the hubs a page belongs to (JSON array).
pub const HUBS_PROP: &str = "synapse-hubs";
pub const TAGS_PROP: &str = "synapse-tags";
/// Page property with the type names (`synapse-types:: persona, lugar`).
pub const TYPES_PROP: &str = "synapse-types";
/// Encodes a page title as a file name (Logseq "triple-lowbar" format: `/` becomes `___`,
/// characters illegal on Windows and `%` are percent-encoded).
@@ -173,6 +183,38 @@ pub fn render_block(block: &Block, depth: usize, referenced: &HashSet<BlockId>)
pub fn render_page(graph: &Graph, page: &Page, referenced: &HashSet<BlockId>) -> Result<String> {
let mut props = page.properties.clone();
props.remove("alias");
if page.is_hub() {
props.insert(KIND_PROP.into(), Value::String("hub".into()));
} else if page.is_tag() {
props.insert(KIND_PROP.into(), Value::String("tag".into()));
}
if !page.description.is_empty() {
props.insert(
DESCRIPTION_PROP.into(),
Value::String(page.description.clone()),
);
}
let mut hubs = Vec::new();
for h in graph.hubs_of(page.id)? {
if let Some(h) = graph.get_page(h)? {
hubs.push(Value::String(h.title));
}
}
if !hubs.is_empty() {
props.insert(HUBS_PROP.into(), Value::Array(hubs));
}
if !page.tags.is_empty() {
props.insert(
TAGS_PROP.into(),
Value::Array(page.tags.iter().cloned().map(Value::String).collect()),
);
}
if !page.types.is_empty() {
props.insert(
TYPES_PROP.into(),
Value::Array(page.types.iter().cloned().map(Value::String).collect()),
);
}
let mut list = sorted_props(&props);
let aliases = graph.aliases_of(page.id)?;
if !aliases.is_empty() {
+7 -1
View File
@@ -189,14 +189,20 @@ impl History {
for rec in ops {
match rec.op {
Op::UpsertPage { page } => {
// Members list their hubs by title: a renamed hub, or one that
// became a note, changes their files.
touched.extend(graph.hub_members(page.id)?);
touched.insert(page.id);
}
Op::UpsertBlock { block } => {
touched.insert(block.page_id);
}
// A deleted hub drops out of its members' lists (their `page_hubs`
// rows outlive it when no member upsert came along).
Op::DeletePage { id } => touched.extend(graph.hub_members(id)?),
// Deletions and moves do not say which page lost a block; those
// pages are caught by the `updated_at` scan below.
Op::DeleteBlock { .. } | Op::DeletePage { .. } | Op::PutAsset { .. } => {}
Op::DeleteBlock { .. } | Op::PutAsset { .. } => {}
// The previous owner of an alias is unknown.
Op::SetAlias { .. } => everything = true,
}
+56 -2
View File
@@ -1,6 +1,6 @@
//! Parser for the Markdown files produced by [`crate::export`] (and plain Logseq pages).
use crate::export::parse_value;
use crate::export::{DESCRIPTION_PROP, HUBS_PROP, KIND_PROP, TAGS_PROP, TYPES_PROP, parse_value};
use serde_json::Value;
use synapse_core::{BlockId, Properties, parse::property_split};
@@ -16,9 +16,21 @@ pub struct ParsedBlock {
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ParsedPage {
/// Page properties except `alias`.
/// Page properties except `alias` and the `synapse-*` hub properties.
pub properties: Properties,
pub aliases: Vec<String>,
/// `synapse-kind:: hub`.
pub is_hub: bool,
/// `synapse-kind:: tag`.
pub is_tag: bool,
/// `synapse-description::`.
pub description: String,
/// Titles from `synapse-hubs::`.
pub hubs: Vec<String>,
/// Tag page titles from `synapse-tags::`.
pub tags: Vec<String>,
/// Names from `synapse-types::`.
pub types: Vec<String>,
pub blocks: Vec<ParsedBlock>,
}
@@ -106,6 +118,48 @@ pub fn parse_page(text: &str) -> ParsedPage {
}
}
let kind = page.properties.remove(KIND_PROP);
page.is_hub = matches!(&kind, Some(Value::String(k)) if k == "hub");
page.is_tag = matches!(&kind, Some(Value::String(k)) if k == "tag");
page.description = match page.properties.remove(DESCRIPTION_PROP) {
Some(Value::String(d)) => d,
Some(other) => other.to_string(),
None => String::new(),
};
page.hubs = match page.properties.remove(HUBS_PROP) {
Some(Value::Array(items)) => items
.into_iter()
.filter_map(|v| match v {
Value::String(s) => Some(s),
_ => None,
})
.collect(),
Some(Value::String(s)) => vec![s],
_ => Vec::new(),
};
page.tags = match page.properties.remove(TAGS_PROP) {
Some(Value::Array(items)) => items
.into_iter()
.filter_map(|v| match v {
Value::String(s) => Some(s),
_ => None,
})
.collect(),
Some(Value::String(s)) => vec![s],
_ => Vec::new(),
};
page.types = match page.properties.remove(TYPES_PROP) {
Some(Value::Array(items)) => items
.into_iter()
.filter_map(|v| match v {
Value::String(s) => Some(s),
_ => None,
})
.collect(),
Some(Value::String(s)) => vec![s],
_ => Vec::new(),
};
for raw in raws {
let mut lines = raw.lines;
// Blank separator lines between blocks are not content.
+154 -13
View File
@@ -8,7 +8,7 @@ use crate::parse::{ParsedPage, parse_page};
use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use synapse_core::position::between;
use synapse_core::{Block, BlockId, Graph, NewPage, Page, new_id};
use synapse_core::{Block, BlockId, Graph, NewPage, Page, PageId, PageKind, new_id};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RestoreReport {
@@ -51,6 +51,14 @@ fn atomic<T>(graph: &Graph, f: impl FnOnce() -> Result<T>) -> Result<T> {
}
struct Plan {
page: PageId,
is_hub: bool,
is_tag: bool,
description: String,
/// Titles of the hubs the page belongs to.
hubs: Vec<String>,
tags: Vec<String>,
types: Vec<String>,
blocks: Vec<Block>,
delete: Vec<BlockId>,
}
@@ -67,8 +75,20 @@ fn find_or_create(graph: &Graph, title: &str) -> Result<Page> {
/// Matches parsed blocks to existing ones and decides what to write and delete.
fn plan(graph: &Graph, title: &str, parsed: &ParsedPage, steal: bool) -> Result<Plan> {
let page = find_or_create(graph, title)?;
let mut page = find_or_create(graph, title)?;
let now = graph.now_ms();
// A hub cannot hold blocks: turn it back into a note before any block is written.
if page.is_hub() && !parsed.is_hub {
page.kind = PageKind::Note;
page.updated_at = now;
graph.put_page(&page)?;
// Like `convert_to_note`: members leave it, so it never regains them by surprise.
for m in graph.hub_members(page.id)? {
graph.remove_from_hub(m, page.id)?;
}
}
// A hub file has no blocks; any left over in the page are deleted.
let parsed_blocks: &[_] = if parsed.is_hub { &[] } else { &parsed.blocks };
if page.properties != parsed.properties {
graph.set_page_properties(page.id, parsed.properties.clone())?;
@@ -89,9 +109,9 @@ fn plan(graph: &Graph, title: &str, parsed: &ParsedPage, steal: bool) -> Result<
.collect();
let by_id: HashMap<BlockId, &Block> = existing.iter().map(|b| (b.id, b)).collect();
let mut claimed: HashSet<BlockId> = HashSet::new();
let mut ids: Vec<Option<BlockId>> = vec![None; parsed.blocks.len()];
let mut ids: Vec<Option<BlockId>> = vec![None; parsed_blocks.len()];
for (i, pb) in parsed.blocks.iter().enumerate() {
for (i, pb) in parsed_blocks.iter().enumerate() {
let Some(id) = pb.id else { continue };
let usable = by_id.contains_key(&id)
|| match graph.get_block(id)? {
@@ -102,7 +122,7 @@ fn plan(graph: &Graph, title: &str, parsed: &ParsedPage, steal: bool) -> Result<
ids[i] = Some(id);
}
}
for (i, pb) in parsed.blocks.iter().enumerate() {
for (i, pb) in parsed_blocks.iter().enumerate() {
if ids[i].is_some() {
continue;
}
@@ -115,10 +135,10 @@ fn plan(graph: &Graph, title: &str, parsed: &ParsedPage, steal: bool) -> Result<
}
// Build the tree: parents from depth, positions kept when still ordered.
let mut blocks: Vec<Block> = Vec::with_capacity(parsed.blocks.len());
let mut blocks: Vec<Block> = Vec::with_capacity(parsed_blocks.len());
let mut stack: Vec<BlockId> = Vec::new();
let mut last_pos: HashMap<Option<BlockId>, String> = HashMap::new();
for (i, pb) in parsed.blocks.iter().enumerate() {
for (i, pb) in parsed_blocks.iter().enumerate() {
let id = ids[i].unwrap();
stack.truncate(pb.depth);
let parent = stack.last().copied();
@@ -149,7 +169,17 @@ fn plan(graph: &Graph, title: &str, parsed: &ParsedPage, steal: bool) -> Result<
.filter(|b| !claimed.contains(&b.id))
.map(|b| b.id)
.collect();
Ok(Plan { blocks, delete })
Ok(Plan {
page: page.id,
is_hub: parsed.is_hub,
is_tag: parsed.is_tag,
description: parsed.description.clone(),
hubs: parsed.hubs.clone(),
tags: parsed.tags.clone(),
types: parsed.types.clone(),
blocks,
delete,
})
}
fn same(a: &Block, b: &Block) -> bool {
@@ -186,6 +216,72 @@ fn apply_puts(graph: &Graph, plan: &Plan, fault: Fault) -> Result<bool> {
Ok(wrote || !plan.delete.is_empty())
}
/// Sets kind and description once the page's blocks are gone; returns whether it changed.
fn apply_kind(graph: &Graph, plan: &Plan) -> Result<bool> {
let Some(mut page) = graph.get_page(plan.page)? else {
return Ok(false);
};
let kind = if plan.is_hub {
PageKind::Hub
} else if plan.is_tag {
PageKind::Tag
} else {
PageKind::Note
};
if page.kind == kind
&& page.description == plan.description
&& page.tags == plan.tags
&& page.types == plan.types
{
return Ok(false);
}
page.kind = kind;
page.tags = plan.tags.clone();
page.types = plan.types.clone();
page.description = plan.description.clone();
page.updated_at = graph.now_ms();
graph.put_page(&page)?;
Ok(true)
}
/// Puts the page back in the hubs named by the snapshot (once every page has its kind).
/// Hubs that no longer exist or would now be invalid (e.g. a cycle) are skipped.
fn apply_hubs(graph: &Graph, plan: &Plan) -> Result<bool> {
let Some(page) = graph.get_page(plan.page)? else {
return Ok(false);
};
let mut wanted = Vec::new();
for t in &plan.hubs {
if let Some(h) = graph.page_by_title(t)?
&& h.is_hub()
&& !wanted.contains(&h.id)
{
wanted.push(h.id);
}
}
wanted.truncate(1);
if page.hubs == wanted {
return Ok(false);
}
if skip_invalid(graph.set_page_hubs(page.id, wanted.clone()))?.is_none() {
graph.set_page_hubs(page.id, Vec::new())?;
for h in wanted {
skip_invalid(graph.add_to_hub(page.id, h))?;
}
}
Ok(true)
}
/// Rule violations (cycles, pages that are no longer hubs) become `None`; storage errors
/// still abort the restore.
fn skip_invalid<T>(r: synapse_core::Result<T>) -> Result<Option<T>> {
match r {
Ok(v) => Ok(Some(v)),
Err(synapse_core::Error::Invalid(_) | synapse_core::Error::NotFound(_)) => Ok(None),
Err(e) => Err(e.into()),
}
}
fn clear_or_delete(graph: &Graph, page: &Page) -> Result<bool> {
if page.is_journal() {
let roots: Vec<_> = graph
@@ -223,12 +319,19 @@ impl History {
..Default::default()
};
let fault = &self.fault;
let this = &*self;
atomic(graph, || {
match text {
Some(text) => {
let p = plan(graph, title, &parse_page(&text), false)?;
let parsed = parse_page(&text);
let p = plan(graph, title, &parsed, false)?;
apply_deletes(graph, &p, fault)?;
apply_puts(graph, &p, fault)?;
apply_kind(graph, &p)?;
apply_hubs(graph, &p)?;
if parsed.is_hub {
this.rejoin_members(graph, commit, title, p.page)?;
}
report.restored = 1;
}
None => {
@@ -245,6 +348,38 @@ impl History {
Ok(report)
}
/// Membership lives on the members: after restoring a hub alone, puts back the existing
/// pages that were in it at `commit` (other memberships are left alone).
fn rejoin_members(
&self,
graph: &Graph,
commit: gix::ObjectId,
title: &str,
hub: PageId,
) -> Result<()> {
let key = synapse_core::title_key(title);
for (path, oid) in &self.snapshot_files(&commit.to_string())? {
let Some(member) = export::title_from_path(path) else {
continue;
};
let parsed = parse_page(&self.read_blob(*oid)?);
if !parsed
.hubs
.iter()
.any(|h| synapse_core::title_key(h) == key)
{
continue;
}
if let Some(m) = graph.page_by_title(&member)?
&& m.id != hub
{
// Skipped when it would now be invalid (e.g. a cycle).
skip_invalid(graph.add_to_hub(m.id, hub))?;
}
}
Ok(())
}
/// Restores every page to its state at `rev`; pages created since are removed.
pub fn restore_graph(
&mut self,
@@ -275,11 +410,17 @@ impl History {
for p in &plans {
apply_deletes(graph, p, fault)?;
}
for p in &plans {
if apply_puts(graph, p, fault)? {
report.restored += 1;
}
let mut changed = vec![false; plans.len()];
for (i, p) in plans.iter().enumerate() {
changed[i] = apply_puts(graph, p, fault)?;
}
for (i, p) in plans.iter().enumerate() {
changed[i] |= apply_kind(graph, p)?;
}
for (i, p) in plans.iter().enumerate() {
changed[i] |= apply_hubs(graph, p)?;
}
report.restored += changed.iter().filter(|c| **c).count();
let mut offset = 0;
let mut extra = Vec::new();
loop {
+105
View File
@@ -341,3 +341,108 @@ fn failed_restore_leaves_graph_unchanged() {
h.restore_graph(&g, &s1.id, T0 + 4000).unwrap();
assert!(g.page_by_title("Gone").unwrap().is_some());
}
#[test]
fn tags_round_trip_through_snapshots() {
let (_d, g, mut h) = setup();
let note = add(&g, "Note", &["body"]);
g.add_page_tag(note.id, "tecnología").unwrap();
g.add_page_tag(note.id, "idea").unwrap();
g.add_page_type(note.id, "concepto").unwrap();
let s1 = h.snapshot(&g, T0 + 500).unwrap().unwrap();
let tag_md = h.page_at(&s1.id, "idea").unwrap().unwrap();
assert!(tag_md.contains("synapse-kind:: tag"), "{tag_md}");
let md = h.page_at(&s1.id, "Note").unwrap().unwrap();
assert!(
md.contains(r#"synapse-tags:: ["tecnología","idea"]"#),
"{md}"
);
at(&g, T0 + 1000);
g.set_page_tags(note.id, vec![]).unwrap();
g.set_page_types(note.id, vec![]).unwrap();
h.restore_graph(&g, &s1.id, T0 + 2000).unwrap();
assert_eq!(g.get_page(note.id).unwrap().unwrap().types, ["concepto"]);
assert!(g.page_by_title("idea").unwrap().unwrap().is_tag());
assert_eq!(
g.get_page(note.id).unwrap().unwrap().tags,
["tecnología", "idea"]
);
assert_eq!(g.pages_with_tag("idea").unwrap(), [note.id]);
}
#[test]
fn hubs_round_trip_kind_description_and_memberships() {
let (_d, g, mut h) = setup();
let top = g.create_hub("Top", "All my stuff,\nin one place").unwrap();
let sub = g.create_hub("Sub", "").unwrap();
let note = add(&g, "Note", &["body"]);
g.add_to_hub(sub.id, top.id).unwrap();
g.add_to_hub(note.id, sub.id).unwrap();
let s1 = h.snapshot(&g, T0).unwrap().unwrap();
let top_md = h.page_at(&s1.id, "Top").unwrap().unwrap();
assert!(top_md.contains("synapse-kind:: hub"), "{top_md}");
assert!(top_md.contains(r#"synapse-description:: "All my stuff,\nin one place""#));
let note_md = h.page_at(&s1.id, "Note").unwrap().unwrap();
assert!(note_md.contains(r#"synapse-hubs:: ["Sub"]"#), "{note_md}");
// Renaming a hub re-exports its members (they list hubs by title).
at(&g, T0 + 1000);
g.rename_page(sub.id, "Sub 2").unwrap();
let s2 = h.snapshot(&g, T0 + 1500).unwrap().unwrap();
let note_md = h.page_at(&s2.id, "Note").unwrap().unwrap();
assert!(note_md.contains(r#"synapse-hubs:: ["Sub 2"]"#), "{note_md}");
// Break everything, then restore the graph.
at(&g, T0 + 2000);
g.convert_to_note(top.id).unwrap();
g.remove_from_hub(note.id, sub.id).unwrap();
g.delete_page(sub.id).unwrap();
h.restore_graph(&g, &s1.id, T0 + 3000).unwrap();
let top = g.page_by_title("Top").unwrap().unwrap();
assert!(top.is_hub());
assert_eq!(top.description, "All my stuff,\nin one place");
assert!(
g.page_tree(top.id).unwrap().is_empty(),
"hubs have no blocks"
);
let sub = g.page_by_title("Sub").unwrap().expect("sub hub restored");
assert!(g.page_by_title("Sub 2").unwrap().is_none());
assert!(sub.is_hub());
assert_eq!(g.hub_members(top.id).unwrap(), vec![sub.id]);
assert_eq!(g.hub_members(sub.id).unwrap(), vec![note.id]);
assert_eq!(g.hubs_of(note.id).unwrap(), vec![sub.id]);
assert_eq!(g.page_tree(note.id).unwrap()[0].1.content, "body");
// A single page restore brings back its memberships too.
at(&g, T0 + 4000);
g.set_page_hubs(note.id, vec![]).unwrap();
h.restore_page(&g, "Note", &s1.id, T0 + 5000).unwrap();
assert_eq!(g.hubs_of(note.id).unwrap(), vec![sub.id]);
// Restoring a deleted hub alone brings its members back (they hold the membership).
at(&g, T0 + 5100);
g.delete_page(sub.id).unwrap();
let s3 = h.snapshot(&g, T0 + 5200).unwrap().unwrap();
let note_md = h.page_at(&s3.id, "Note").unwrap().unwrap();
assert!(!note_md.contains("synapse-hubs"), "{note_md}");
h.restore_page(&g, "Sub", &s1.id, T0 + 5300).unwrap();
let sub = g.page_by_title("Sub").unwrap().unwrap();
assert!(sub.is_hub());
assert_eq!(g.hub_members(sub.id).unwrap(), vec![note.id]);
assert_eq!(g.hubs_of(sub.id).unwrap(), vec![top.id]);
// The next snapshot matches the original export.
let s = h
.snapshot(&g, T0 + 6000)
.unwrap()
.unwrap_or_else(|| h.snapshots(1).unwrap().remove(0));
for title in ["Top", "Sub", "Note"] {
assert_eq!(
h.page_at(&s.id, title).unwrap(),
h.page_at(&s1.id, title).unwrap(),
"{title}"
);
}
}
+4 -2
View File
@@ -1,4 +1,4 @@
//! `cargo run -p synapse-import --example import -- <logseq_dir> <graph_dir> [--skip-existing]`
//! `cargo run -p synapse-import --example import -- <logseq_dir> <graph_dir> [--skip-existing] [--keep-legacy]`
use std::path::PathBuf;
use synapse_core::Graph;
@@ -7,13 +7,14 @@ use synapse_import::{ExistingPages, ImportOptions, import_logseq};
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let skip = args.iter().any(|a| a == "--skip-existing");
let keep_legacy = args.iter().any(|a| a == "--keep-legacy");
let paths: Vec<PathBuf> = args
.iter()
.filter(|a| !a.starts_with("--"))
.map(PathBuf::from)
.collect();
let [src, dst] = paths.as_slice() else {
eprintln!("usage: import <logseq_dir> <graph_dir> [--skip-existing]");
eprintln!("usage: import <logseq_dir> <graph_dir> [--skip-existing] [--keep-legacy]");
std::process::exit(2);
};
let graph = Graph::open(dst).expect("open graph");
@@ -23,6 +24,7 @@ fn main() {
} else {
ExistingPages::Update
},
skip_legacy_pages: !keep_legacy,
};
let started = std::time::Instant::now();
let mut last = (None, 0);
+76 -3
View File
@@ -39,9 +39,22 @@ pub enum ExistingPages {
Skip,
}
#[derive(Debug, Clone, Default)]
#[derive(Debug, Clone)]
pub struct ImportOptions {
pub existing: ExistingPages,
/// Skip the files of Logseq's organisational pages (`contents`, `card`, `favorites`,
/// `hls__*`; see [`is_skipped_legacy`]) and drop the empty stubs their refs would create
/// in this import. Other built-in names (`TODO`, `NOW`, ...) are imported normally.
pub skip_legacy_pages: bool,
}
impl Default for ImportOptions {
fn default() -> Self {
Self {
existing: ExistingPages::default(),
skip_legacy_pages: true,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -78,6 +91,8 @@ pub struct Report {
pub unchanged: usize,
/// `.org` files imported as raw blocks (relative paths).
pub org_files: Vec<String>,
/// Legacy organisational pages left out (relative paths), see `skip_legacy_pages`.
pub skipped_legacy: Vec<String>,
pub warnings: Vec<String>,
}
@@ -163,7 +178,16 @@ pub fn import_logseq(
.collect();
docs.extend(parsed);
}
let docs = dedupe(docs, &mut report.warnings);
let mut docs = dedupe(docs, &mut report.warnings);
if opts.skip_legacy_pages {
docs.retain(|d| {
let legacy = d.journal.is_none() && is_skipped_legacy(&d.title);
if legacy {
report.skipped_legacy.push(d.rel.clone());
}
!legacy
});
}
// ---- origin journals: earliest journal referencing each page (aliases resolved)
let mut alias_to_key: HashMap<String, String> = HashMap::new();
@@ -187,10 +211,52 @@ pub fn import_logseq(
// One transaction for the whole write phase: much faster, and a failed import leaves the
// graph untouched.
track::init(graph)?;
graph.transaction(|g| write_all(g, opts, &docs, &origin, &mut report, &mut progress))?;
graph.transaction(|g| {
let before: HashSet<PageId> = if opts.skip_legacy_pages {
page_ids(g)?
} else {
HashSet::new()
};
write_all(g, opts, &docs, &origin, &mut report, &mut progress)?;
if opts.skip_legacy_pages {
drop_legacy_stubs(g, &before)?;
}
Ok(())
})?;
Ok(report)
}
/// Logseq files the importer leaves out when `skip_legacy_pages` is set: `contents`, `card`,
/// `favorites` and PDF highlight pages (`hls__*`).
pub fn is_skipped_legacy(title: &str) -> bool {
let key = title_key(title);
key.starts_with("hls__") || ["contents", "card", "favorites"].contains(&key.as_str())
}
fn page_ids(g: &Graph) -> Result<HashSet<PageId>> {
Ok(g.list_pages(false, u32::MAX, 0)?
.into_iter()
.map(|p| p.id)
.collect())
}
/// Refs to `[[contents]]`, `[[card]]`, ... make core create empty stub pages; remove the ones
/// this import created (pages that existed before are never touched).
fn drop_legacy_stubs(g: &Graph, before: &HashSet<PageId>) -> Result<()> {
let stubs: Vec<PageId> = g
.list_pages(false, u32::MAX, 0)?
.into_iter()
.filter(|p| !before.contains(&p.id) && is_skipped_legacy(&p.title))
.map(|p| p.id)
.collect();
for id in stubs {
if g.page_tree(id)?.is_empty() {
g.delete_page(id)?;
}
}
Ok(())
}
fn write_all(
graph: &Graph,
opts: &ImportOptions,
@@ -218,6 +284,13 @@ fn write_all(
let d = &docs[i];
let o = origin.get(&d.key).copied();
match graph.transaction(|g| ensure_page(g, d, o)) {
// Hubs are Synapse-only pages without blocks: a re-import never writes them.
Ok((pid, true)) if graph.get_page(pid)?.is_some_and(|p| p.is_hub()) => {
report.warnings.push(format!(
"{}: {:?} is a hub in Synapse, skipped",
d.rel, d.title
));
}
Ok(r) => {
ids.insert(i, r);
}
+79
View File
@@ -146,6 +146,7 @@ fn reimport_updates_changed_pages_and_skip_mode() {
.unwrap();
let skip = ImportOptions {
existing: ExistingPages::Skip,
..Default::default()
};
let r = import_logseq(src.path(), &g, &skip, |_| {}).unwrap();
assert_eq!(r.updated, 0);
@@ -334,3 +335,81 @@ fn renamed_page_is_not_duplicated() {
let t = texts(&g, "Renamed");
assert_eq!(t.len(), 2);
}
#[test]
fn skips_legacy_pages_and_their_stubs() {
let files = [
("pages/contents.md", "- [[Alpha]]\n"),
("pages/TODO.md", "- old\n"),
("pages/hls__book_1.md", "- highlight\n"),
(
"pages/Alpha.md",
"- see [[contents]], [[card]], [[favorites]] and [[TODO]]\n",
),
];
let src = mini_graph(&files);
let dir = tempfile::tempdir().unwrap();
let g = Graph::open(dir.path()).unwrap();
// A page that already exists is never removed, even with a legacy title and no blocks.
let card = g.ensure_page("card", None).unwrap();
let r = imp(src.path(), &g);
assert_eq!(r.pages, 2, "Alpha and TODO");
assert_eq!(
r.skipped_legacy,
["pages/contents.md", "pages/hls__book_1.md"]
);
for t in ["contents", "favorites", "hls__book_1"] {
assert!(g.page_by_title(t).unwrap().is_none(), "{t}");
}
assert_eq!(
texts(&g, "TODO").len(),
1,
"other built-ins import normally"
);
assert_eq!(g.page_by_title("card").unwrap().unwrap().id, card.id);
let keep = ImportOptions {
skip_legacy_pages: false,
..Default::default()
};
let dir2 = tempfile::tempdir().unwrap();
let g2 = Graph::open(dir2.path()).unwrap();
let r = import_logseq(src.path(), &g2, &keep, |_| {}).unwrap();
assert!(r.skipped_legacy.is_empty());
assert!(g2.page_by_title("contents").unwrap().is_some());
}
#[test]
fn reimport_never_writes_hubs() {
let src = mini_graph(&[
("pages/Area.md", "- [[Note]]\n- more\n"),
("pages/Note.md", "- body\n"),
]);
let dir = tempfile::tempdir().unwrap();
let g = Graph::open(dir.path()).unwrap();
imp(src.path(), &g);
let area = g.page_by_title("Area").unwrap().unwrap();
let note = g.page_by_title("Note").unwrap().unwrap();
g.convert_to_hub(
area.id,
&synapse_core::HubConversion {
title: "Area".into(),
description: "d".into(),
members: vec![note.id],
keep_outline_as: None,
},
)
.unwrap();
std::fs::write(src.path().join("pages/Area.md"), "- [[Note]]\n- changed\n").unwrap();
let r = imp(src.path(), &g);
assert!(
r.warnings.iter().any(|w| w.contains("is a hub")),
"{:?}",
r.warnings
);
let area = g.page_by_title("Area").unwrap().unwrap();
assert!(area.is_hub());
assert!(g.page_tree(area.id).unwrap().is_empty());
assert_eq!(g.hub_members(area.id).unwrap(), vec![note.id]);
}
+6 -1
View File
@@ -1,4 +1,5 @@
//! tantivy-backed full-text index: one document per block and one per page (title + aliases).
//! tantivy-backed full-text index: one document per block and one per page (title + aliases,
//! plus the description of hubs as content).
use crate::error::Result;
use crate::{Filter, JournalFilter, Scope};
@@ -184,6 +185,7 @@ impl FullText {
id: Uuid,
title: &str,
aliases: &[String],
description: &str,
day: i64,
journal: bool,
) -> Result<()> {
@@ -196,6 +198,9 @@ impl FullText {
for a in aliases {
d.add_text(self.f.title, a);
}
if !description.is_empty() {
d.add_text(self.f.content, description);
}
d.add_i64(self.f.day, day);
d.add_u64(self.f.journal, journal as u64);
self.writer.add_document(d)?;
+4 -2
View File
@@ -318,7 +318,8 @@ impl Search {
Some(d) => (day_of_date(d), true),
None => (day_of_ms(p.updated_at), false),
};
self.ft.upsert_page(id, &p.title, &aliases, day, journal)?;
self.ft
.upsert_page(id, &p.title, &aliases, &p.description, day, journal)?;
}
None => {
self.ft.delete(id);
@@ -350,7 +351,8 @@ impl Search {
Some(d) => (day_of_date(d), true),
None => (day_of_ms(p.updated_at), false),
};
self.ft.upsert_page(p.id, &p.title, &al, day, journal)?;
self.ft
.upsert_page(p.id, &p.title, &al, &p.description, day, journal)?;
}
}
Ok(())
+4 -4
View File
@@ -40,15 +40,15 @@ pub(crate) fn quantize(v: &[f32]) -> (Vec<i8>, f32) {
fn dot(row: &[i8], q: &[f32]) -> f32 {
let mut acc = [0f32; 8];
let mut rc = row.chunks_exact(8);
let mut qc = q.chunks_exact(8);
for (r, c) in (&mut rc).zip(&mut qc) {
let (rc, r_rem) = row.as_chunks::<8>();
let (qc, q_rem) = q.as_chunks::<8>();
for (r, c) in rc.iter().zip(qc) {
for i in 0..8 {
acc[i] += r[i] as f32 * c[i];
}
}
let mut s: f32 = acc.iter().sum();
for (r, c) in rc.remainder().iter().zip(qc.remainder()) {
for (r, c) in r_rem.iter().zip(q_rem) {
s += *r as f32 * c;
}
s
+18
View File
@@ -331,3 +331,21 @@ fn store_inside_graph_transaction_and_rename_delete() {
assert!(s.search(&g, "ferris", &f, 10).unwrap().is_empty());
assert_eq!(s.vector_counts(&g, "test/hash").unwrap(), (1, 0));
}
#[test]
fn hub_titles_and_descriptions_are_indexed() {
let (_d, g) = setup();
let h = g.create_hub("Anime", "Japanese animation series").unwrap();
add(&g, "Other", "nothing related");
let mut s = Search::open(&g).unwrap();
s.sync(&g).unwrap();
let f = Filter::default();
let hits = s.search(&g, "animation", &f, 5).unwrap();
assert_eq!(hits[0].kind, HitKind::Page);
assert_eq!(hits[0].page_id, h.id);
assert_eq!(s.search(&g, "anime", &f, 5).unwrap()[0].page_id, h.id);
g.set_hub_description(h.id, "Cartoons from Japan").unwrap();
s.sync(&g).unwrap();
assert!(s.search(&g, "animation", &f, 5).unwrap().is_empty());
assert_eq!(s.search(&g, "cartoons", &f, 5).unwrap()[0].page_id, h.id);
}
+33
View File
@@ -162,6 +162,39 @@ async fn concurrent_edits_resolve_last_writer_wins() {
assert_eq!(texts(&b, "Shared"), vec!["from A"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn hubs_and_memberships_converge() {
let srv = TestServer::start().await;
let a = device(&srv, "h");
let b = device(&srv, "h");
let (hub, note) = {
let g = a.g();
let hub = g.create_hub("Top", "All of it").unwrap();
let note = g.create_page(NewPage::titled("Note")).unwrap();
g.add_to_hub(note.id, hub.id).unwrap();
(hub.id, note.id)
};
a.client.sync_once().await.unwrap();
b.client.sync_once().await.unwrap();
{
let g = b.g();
let h = g.get_page(hub).unwrap().unwrap();
assert!(h.is_hub());
assert_eq!(h.description, "All of it");
assert_eq!(g.hub_members(hub).unwrap(), vec![note]);
assert_eq!(g.hubs_of(note).unwrap(), vec![hub]);
// B deletes the hub: the member's list is cleaned on both sides.
g.delete_page(hub).unwrap();
}
b.client.refresh_pending().await.unwrap();
b.client.sync_once().await.unwrap();
a.client.sync_once().await.unwrap();
let g = a.g();
assert!(g.get_page(hub).unwrap().is_none());
assert!(g.get_page(note).unwrap().unwrap().hubs.is_empty());
assert!(g.hubs_of(note).unwrap().is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn auth_failures() {
let srv = TestServer::start().await;
+82 -8
View File
@@ -33,7 +33,7 @@ flutter build linux --release # build/linux/x64/release/bundle/
flutter run -d <android-device> # or: flutter build apk --release
flutter build windows --release # on Windows
```
The graph lives in the platform app-support dir (`~/.local/share/es.zenvairo.synapse/graph`
The graph lives in the platform app-support dir (`~/.local/share/dev.dasemu.synapse/graph`
on Linux). Override it with `SYNAPSE_GRAPH=/path/to/graph`.
## After changing the FFI API
@@ -57,27 +57,101 @@ Commit the regenerated `crates/synapse-ffi/src/frb_generated.rs` and `app/lib/sr
block, Delete at end pulls the next one in, ↑/↓/←/→ cross block edges, Alt+Shift+↑/↓ move
among siblings, Ctrl+↑/↓ collapse/expand, Ctrl+Enter cycles TODO/DONE, Esc leaves editing.
- `[[`, `((` auto-pair; `[[`, `#` and `((` open autocomplete (↑/↓, Enter/Tab, Esc).
- `/` at the start of a word opens the command menu: `/link` (page link, then the page picker),
`/ref`, `/url`, `/image`, `/bold`, `/italic`, `/strike`, `/highlight`, `/code`, `/codeblock`,
`/h1`–`/h3`, `/todo`, `/quote`, `/divider`, `/today`, `/tag` (`SlashCommand` in
`editor/completion.dart`).
- Rich text is Markdown: `**bold**`, `*italic*`, `~~strike~~`, `==highlight==`, `` `code` ``,
`[label](url)`, `![img](url)`. A backslash escapes punctuation (`\*` shows a literal `*`,
`\[[` is not a link); the backslash is hidden when the block is not being edited.
- Ctrl+B / I / E / L and Ctrl+Shift+S / H wrap the selection (or the caret) in bold, italic,
code, page link, strike and highlight; pressing again unwraps.
- Drag a bullet onto a row: upper half = before, lower half = after, lower half to the right
= first child.
- Edits apply locally at once and go to the core through one serial write queue (text saves
are debounced 350 ms); after structural edits the outline is re-read and the core's
structure wins if they ever disagree.
- App shortcuts: Ctrl+K quick switcher, Ctrl+Shift+J journals, Ctrl+Shift+T timeline,
Ctrl+\ sidebar, Alt+←/→ back/forward.
- App shortcuts (defaults, all rebindable in Settings): Ctrl+K quick switcher, Ctrl+Shift+J
journals, Ctrl+Shift+G graph, Ctrl+Shift+T timeline, Ctrl+\ sidebar, Ctrl+Shift+\ graph
sidebar, Ctrl+, settings, Alt+←/→ back/forward.
## Settings, themes and key bindings
- Sidebar "Settings" (Ctrl+,): theme cards and the shortcut list. Click a shortcut, press the new
combination (Esc cancels); a combo already in use is refused and names its owner; each row
and "Reset all" restore defaults.
- Themes (`appThemes` in `theme/theme.dart`): System (Paper light/dark by OS), Paper, Paper dark,
Sweet (KDE-style indigo and magenta), Sweet light, Nord. A theme is a `SynapseColors` palette.
- Preferences live in `app-settings.json` inside the graph directory (`FileSettings`);
`Keymap` (`state/keymap.dart`) stores only the overrides, encoded as `ctrl+shift+<keyId>`.
## Types and tags
- **Type** (what a note is): plain names, no page (persona, lugar, empresa, cliente, herramienta,
concepto, idea, ...). "Type" under the header opens a picker with the types in use (with count)
and seeded suggestions, or type a new name. Stored in `Page.types`.
- **Tag** (a topic): a real page of kind `tag`. "Tag" opens a picker over the existing tag pages
or creates one by typing a new name (a note used as a tag becomes a tag page; hubs, journals
and templates cannot be tags). Tag chips open the tag page, which lists its tagged notes.
An inline `#tema` or `[[tema]]` in the text also links to the page. Renaming or deleting a tag
page updates its members. Tag pages cannot be tagged themselves.
- In the graph a tagged note points at its tag pages with a separate edge kind (TAGGED), apart
from page links and inline references.
## Hubs, namespaces and cleanup
- **Hub** (folder icon): a page kind, not a note: no outline, a title, a short description
and members (notes and sub-hubs). Membership is stored on the member (its parent hubs), so
a page belongs to at most one hub (adding it to another hub moves it); cycles are rejected. **Namespace** (tree icon): `A/B/C`
titles; `A/B` is the parent of `A/B/C` even when it does not exist yet.
- Hubs never appear in the sidebar's "RECENT" list (they are folders, not pages).
- Sidebar "HUBS" (always shown, "+" creates a hub): tree of root hubs, collapsed by default;
unfolding a hub lists only its sub-hubs (notes live on the hub screen), above "RECENT";
reloads after edits settle.
- Hub screen ends with the local graph panel (same as the page sidebar on notes).
- Every hub has a template (a hidden note, possibly empty): "Template" on the hub screen opens
it for editing, and notes created from "Add" start as a copy of it.
- Hub screen: editable title and description (saved on blur), members listed sub-hubs first
then by title, "Add" (pick a page, or create a note / sub-hub), × on hover or long-press
to remove, `⋯` ▸ "Convert to note" (description and members become blocks and links).
- Notes: namespace breadcrumb, "In: ..." chips with a × to leave a hub, and a `⋯` menu
with "Convert to hub…" (dialog: shortened title, description, member checklist, optional
note that keeps the original outline; title clashes are shown inline) and "Add to hub…".
- All pages ▸ "Clean up": dialog listing legacy Logseq pages (`contents`, `hls__...`, pages
with `type:: system`, ...) with checkboxes; "Delete (n)" removes only the checked ones
and their blocks.
## Page sidebar and All pages
- The sidebar icon next to a note's `⋯` menu toggles a right sidebar (collapsed by default,
state in `AppState.pageSidebar`) with the local graph (neighbourhood at depth 1–3) and the
related pages; on narrow windows they appear below the content.
- All pages lists notes only (hubs are folders, not pages) and can be sorted by edited,
created or title, ascending or descending.
## Graph view
One view (sidebar "Graph", Ctrl+Shift+G) with a mode selector:
- **Network**: force-directed graph of pages (journals optional). Edges: links, tags,
- **Network**: force-directed graph of pages (journals shown by default). Edges: links, tags,
property refs, block refs/embeds (aggregated per page) and dashed mentions (unlinked
references: a page title appearing as whole words in another page's text). Node size by
degree + backlinks, colour by cluster or primary tag. Filters: title, tag, created date
degree + backlinks, colour by cluster, primary tag or home hub. Hubs (a page kind: folders of
notes) are drawn larger with a ring in every mode including Synapses (one batched draw per
size), connected to their members by thin solid "contains" edges (CONTAINS, structural, on by
default), both marked in the legend. Filters: title, tag, created date
range, min links, orphans, journals, mentions. Drag nodes, hover highlights neighbours,
wheel/pinch zoom, tap opens the page.
- **Local**: neighbourhood of a page at depth 1–3 (also a side panel on every page).
- **Synapses**: `related()` spreading activation from a focus page; brightness/size =
activation, edge thickness = Hebbian synapse weight, a pulse travels outward by hops.
- **Clusters**: Louvain communities with soft hulls.
- **Namespaces**: radial tree of `a/b/c` titles and of tags with their pages.
- **Clusters**: soft hulls grouped by "Hubs" (home hub, default when the graph has hubs; hull
labelled with the hub title once it is wide enough on screen; layout-only springs pull
members to their hub), by "Tags" (each page goes to its most widely used tag page, ties
alphabetical; hull labelled with the tag name; springs pull pages to the best connected page
of the tag; journals and untagged pages stay out) or by "Communities" (Louvain: groups found
automatically from link density, no names). Colours follow group size.
- **Tree** (no "Hubs" node: root hubs and the notes that sit in no hub, orphans included,
hang straight off the centre): the centre is labelled with the store name (graph directory name); every arm and
sub-branch has its own colour (arms evenly spread over the hue circle, children split their
parent's sector evenly); drag a node to move it with its branch, drag empty space to pan.
Radial tree: hubs (root hubs, then members recursively, cycle-safe,
each hub expanded once, folder glyph; membership = CONTAINS edges from the graph data),
namespaces (`a/b/c` titles, attached straight to the centre, no "Namespaces" node)
and Tags (with their pages).
- **Timeline**: the journal timeline.
Data and layout live in Rust: `SynapseGraph::graph_data()` returns the whole page-level
+58
View File
@@ -27,6 +27,64 @@ crates may add their own tables to the same database (prefix them: `search_*`, `
- **Synapses**: local weighted associations between pages (Hebbian, 30-day half-life).
- **Assets**: metadata rows; bytes in the blob store.
## Tags and types (`synapse-core::{tags, types}`)
- **Tags are pages** of kind `tag` (topics such as "tecnología"). A page carries
`Page.tags: Vec<String>` (tag page titles; `pages.tags`, schema v5, synced with the page, LWW
per page); the derived `page_tags(page_id, tag_key)` index is rewritten on every page write.
Setting a tag creates the tag page or converts a note to one; hubs, journals and templates
cannot be tags, and tag pages cannot be tagged. Renaming/deleting a tag page rewrites/removes
it in its members; opening the graph creates tag pages for tag names that lack one.
API: `set_page_tags`, `add_page_tag`, `remove_page_tag`, `pages_with_tag`, `tag_catalog`.
The graph has a `TAGGED` edge from each tagged page to its tag pages.
- **Types** are plain names saying what a page is: `Page.types` (`pages.types`, no page, no
index). API: `set_page_types`, `add_page_type`, `remove_page_type`, `type_catalog` (types in
use by count, then the seeded `SUGGESTED_TYPES`).
- Both are exported as `synapse-tags::` / `synapse-types::`, and tag pages as
`synapse-kind:: tag` (see `history.md`).
## Hubs and namespaces (`synapse-core::structure`)
Two orthogonal ways to organise pages.
- **Namespace** (kinship by title, derived): `A/B` is a child of `A` (`namespace_parent`,
`Graph::namespace_children`). Parents may not exist as pages (virtual levels).
- **Hub** (folder, explicit): a page with `kind = hub` (`PageKind`, schema v3 column
`pages.kind`). A hub has a `description` and **no blocks** (`insert_block`/`put_block`/
`move_block` into a hub fail with `Error::Invalid`). Created with `create_hub`, or by
`convert_to_hub` (manual, from an existing note) and undone with `convert_to_note`.
- Membership lives on the **member**: `Page.hubs: Vec<PageId>` (`pages.hubs`, JSON), synced
with the page (`UpsertPage`, LWW per page), so no new op exists. A derived local index
`page_hubs(page_id, hub_id)` is rewritten on every page write (local or remote) and rebuilt
by the v2 → v3 migration.
- **One hub per page**: the list holds at most one id (local writes with more are refused;
`add_to_hub` moves the page). The wire format stays a list, and readers (index, `structure`)
use only its first entry, so data from older replicas converges.
- **Template**: every hub owns exactly one page with `kind = template` (member of its hub,
possibly empty, an ordinary outline). `create_hub`/`convert_to_hub` create it,
`hub_template` returns it (creating one for older hubs). Templates are hidden from
`hub_members`, `list_pages` and `structure`, cannot be deleted alone and go with their hub
(`convert_to_note` deletes it). `create_page_from_template(hub, title)` makes a note in the
hub with a copy of the template's blocks.
- API: `set_page_hubs`, `add_to_hub`, `remove_from_hub`, `hub_members` (sub-hubs first, then
by title), `hubs_of`. Rules: the target must be a hub, no self-membership, no journals, no
cycles (checked locally); duplicates dropped. Readers ignore ids that dangle or point at a
page that is no longer a hub. Deleting a hub or converting it to a note removes its id from
every member (one `UpsertPage` per member).
- `hub_conversion_preview` suggests a title (last namespace segment), a description (first
prose block, plain text, <= 280 chars) and members (outline refs, then property and tag
refs). `convert_to_hub` applies a `HubConversion` in one transaction: rename (link
rewrite), optionally move the outline to a new note (`keep_outline_as`), delete the
remaining blocks, set kind/description and add the members.
- `Graph::structure()` returns every hub with members and nesting depth, and each page's
*home hub* (deepest containing hub; ties: fewer members, then title; a hub is its own
home). Cycles created by concurrent edits on two replicas are broken deterministically
(edges ordered by the member page's HLC). The graph view adds `CONTAINS` edges hub → member.
- Sync limits: `apply_remote` does not enforce "no blocks" (rejecting would break
convergence), so a block added on one replica while another converts the page can land in
a hub; `convert_to_note` keeps such blocks. Clients older than schema v3 drop `kind`,
`description` and `hubs` when they upsert a page, so every client must be on v3.
- Logseq built-ins (`contents`, `TODO`, `hls__*`, ...) are recognised by `is_legacy_page`; the
app offers to purge them (`legacy_candidates` / `purge_pages` in `synapse-ffi`). The importer
only skips a narrower set (see `import.md`).
## Temporal model
- `journal_neighbors(date)` gives the previous/next existing journal (episodic chain).
- Pages created from a journal block are born there; other new pages are born in today's
+4
View File
@@ -12,6 +12,10 @@ works on it (`git --git-dir=<graph>/history log`, `clone`, ...).
bullet. Blocks targeted by `((uuid))` get an `id::` property. `collapsed:: true` is kept.
- Property values: raw text, or JSON when the value is not a plain string (so numbers/bools
survive a restore). Keys are sorted, so output is byte-stable.
- Hubs: `synapse-kind:: hub` and `synapse-description::` page properties (hubs have no
bullets). A page's tags (tag page titles) are listed in `synapse-tags:: ["a","b"]` and its types in `synapse-types:: [...]`; tag pages carry `synapse-kind:: tag` (all restored with the page). A page in hubs lists their titles in `synapse-hubs:: ["A","B"]`, so renaming a hub
re-exports its members. Restore sets kinds first, then memberships (missing hubs or
memberships that would now form a cycle are skipped).
- `assets.json`: manifest `hash → name/size/mime`, sorted. Asset bytes are **not** committed
(the blob store is already content-addressed) unless `HistoryOptions::include_blobs`, which
adds `blobs/<hash>`.
+10 -2
View File
@@ -1,7 +1,7 @@
# Logseq import
Crate `synapse-import`: `import_logseq(src, &graph, &ImportOptions, progress) -> Report`.
CLI: `cargo run --release -p synapse-import --example import -- <logseq_dir> <graph_dir> [--skip-existing]`.
CLI: `cargo run --release -p synapse-import --example import -- <logseq_dir> <graph_dir> [--skip-existing] [--keep-legacy]`.
## Pipeline
1. **Scan** `pages/`, `journals/` (`.md`, `.org`) and `assets/` (recursive). Settings are read from
@@ -22,6 +22,14 @@ CLI: `cargo run --release -p synapse-import --example import -- <logseq_dir> <gr
`collapsed:: true` sets the flag.
- Assets: `../assets/x%20y.png` → `asset://<blake3>` in place (`![alt](asset://…)`; `?`/`#`
suffixes kept). Missing files are left as is and reported.
- Logseq's organisational files `contents`, `card`, `favorites` and `hls__*` (PDF highlights)
are skipped (`ImportOptions::skip_legacy_pages`, default on; `--keep-legacy` in the CLI); other
built-in names (`TODO`, `NOW`, ...) import normally. Skipped paths go to
`Report::skipped_legacy`, and empty stubs with those titles that refs created *in this import*
are removed (pages that existed before are never touched). Purging other legacy pages is a
manual action in the app (`legacy_candidates` / `purge_pages`).
- Hubs (Synapse-only pages without blocks, see `architecture.md`) are never written by a
re-import: the file is skipped with a warning.
- `.org` files: one raw root block per top-level heading, no parsing; listed in `Report::org_files`.
- Timestamps: page `created_at` = file birth time (≤ mtime), `updated_at` = mtime; blocks inherit
them. `origin_journal` = earliest journal referencing the page (aliases resolved), else the
@@ -45,7 +53,7 @@ The importer records what it wrote in two local tables (`import_pages`: source f
## Report / progress
`Progress { phase, done, total }` (phases: Scanning, Assets, Parsing, Pages, Blocks) and
`Report { pages, journals, blocks, assets, bytes, updated, unchanged, org_files, warnings }`.
`Report { pages, journals, blocks, assets, bytes, updated, unchanged, org_files, skipped_legacy, warnings }`.
## Known limits
- Not parsed: org-mode syntax, whiteboards, `draws/`, namespace parent stubs, Logseq queries.