diff --git a/app/integration_test/graph_smoke_test.dart b/app/integration_test/graph_smoke_test.dart index 63e2d7e..c344254 100644 --- a/app/integration_test/graph_smoke_test.dart +++ b/app/integration_test/graph_smoke_test.dart @@ -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); diff --git a/app/lib/main.dart b/app/lib/main.dart index 1a1e79b..4a35013 100644 --- a/app/lib/main.dart +++ b/app/lib/main.dart @@ -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 main() async { WidgetsFlutterBinding.ensureInitialized(); @@ -20,5 +21,10 @@ Future 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'), + ), + ); } diff --git a/app/lib/src/app.dart b/app/lib/src/app.dart index 982cad8..2ab66e9 100644 --- a/app/lib/src/app.dart +++ b/app/lib/src/app.dart @@ -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 createState() => _SynapseAppState(); } class _SynapseAppState extends State { - 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 { 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(), + ); + }, ), ); } diff --git a/app/lib/src/backend/graph_backend.dart b/app/lib/src/backend/graph_backend.dart index 9ccf93d..eee529e 100644 --- a/app/lib/src/backend/graph_backend.dart +++ b/app/lib/src/backend/graph_backend.dart @@ -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 putAssetFile(String path, {String? mime}); + /// Hub (folder) structure of the whole graph. + Future hubs(); + Future pageStructure(String pageId); + Future 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 setPageTags(String pageId, List tags); + Future addPageTag(String pageId, String tag); + Future removePageTag(String pageId, String tag); + + Future setPageTypes(String pageId, List types); + Future addPageType(String pageId, String type); + Future removePageType(String pageId, String type); + + /// Types in use (most used first), then the seeded suggestions not used yet. + Future> typeCatalog(); + + /// Tag pages, most used first. + Future> tagCatalog(); + Future> pagesWithTag(String tag); + + /// Id of the hub's template page (opens like a note; may be empty). + Future hubTemplate(String hubId); + + /// Creates a note in the hub, starting from a copy of the hub's template. + Future createPageFromTemplate(String hubId, String title); + Future setHubDescription(String hubId, String description); + + /// Membership is stored on the member: it lists the hub among its parents. + Future addToHub(String pageId, String hubId); + Future removeFromHub(String pageId, String hubId); + Future hubConversionPreview(String pageId); + Future convertToHub( + String pageId, + String title, + String description, + List memberIds, { + String? keepOutlineAs, + }); + Future convertToNote(String pageId); + + /// Logseq leftovers that can be removed, and their removal. Returns the number deleted. + Future> legacyCandidates(); + Future purgePages(List ids); + /// The whole page-level graph (cached by the core until the graph changes). Future 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 open(String dir) async => - FfiGraphBackend(await SynapseGraph.open(dir: dir)); + @override + final String graphName; + + static Future 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 putAssetFile(String path, {String? mime}) => _g.putAssetFile(path: path, mime: mime); + @override + Future hubs() => _g.hubs(); + @override + Future pageStructure(String pageId) => + _g.pageStructure(pageId: pageId); + @override + Future setPageTags(String pageId, List tags) => + _g.setPageTags(pageId: pageId, tags: tags); + @override + Future addPageTag(String pageId, String tag) => + _g.addPageTag(pageId: pageId, tag: tag); + @override + Future removePageTag(String pageId, String tag) => + _g.removePageTag(pageId: pageId, tag: tag); + @override + Future setPageTypes(String pageId, List types) => + _g.setPageTypes(pageId: pageId, types: types); + @override + Future addPageType(String pageId, String type) => + _g.addPageType(pageId: pageId, ty: type); + @override + Future removePageType(String pageId, String type) => + _g.removePageType(pageId: pageId, ty: type); + @override + Future> typeCatalog() => _g.typeCatalog(); + + @override + Future> tagCatalog() => _g.tagCatalog(); + @override + Future> pagesWithTag(String tag) => _g.pagesWithTag(tag: tag); + + @override + Future hubTemplate(String hubId) => _g.hubTemplate(hubId: hubId); + + @override + Future createPageFromTemplate(String hubId, String title) => + _g.createPageFromTemplate(hubId: hubId, title: title); + + @override + Future createHub(String title, String description) => + _g.createHub(title: title, description: description); + @override + Future setHubDescription(String hubId, String description) => + _g.setHubDescription(hubId: hubId, description: description); + @override + Future addToHub(String pageId, String hubId) => + _g.addToHub(pageId: pageId, hubId: hubId); + @override + Future removeFromHub(String pageId, String hubId) => + _g.removeFromHub(pageId: pageId, hubId: hubId); + @override + Future hubConversionPreview(String pageId) => + _g.hubConversionPreview(pageId: pageId); + @override + Future convertToHub( + String pageId, + String title, + String description, + List memberIds, { + String? keepOutlineAs, + }) => _g.convertToHub( + pageId: pageId, + title: title, + description: description, + memberIds: memberIds, + keepOutlineAs: keepOutlineAs, + ); + @override + Future convertToNote(String pageId) => + _g.convertToNote(pageId: pageId); + @override + Future> legacyCandidates() => _g.legacyCandidates(); + @override + Future purgePages(List ids) => _g.purgePages(ids: ids); + @override Future graphData() => _g.graphData(); diff --git a/app/lib/src/editor/block_row.dart b/app/lib/src/editor/block_row.dart index 127b2e5..fe37180 100644 --- a/app/lib/src/editor/block_row.dart +++ b/app/lib/src/editor/block_row.dart @@ -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 { final seq = ++_searchSeq; final backend = c.backend; Future> 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 { 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 { 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, diff --git a/app/lib/src/editor/completion.dart b/app/lib/src/editor/completion.dart index 486d341..d9cda2b 100644 --- a/app/lib/src/editor/completion.dart +++ b/app/lib/src/editor/completion.dart @@ -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 matchCommands(String query, {int limit = 8}) { + final q = query.toLowerCase(); + final starts = []; + final rest = []; + 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}]]'; diff --git a/app/lib/src/editor/markdown.dart b/app/lib/src/editor/markdown.dart index d773882..a057497 100644 --- a/app/lib/src/editor/markdown.dart +++ b/app/lib/src/editor/markdown.dart @@ -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); diff --git a/app/lib/src/graph/graph_model.dart b/app/lib/src/graph/graph_model.dart index dcaed37..378942c 100644 --- a/app/lib/src/graph/graph_model.dart +++ b/app/lib/src/graph/graph_model.dart @@ -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 hubOrder = () { + final count = {}; + 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 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> hubMembers = () { + final m = >{}; + 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] ??= {}).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 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 _tagUse = () { + final m = {}; + 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 = {}; + + /// 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 tagGroups = () { + final count = {}; + 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 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 nodes, { + double strength = 0.6, + }) { + final anchor = {}; + 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 tags = () { final count = {}; @@ -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, }, }); diff --git a/app/lib/src/graph/network_canvas.dart b/app/lib/src/graph/network_canvas.dart index 05e63a4..ed71a9f 100644 --- a/app/lib/src/graph/network_canvas.dart +++ b/app/lib/src/graph/network_canvas.dart @@ -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 graphPalette(Brightness b) => b == Brightness.light @@ -119,6 +119,7 @@ class NetworkCanvasState extends State // Reused point buffers (no per-frame allocation or boxing). final _edgeBufs = {}; final _nodeBufs = <(int, int), _Buf>{}; + final _hubBufs = {}; Float32List _meshPos = Float32List(0); Int32List _meshCol = Int32List(0); double _startScale = 1; @@ -189,6 +190,8 @@ class NetworkCanvasState extends State 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 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)>(); + static final _hullLabels = Expando<(Color, Map)>(); + 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 = >{}; + /// 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 = >{}; 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, {}); + } + 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); diff --git a/app/lib/src/graph/tree_canvas.dart b/app/lib/src/graph/tree_canvas.dart index 4502f18..9dd5249 100644 --- a/app/lib/src/graph/tree_canvas.dart +++ b/app/lib/src/graph/tree_canvas.dart @@ -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 = []; @@ -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 _hubBranches(GraphModel g, int maxPerHub, int maxLoose) { + final branches = []; + final members = g.hubMembers; + final nested = {for (final m in members.values) ...m}; + final expanded = {}; + 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 {}; + // 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 = {}; 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 _walk(TreeItem t) sync* { yield t; for (final c in t.children) { @@ -105,10 +206,18 @@ Iterable _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 { - 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 { 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 { ); _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 { 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 { }, ); } + + 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 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; } diff --git a/app/lib/src/state/app_state.dart b/app/lib/src/state/app_state.dart index 5f06816..8eb7f6a 100644 --- a/app/lib/src/state/app_state.dart +++ b/app/lib/src/state/app_state.dart @@ -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 = []; final _forward = []; - ThemeMode themeMode = ThemeMode.system; final List 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 = {}; + + /// 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 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'); } } diff --git a/app/lib/src/state/keymap.dart b/app/lib/src/state/keymap.dart new file mode 100644 index 0000000..004a119 --- /dev/null +++ b/app/lib/src/state/keymap.dart @@ -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+`: 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 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 = {}; + + 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 toJson() => { + for (final e in _custom.entries) e.key.name: e.value.encode(), + }; +} diff --git a/app/lib/src/state/settings.dart b/app/lib/src/state/settings.dart new file mode 100644 index 0000000..cbb116c --- /dev/null +++ b/app/lib/src/state/settings.dart @@ -0,0 +1,42 @@ +import 'dart:convert'; +import 'dart:io'; + +/// Where user preferences (theme, key bindings) are kept between runs. +abstract class SettingsStore { + Map load(); + void save(Map data); +} + +/// Keeps nothing (tests, previews). +class MemorySettings implements SettingsStore { + Map data = {}; + + @override + Map load() => data; + + @override + void save(Map 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 load() { + try { + final v = jsonDecode(File(path).readAsStringSync()); + return v is Map ? v : {}; + } catch (_) { + return {}; + } + } + + @override + void save(Map data) { + try { + File(path).writeAsStringSync(jsonEncode(data)); + } catch (_) {} + } +} diff --git a/app/lib/src/theme/theme.dart b/app/lib/src/theme/theme.dart index 24dc17f..a994cf7 100644 --- a/app/lib/src/theme/theme.dart +++ b/app/lib/src/theme/theme.dart @@ -70,6 +70,52 @@ class SynapseColors extends ThemeExtension { 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()!; } -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, diff --git a/app/lib/src/views/all_pages_view.dart b/app/lib/src/views/all_pages_view.dart index 3cea414..ff1b128 100644 --- a/app/lib/src/views/all_pages_view.dart +++ b/app/lib/src/views/all_pages_view.dart @@ -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 { final _pages = []; - bool _loading = false; - bool _done = false; + PageSort _sort = PageSort.edited; + bool _ascending = false; @override void initState() { super.initState(); - _more(); + _load(); } - Future _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 _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 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 _cleanUp() async { + final app = AppScope.read(context); + final candidates = await app.backend.legacyCandidates(); + if (!mounted) return; + final removed = await showDialog>( + 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( - 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( + 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 candidates; + + @override + State createState() => _CleanupDialogState(); +} + +class _CleanupDialogState extends State { + late final Set _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})'), + ), + ], + ); + } +} diff --git a/app/lib/src/views/convert_dialog.dart b/app/lib/src/views/convert_dialog.dart new file mode 100644 index 0000000..0c4db9b --- /dev/null +++ b/app/lib/src/views/convert_dialog.dart @@ -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 createState() => _ConvertToHubDialogState(); +} + +class _ConvertToHubDialogState extends State { + HubPreviewDto? _preview; + final _title = TextEditingController(); + final _description = TextEditingController(); + final _noteTitle = TextEditingController(); + final _checked = {}; + 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 _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 _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'), + ), + ], + ); + } +} diff --git a/app/lib/src/views/graph_view.dart b/app/lib/src/views/graph_view.dart index e74c3bc..6604388 100644 --- a/app/lib/src/views/graph_view.dart +++ b/app/lib/src/views/graph_view.dart @@ -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 createState() => _GraphViewState(); } +/// How the clusters mode groups pages. +enum ClusterBy { hubs, tags, communities } + class _GraphViewState extends State { 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 { } } + 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 { 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 { 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( + 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 { ), ); } - 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 { 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 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 { 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 { ), ), ), - 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), diff --git a/app/lib/src/views/hub_screen.dart b/app/lib/src/views/hub_screen.dart new file mode 100644 index 0000000..1279313 --- /dev/null +++ b/app/lib/src/views/hub_screen.dart @@ -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 aliases; + final PageStructure? structure; + final Map hubSizes; + + @override + State createState() => _HubScreenState(); +} + +class _HubScreenState extends State { + 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 _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 _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 _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 []; + 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 _menu(Offset at) async { + final r = await showMenu( + 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, + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/app/lib/src/views/hubs_tree.dart b/app/lib/src/views/hubs_tree.dart new file mode 100644 index 0000000..143a1f2 --- /dev/null +++ b/app/lib/src/views/hubs_tree.dart @@ -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 createState() => _HubsSectionState(); +} + +class _HubsSectionState extends State { + HubsDto? _data; + Map _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 _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 _create() async { + final app = AppScope.read(context); + final hub = await showNameDialog( + 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 out, + HubDto hub, + int depth, + Set path, + Set 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 = []; + for (final id in data?.roots ?? const []) { + 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, + ), + ), + ), + ], + ), + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/app/lib/src/views/page_screen.dart b/app/lib/src/views/page_screen.dart index 84cf3ba..5f765dd 100644 --- a/app/lib/src/views/page_screen.dart +++ b/app/lib/src/views/page_screen.dart @@ -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 { OutlineController? _outline; List? _backlinks; List? _related; + PageStructure? _structure; + Map _hubSizes = const {}; Object? _error; @override @@ -69,6 +75,8 @@ class _PageScreenState extends State { 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 { } } + /// Hub and namespace context of the page (not shown for journals). + Future _loadStructure() async { + final app = AppScope.read(context); + final id = _view!.page.id; + try { + final st = await app.backend.pageStructure(id); + var sizes = const {}; + 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 { } 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 { 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 { ), ], ); - if (!wide) return scroll; + if (!side) return scroll; return Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -154,8 +199,9 @@ class _PageScreenState extends State { } 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 createState() => TitleFieldState(); } -class _TitleFieldState extends State<_TitleField> { +class TitleFieldState extends State { 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 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 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 _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 _toHub(BuildContext context) async { + final app = AppScope.read(context); + final ok = await showDialog( + context: context, + builder: (_) => ConvertToHubDialog(page: page), + ); + if (ok == true) { + app.recent.removeWhere((p) => p.id == page.id); + app.replaceWithId(page.id, page.title); + } + } + + Future _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( + 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, + ), + ), + ), + ], + ), + ), + ), + ), + ], + ), + ], + ), + ); + } +} diff --git a/app/lib/src/views/settings_view.dart b/app/lib/src/views/settings_view.dart new file mode 100644 index 0000000..01cf608 --- /dev/null +++ b/app/lib/src/views/settings_view.dart @@ -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 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), + ), + ], + ), + ), + ); + } +} diff --git a/app/lib/src/views/shell.dart b/app/lib/src/views/shell.dart index 08a1cc0..4507c9e 100644 --- a/app/lib/src/views/shell.dart +++ b/app/lib/src/views/shell.dart @@ -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 { ); }); } + final actions = { + 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 { 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> 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, + ), +]; diff --git a/app/lib/src/widgets/pickers.dart b/app/lib/src/widgets/pickers.dart new file mode 100644 index 0000000..891624f --- /dev/null +++ b/app/lib/src/widgets/pickers.dart @@ -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 showPagePicker( + BuildContext context, { + required String heading, + required Future> Function(String query) search, + bool canCreateNote = false, + bool canCreateHub = false, +}) => showDialog( + 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> Function(String) search; + final bool canCreateNote; + final bool canCreateHub; + + @override + State<_PagePicker> createState() => _PagePickerState(); +} + +class _PagePickerState extends State<_PagePicker> { + final _text = TextEditingController(); + List _items = const []; + int _seq = 0; + + @override + void initState() { + super.initState(); + _query(''); + } + + @override + void dispose() { + _text.dispose(); + super.dispose(); + } + + Future _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 showNameDialog( + BuildContext context, { + required String heading, + required String confirm, + required Future Function(String name) submit, + String hint = 'Title', +}) => showDialog( + context: context, + builder: (_) => _NameDialog( + heading: heading, + confirm: confirm, + submit: submit, + hint: hint, + ), +); + +class _NameDialog 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 Function(String) submit; + + @override + State<_NameDialog> createState() => _NameDialogState(); +} + +class _NameDialogState extends State<_NameDialog> { + final _text = TextEditingController(); + String? _error; + bool _busy = false; + + @override + void dispose() { + _text.dispose(); + super.dispose(); + } + + Future _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(); +} diff --git a/app/lib/src/widgets/tags.dart b/app/lib/src/widgets/tags.dart new file mode 100644 index 0000000..ab8c333 --- /dev/null +++ b/app/lib/src/widgets/tags.dart @@ -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 _run( + BuildContext context, + Future 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 _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( + 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 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>( + future: app.backend.pagesWithTag(tag), + builder: (context, snap) { + final pages = snap.data ?? const []; + 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 showTagPages(BuildContext context, String tag) async { + final app = AppScope.read(context); + final pages = await app.backend.pagesWithTag(tag); + if (!context.mounted) return; + await showDialog( + 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 catalog; + final List 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'), + ), + ], + ); + } +} diff --git a/app/test/graph_view_test.dart b/app/test/graph_view_test.dart index c59362f..75ba43f 100644 --- a/app/test/graph_view_test.dart +++ b/app/test/graph_view_test.dart @@ -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(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 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() async => _data; } diff --git a/app/test/hubs_ui_test.dart b/app/test/hubs_ui_test.dart new file mode 100644 index 0000000..1b2a0f4 --- /dev/null +++ b/app/test/hubs_ui_test.dart @@ -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 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 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( + 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(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( + 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']); + }); +} diff --git a/app/test/settings_test.dart b/app/test/settings_test.dart new file mode 100644 index 0000000..a89255e --- /dev/null +++ b/app/test/settings_test.dart @@ -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 = {}; + 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']); + }); +} diff --git a/app/test/support/memory_backend.dart b/app/test/support/memory_backend.dart index e595669..d32d432 100644 --- a/app/test/support/memory_backend.dart +++ b/app/test/support/memory_backend.dart @@ -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 = {}; final outlines = >{}; final aliases = {}; @@ -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 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 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 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 = {}; + + /// Ids passed to `purgePages`, in call order. + final purged = []; + + /// Parent hubs of each page (membership lives on the member, like the core). + final hubsOfPage = >{}; + + /// 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? tags, + bool? isTag, + List? 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 _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 _linked(String id) { + final link = RegExp(r'\[\[([^\]]+)\]\]|(?:^|\s)#(\w+)'); + final out = []; + for (final n in outlines[id] ?? const []) { + 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? 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 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 _tagKey(String t) => t.trim().toLowerCase(); + + @override + Future setPageTags(String pageId, List tags) async { + final p = pages[pageId]!; + if (p.journalDate != null) throw Exception('Journals cannot have tags'); + final next = []; + 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 = []; + 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 setPageTypes(String pageId, List types) async { + final p = pages[pageId]!; + if (p.journalDate != null) throw Exception('Journals cannot have types'); + final next = []; + 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 addPageType(String pageId, String ty) => + setPageTypes(pageId, [...pages[pageId]!.types, ty]); + + @override + Future removePageType(String pageId, String ty) => + setPageTypes(pageId, [ + for (final t in pages[pageId]!.types) + if (_tagKey(t) != _tagKey(ty)) t, + ]); + + @override + Future> typeCatalog() async { + final used = {}; + 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 addPageTag(String pageId, String tag) => + setPageTags(pageId, [...pages[pageId]!.tags, tag]); + + @override + Future removePageTag(String pageId, String tag) => + setPageTags(pageId, [ + for (final t in pages[pageId]!.tags) + if (_tagKey(t) != _tagKey(tag)) t, + ]); + + @override + Future> 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> pagesWithTag(String tag) async => [ + for (final p in pages.values) + if (p.tags.any((t) => _tagKey(t) == _tagKey(tag))) _brief(p), + ]; + + @override + Future 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 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 setHubDescription(String hubId, String description) async { + if (!_isHub(hubId)) throw Exception('Not a hub'); + _put(pages[hubId]!, description: description); + return pages[hubId]!; + } + + @override + Future 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 removeFromHub(String pageId, String hubId) async { + hubsOfPage[pageId]?.remove(hubId); + } + + @override + Future 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 []; + 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 []).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 convertToHub( + String pageId, + String title, + String description, + List 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 convertToNote(String pageId) async { + final p = pages[pageId]!; + if (!p.isHub) throw Exception('Not a hub'); + final members = _members(pageId); + final l = []; + 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 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 = {}; + var frontier = roots; + for (var d = 0; frontier.isNotEmpty; d++) { + final next = []; + 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 _home(HubsDto h) { + final byId = {for (final x in h.hubs) x.id: x}; + final home = {}; + 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 {}) + 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(String pageId) async { + final p = pages[pageId]!; + final parts = p.title.split('/'); + final path = []; + 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 {}) + 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> 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 purgePages(List 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() async { @@ -288,6 +859,13 @@ class MemoryBackend implements GraphBackend { final s = [], t = [], k = []; 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); + } +} diff --git a/docs/app.md b/docs/app.md index 08c30c0..553ef1a 100644 --- a/docs/app.md +++ b/docs/app.md @@ -33,7 +33,7 @@ flutter build linux --release # build/linux/x64/release/bundle/ flutter run -d # 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+`. + +## 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 diff --git a/docs/architecture.md b/docs/architecture.md index cfa3f82..15b9722 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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` (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` (`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 diff --git a/docs/history.md b/docs/history.md index 0656be2..d7813ee 100644 --- a/docs/history.md +++ b/docs/history.md @@ -12,6 +12,10 @@ works on it (`git --git-dir=/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/`. diff --git a/docs/import.md b/docs/import.md index 6eb1148..04fa4e3 100644 --- a/docs/import.md +++ b/docs/import.md @@ -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 -- [--skip-existing]`. +CLI: `cargo run --release -p synapse-import --example import -- [--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 -- ` 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.