mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 15:26:17 +00:00
feat(app): hubs, types and tags UI, themes, key bindings and slash commands
Settings screen (themes incl. Sweet, rebindable shortcuts), rich text escapes, page sidebar with the local graph, sortable All pages, tree view changes and the Type/Tags rows in the page header. Docs updated. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e18fd2c27e
commit
88ef4a97a5
32 files changed
+5431
-375
No files matched your search
+25
-10
@@ -2,19 +2,24 @@ import 'package:flutter/material.dart';
|
||||
|
||||
import 'backend/graph_backend.dart';
|
||||
import 'state/app_state.dart';
|
||||
import 'state/settings.dart';
|
||||
import 'theme/theme.dart';
|
||||
import 'views/shell.dart';
|
||||
|
||||
class SynapseApp extends StatefulWidget {
|
||||
const SynapseApp({super.key, required this.backend});
|
||||
const SynapseApp({super.key, required this.backend, this.settings});
|
||||
final GraphBackend backend;
|
||||
final SettingsStore? settings;
|
||||
|
||||
@override
|
||||
State<SynapseApp> createState() => _SynapseAppState();
|
||||
}
|
||||
|
||||
class _SynapseAppState extends State<SynapseApp> {
|
||||
late final AppState _state = AppState(widget.backend)..loadRecent();
|
||||
late final AppState _state = AppState(
|
||||
widget.backend,
|
||||
settings: widget.settings,
|
||||
)..loadRecent();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
@@ -28,14 +33,24 @@ class _SynapseAppState extends State<SynapseApp> {
|
||||
state: _state,
|
||||
child: ListenableBuilder(
|
||||
listenable: _state,
|
||||
builder: (context, _) => MaterialApp(
|
||||
title: 'Synapse',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: buildTheme(Brightness.light),
|
||||
darkTheme: buildTheme(Brightness.dark),
|
||||
themeMode: _state.themeMode,
|
||||
home: const Shell(),
|
||||
),
|
||||
builder: (context, _) {
|
||||
final t = themeById(_state.themeId);
|
||||
final built = t == null
|
||||
? null
|
||||
: buildTheme(t.brightness, colors: t.colors);
|
||||
return MaterialApp(
|
||||
title: 'Synapse',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: built ?? buildTheme(Brightness.light),
|
||||
darkTheme: built ?? buildTheme(Brightness.dark),
|
||||
themeMode: t == null
|
||||
? ThemeMode.system
|
||||
: (t.brightness == Brightness.dark
|
||||
? ThemeMode.dark
|
||||
: ThemeMode.light),
|
||||
home: const Shell(),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,9 @@ export '../rust/api/dto.dart';
|
||||
/// in-memory implementation. Keeping the UI on this interface (instead of the generated
|
||||
/// opaque class) is what makes the editor testable without the native library.
|
||||
abstract class GraphBackend {
|
||||
/// Name of the notes store (shown at the centre of the tree view).
|
||||
String get graphName;
|
||||
|
||||
/// Today's date in the graph clock, `YYYY-MM-DD`.
|
||||
String today();
|
||||
|
||||
@@ -54,6 +57,52 @@ abstract class GraphBackend {
|
||||
String? assetPath(String hash);
|
||||
Future<AssetDto> putAssetFile(String path, {String? mime});
|
||||
|
||||
/// Hub (folder) structure of the whole graph.
|
||||
Future<HubsDto> hubs();
|
||||
Future<PageStructure> pageStructure(String pageId);
|
||||
Future<PageDto> createHub(String title, String description);
|
||||
|
||||
/// Tags are pages of kind `tag` (topics); a page can have any number. Types are plain
|
||||
/// names saying what a page is.
|
||||
Future<PageDto> setPageTags(String pageId, List<String> tags);
|
||||
Future<PageDto> addPageTag(String pageId, String tag);
|
||||
Future<PageDto> removePageTag(String pageId, String tag);
|
||||
|
||||
Future<PageDto> setPageTypes(String pageId, List<String> types);
|
||||
Future<PageDto> addPageType(String pageId, String type);
|
||||
Future<PageDto> removePageType(String pageId, String type);
|
||||
|
||||
/// Types in use (most used first), then the seeded suggestions not used yet.
|
||||
Future<List<TagDto>> typeCatalog();
|
||||
|
||||
/// Tag pages, most used first.
|
||||
Future<List<TagDto>> tagCatalog();
|
||||
Future<List<PageBrief>> pagesWithTag(String tag);
|
||||
|
||||
/// Id of the hub's template page (opens like a note; may be empty).
|
||||
Future<String> hubTemplate(String hubId);
|
||||
|
||||
/// Creates a note in the hub, starting from a copy of the hub's template.
|
||||
Future<PageDto> createPageFromTemplate(String hubId, String title);
|
||||
Future<PageDto> setHubDescription(String hubId, String description);
|
||||
|
||||
/// Membership is stored on the member: it lists the hub among its parents.
|
||||
Future<void> addToHub(String pageId, String hubId);
|
||||
Future<void> removeFromHub(String pageId, String hubId);
|
||||
Future<HubPreviewDto> hubConversionPreview(String pageId);
|
||||
Future<PageDto> convertToHub(
|
||||
String pageId,
|
||||
String title,
|
||||
String description,
|
||||
List<String> memberIds, {
|
||||
String? keepOutlineAs,
|
||||
});
|
||||
Future<PageDto> convertToNote(String pageId);
|
||||
|
||||
/// Logseq leftovers that can be removed, and their removal. Returns the number deleted.
|
||||
Future<List<LegacyCandidate>> legacyCandidates();
|
||||
Future<int> purgePages(List<String> ids);
|
||||
|
||||
/// The whole page-level graph (cached by the core until the graph changes).
|
||||
Future<GraphData> graphData();
|
||||
|
||||
@@ -89,12 +138,20 @@ class _FfiLayout implements LayoutEngine {
|
||||
}
|
||||
|
||||
class FfiGraphBackend implements GraphBackend {
|
||||
FfiGraphBackend(this._g);
|
||||
FfiGraphBackend(this._g, this.graphName);
|
||||
|
||||
final SynapseGraph _g;
|
||||
|
||||
static Future<FfiGraphBackend> open(String dir) async =>
|
||||
FfiGraphBackend(await SynapseGraph.open(dir: dir));
|
||||
@override
|
||||
final String graphName;
|
||||
|
||||
static Future<FfiGraphBackend> open(String dir) async {
|
||||
final parts = dir.split(RegExp(r'[\\/]')).where((p) => p.isNotEmpty);
|
||||
return FfiGraphBackend(
|
||||
await SynapseGraph.open(dir: dir),
|
||||
parts.isEmpty ? 'Graph' : parts.last,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String today() => _g.today();
|
||||
@@ -183,6 +240,81 @@ class FfiGraphBackend implements GraphBackend {
|
||||
Future<AssetDto> putAssetFile(String path, {String? mime}) =>
|
||||
_g.putAssetFile(path: path, mime: mime);
|
||||
|
||||
@override
|
||||
Future<HubsDto> hubs() => _g.hubs();
|
||||
@override
|
||||
Future<PageStructure> pageStructure(String pageId) =>
|
||||
_g.pageStructure(pageId: pageId);
|
||||
@override
|
||||
Future<PageDto> setPageTags(String pageId, List<String> tags) =>
|
||||
_g.setPageTags(pageId: pageId, tags: tags);
|
||||
@override
|
||||
Future<PageDto> addPageTag(String pageId, String tag) =>
|
||||
_g.addPageTag(pageId: pageId, tag: tag);
|
||||
@override
|
||||
Future<PageDto> removePageTag(String pageId, String tag) =>
|
||||
_g.removePageTag(pageId: pageId, tag: tag);
|
||||
@override
|
||||
Future<PageDto> setPageTypes(String pageId, List<String> types) =>
|
||||
_g.setPageTypes(pageId: pageId, types: types);
|
||||
@override
|
||||
Future<PageDto> addPageType(String pageId, String type) =>
|
||||
_g.addPageType(pageId: pageId, ty: type);
|
||||
@override
|
||||
Future<PageDto> removePageType(String pageId, String type) =>
|
||||
_g.removePageType(pageId: pageId, ty: type);
|
||||
@override
|
||||
Future<List<TagDto>> typeCatalog() => _g.typeCatalog();
|
||||
|
||||
@override
|
||||
Future<List<TagDto>> tagCatalog() => _g.tagCatalog();
|
||||
@override
|
||||
Future<List<PageBrief>> pagesWithTag(String tag) => _g.pagesWithTag(tag: tag);
|
||||
|
||||
@override
|
||||
Future<String> hubTemplate(String hubId) => _g.hubTemplate(hubId: hubId);
|
||||
|
||||
@override
|
||||
Future<PageDto> createPageFromTemplate(String hubId, String title) =>
|
||||
_g.createPageFromTemplate(hubId: hubId, title: title);
|
||||
|
||||
@override
|
||||
Future<PageDto> createHub(String title, String description) =>
|
||||
_g.createHub(title: title, description: description);
|
||||
@override
|
||||
Future<PageDto> setHubDescription(String hubId, String description) =>
|
||||
_g.setHubDescription(hubId: hubId, description: description);
|
||||
@override
|
||||
Future<void> addToHub(String pageId, String hubId) =>
|
||||
_g.addToHub(pageId: pageId, hubId: hubId);
|
||||
@override
|
||||
Future<void> removeFromHub(String pageId, String hubId) =>
|
||||
_g.removeFromHub(pageId: pageId, hubId: hubId);
|
||||
@override
|
||||
Future<HubPreviewDto> hubConversionPreview(String pageId) =>
|
||||
_g.hubConversionPreview(pageId: pageId);
|
||||
@override
|
||||
Future<PageDto> convertToHub(
|
||||
String pageId,
|
||||
String title,
|
||||
String description,
|
||||
List<String> memberIds, {
|
||||
String? keepOutlineAs,
|
||||
}) => _g.convertToHub(
|
||||
pageId: pageId,
|
||||
title: title,
|
||||
description: description,
|
||||
memberIds: memberIds,
|
||||
keepOutlineAs: keepOutlineAs,
|
||||
);
|
||||
@override
|
||||
Future<PageDto> convertToNote(String pageId) =>
|
||||
_g.convertToNote(pageId: pageId);
|
||||
@override
|
||||
Future<List<LegacyCandidate>> legacyCandidates() => _g.legacyCandidates();
|
||||
@override
|
||||
Future<int> purgePages(List<String> ids) => _g.purgePages(ids: ids);
|
||||
|
||||
@override
|
||||
Future<GraphData> graphData() => _g.graphData();
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import 'package:flutter/services.dart';
|
||||
|
||||
import '../backend/graph_backend.dart';
|
||||
import '../state/app_state.dart';
|
||||
import '../state/keymap.dart';
|
||||
import '../state/outline_controller.dart';
|
||||
import '../state/outline_ops.dart';
|
||||
import '../theme/theme.dart';
|
||||
@@ -512,6 +513,12 @@ class _BlockEditorState extends State<BlockEditor> {
|
||||
final seq = ++_searchSeq;
|
||||
final backend = c.backend;
|
||||
Future<List<CompletionItem>> search() async {
|
||||
if (q.kind == CompletionKind.command) {
|
||||
return [
|
||||
for (final cmd in matchCommands(q.query))
|
||||
CompletionItem('/${cmd.name}', cmd.name, detail: cmd.label),
|
||||
];
|
||||
}
|
||||
if (q.kind == CompletionKind.block) {
|
||||
final hits = await backend.searchBlocks(q.query, limit: 8);
|
||||
return [
|
||||
@@ -564,10 +571,35 @@ class _BlockEditorState extends State<BlockEditor> {
|
||||
final q = _query;
|
||||
if (q == null || i >= _items.length) return;
|
||||
final v = applyCompletion(_text.text, q, _items[i]);
|
||||
final again =
|
||||
q.kind == CompletionKind.command &&
|
||||
slashCommands.firstWhere((c) => c.name == _items[i].value).then;
|
||||
_closeCompletion();
|
||||
_text.value = v;
|
||||
_last = v;
|
||||
c.setText(n, v.text);
|
||||
// `/link` leaves the caret inside `[[]]`: go straight on to the page picker.
|
||||
if (again) _updateCompletion();
|
||||
}
|
||||
|
||||
/// Applies an editor formatting shortcut to the selection; false if `a` is not one.
|
||||
bool _format(AppAction a) {
|
||||
final (open, close) = switch (a) {
|
||||
AppAction.bold => ('**', '**'),
|
||||
AppAction.italic => ('*', '*'),
|
||||
AppAction.strike => ('~~', '~~'),
|
||||
AppAction.highlight => ('==', '=='),
|
||||
AppAction.code => ('`', '`'),
|
||||
AppAction.link => ('[[', ']]'),
|
||||
_ => ('', ''),
|
||||
};
|
||||
if (open.isEmpty) return false;
|
||||
final v = wrapSelection(_text.value, open, close);
|
||||
_text.value = v;
|
||||
_last = v;
|
||||
c.setText(n, v.text);
|
||||
_updateCompletion();
|
||||
return true;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- keys
|
||||
@@ -619,6 +651,14 @@ class _BlockEditorState extends State<BlockEditor> {
|
||||
final caret = sel.isValid ? sel.extentOffset : _text.text.length;
|
||||
final len = _text.text.length;
|
||||
|
||||
if (ctrl || alt) {
|
||||
final bound = AppScope.read(context).keymap.actionFor(
|
||||
Combo(key, ctrl: ctrl, shift: shift, alt: alt),
|
||||
editor: true,
|
||||
);
|
||||
if (bound != null && _format(bound)) return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
if (_completing) {
|
||||
if (key == LogicalKeyboardKey.arrowDown) {
|
||||
setState(() => _selected = (_selected + 1) % _items.length);
|
||||
@@ -842,6 +882,8 @@ class CompletionPopup extends StatelessWidget {
|
||||
? Icons.add_rounded
|
||||
: kind == CompletionKind.block
|
||||
? Icons.notes_rounded
|
||||
: kind == CompletionKind.command
|
||||
? Icons.bolt_rounded
|
||||
: kind == CompletionKind.tag
|
||||
? Icons.tag_rounded
|
||||
: Icons.description_outlined,
|
||||
|
||||
@@ -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', '', keywords: 'picture img'),
|
||||
SlashCommand('bold', 'Bold', '**|**', keywords: 'strong'),
|
||||
SlashCommand('italic', 'Italic', '*|*', keywords: 'emphasis'),
|
||||
SlashCommand('strike', 'Strikethrough', '~~|~~', keywords: 'delete'),
|
||||
SlashCommand('highlight', 'Highlight', '==|==', keywords: 'mark'),
|
||||
SlashCommand('code', 'Inline code', '`|`', keywords: 'mono'),
|
||||
SlashCommand('codeblock', 'Code block', '```\n|\n```', keywords: 'fence'),
|
||||
SlashCommand('h1', 'Heading 1', '# |', keywords: 'title'),
|
||||
SlashCommand('h2', 'Heading 2', '## |', keywords: 'title'),
|
||||
SlashCommand('h3', 'Heading 3', '### |', keywords: 'title'),
|
||||
SlashCommand('todo', 'Task', 'TODO |', keywords: 'task checkbox'),
|
||||
SlashCommand('quote', 'Quote', '> |', keywords: 'blockquote'),
|
||||
SlashCommand('divider', 'Divider', '---', keywords: 'rule line hr'),
|
||||
SlashCommand(
|
||||
'today',
|
||||
"Link to today's journal",
|
||||
'[[{today}]]',
|
||||
keywords: 'date',
|
||||
),
|
||||
SlashCommand('tag', 'Tag', '#|', keywords: 'hashtag', then: true),
|
||||
];
|
||||
|
||||
/// Commands matching `query` (name prefix first, then name/label/keyword substrings).
|
||||
List<SlashCommand> matchCommands(String query, {int limit = 8}) {
|
||||
final q = query.toLowerCase();
|
||||
final starts = <SlashCommand>[];
|
||||
final rest = <SlashCommand>[];
|
||||
for (final c in slashCommands) {
|
||||
if (c.name.startsWith(q)) {
|
||||
starts.add(c);
|
||||
} else if ('${c.label} ${c.keywords}'.toLowerCase().contains(q)) {
|
||||
rest.add(c);
|
||||
}
|
||||
}
|
||||
return [...starts, ...rest].take(limit).toList();
|
||||
}
|
||||
|
||||
/// Wraps the selection in `open`/`close` (or inserts the pair with the caret between). If the
|
||||
/// selection is already wrapped, unwraps it.
|
||||
TextEditingValue wrapSelection(TextEditingValue v, String open, String close) {
|
||||
final sel = v.selection;
|
||||
if (!sel.isValid) return v;
|
||||
final t = v.text;
|
||||
final inner = t.substring(sel.start, sel.end);
|
||||
if (!sel.isCollapsed &&
|
||||
sel.start >= open.length &&
|
||||
sel.end + close.length <= t.length &&
|
||||
t.substring(sel.start - open.length, sel.start) == open &&
|
||||
t.substring(sel.end, sel.end + close.length) == close) {
|
||||
return TextEditingValue(
|
||||
text:
|
||||
t.substring(0, sel.start - open.length) +
|
||||
inner +
|
||||
t.substring(sel.end + close.length),
|
||||
selection: TextSelection(
|
||||
baseOffset: sel.start - open.length,
|
||||
extentOffset: sel.end - open.length,
|
||||
),
|
||||
);
|
||||
}
|
||||
final text =
|
||||
t.substring(0, sel.start) + open + inner + close + t.substring(sel.end);
|
||||
return TextEditingValue(
|
||||
text: text,
|
||||
selection: sel.isCollapsed
|
||||
? TextSelection.collapsed(offset: sel.start + open.length)
|
||||
: TextSelection(
|
||||
baseOffset: sel.start + open.length,
|
||||
extentOffset: sel.end + open.length,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Finds the autocomplete trigger that the caret is in, if any.
|
||||
CompletionQuery? detectCompletion(String text, int caret) {
|
||||
if (caret < 0 || caret > text.length) return null;
|
||||
@@ -69,6 +184,15 @@ CompletionQuery? detectCompletion(String text, int caret) {
|
||||
),
|
||||
);
|
||||
}
|
||||
final slash = before.lastIndexOf('/');
|
||||
if (slash >= 0 && (slash == 0 || _ws(before[slash - 1]))) {
|
||||
final q = before.substring(slash + 1);
|
||||
if (!q.contains(RegExp(r'\s'))) {
|
||||
consider(
|
||||
CompletionQuery(CompletionKind.command, lineStart + slash + 1, q),
|
||||
);
|
||||
}
|
||||
}
|
||||
final hash = before.lastIndexOf('#');
|
||||
if (hash >= 0 && (hash == 0 || _ws(before[hash - 1]))) {
|
||||
final q = before.substring(hash + 1);
|
||||
@@ -98,6 +222,19 @@ TextEditingValue applyCompletion(
|
||||
final head = text.substring(0, q.start);
|
||||
var tail = text.substring(end);
|
||||
switch (q.kind) {
|
||||
case CompletionKind.command:
|
||||
final cmd = slashCommands.firstWhere((c) => c.name == item.value);
|
||||
final body = cmd.text();
|
||||
final at = body.indexOf('|');
|
||||
final clean = body.replaceFirst('|', '');
|
||||
// `head` still ends with the `/`.
|
||||
final before = head.substring(0, head.length - 1);
|
||||
return TextEditingValue(
|
||||
text: before + clean + tail,
|
||||
selection: TextSelection.collapsed(
|
||||
offset: before.length + (at < 0 ? clean.length : at),
|
||||
),
|
||||
);
|
||||
case CompletionKind.page:
|
||||
if (tail.startsWith(']]')) tail = tail.substring(2);
|
||||
final t = '$head${item.value}]]';
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -11,7 +11,9 @@ enum EdgeKind {
|
||||
blockRef('Block ref'),
|
||||
embed('Embed'),
|
||||
mention('Mention'),
|
||||
synapse('Synapse');
|
||||
synapse('Synapse'),
|
||||
contains('Contains'),
|
||||
tagged('Shared tag');
|
||||
|
||||
const EdgeKind(this.label);
|
||||
final String label;
|
||||
@@ -51,6 +53,123 @@ class GraphModel {
|
||||
|
||||
bool isJournal(int i) => node(i).journalDate != null;
|
||||
|
||||
bool isHub(int i) => node(i).isHub;
|
||||
|
||||
/// Whether the graph has any hub (folder-like page).
|
||||
late final bool hasHubs = data.nodes.any((n) => n.isHub);
|
||||
|
||||
/// Hubs that are the home hub of the most pages first (journals excluded); ties by index.
|
||||
/// A hub's position here is its colour rank in the hub grouping.
|
||||
late final List<int> hubOrder = () {
|
||||
final count = <int, int>{};
|
||||
for (var i = 0; i < nodeCount; i++) {
|
||||
final h = node(i).homeHub;
|
||||
if (h != null && !isJournal(i)) count[h] = (count[h] ?? 0) + 1;
|
||||
}
|
||||
return count.keys.toList()..sort((a, b) {
|
||||
final c = count[b]!.compareTo(count[a]!);
|
||||
return c != 0 ? c : a.compareTo(b);
|
||||
});
|
||||
}();
|
||||
|
||||
/// Hub node index → colour rank (see [hubOrder]).
|
||||
late final Map<int, int> hubRank = {
|
||||
for (var r = 0; r < hubOrder.length; r++) hubOrder[r]: r,
|
||||
};
|
||||
|
||||
/// Members of each hub: the targets of its `CONTAINS` edges (hub -> member), in edge order.
|
||||
late final Map<int, Set<int>> hubMembers = () {
|
||||
final m = <int, Set<int>>{};
|
||||
for (var e = 0; e < edgeCount; e++) {
|
||||
if (kind(e) != EdgeKind.contains) continue;
|
||||
final hub = source(e), page = target(e);
|
||||
if (hub == page) continue;
|
||||
(m[hub] ??= <int>{}).add(page);
|
||||
}
|
||||
return m;
|
||||
}();
|
||||
|
||||
/// Layout-only springs from every page in `nodes` to its home hub, so folders cluster.
|
||||
List<(int, int, double)> hubSprings(
|
||||
Iterable<int> nodes, {
|
||||
double strength = 0.6,
|
||||
}) => [
|
||||
for (final i in nodes)
|
||||
if (node(i).homeHub case final h? when h != i) (i, h, strength),
|
||||
];
|
||||
|
||||
/// The tag that groups page `i` in the "by tags" clusters: the page's most widely used tag
|
||||
/// (ties: alphabetical). Keys are lower-case; journals and untagged pages have none.
|
||||
String? homeTag(int i) {
|
||||
if (isJournal(i)) return null;
|
||||
String? best;
|
||||
for (final t in node(i).tags) {
|
||||
final k = t.toLowerCase();
|
||||
if (best == null ||
|
||||
_tagUse[k]! > _tagUse[best]! ||
|
||||
(_tagUse[k] == _tagUse[best] && k.compareTo(best) < 0)) {
|
||||
best = k;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// Pages per tag key and the first spelling met, over every non-journal page.
|
||||
late final Map<String, int> _tagUse = () {
|
||||
final m = <String, int>{};
|
||||
for (var i = 0; i < nodeCount; i++) {
|
||||
if (isJournal(i)) continue;
|
||||
for (final t in node(i).tags) {
|
||||
final k = t.toLowerCase();
|
||||
m[k] = (m[k] ?? 0) + 1;
|
||||
_tagName.putIfAbsent(k, () => t);
|
||||
}
|
||||
}
|
||||
return m;
|
||||
}();
|
||||
final _tagName = <String, String>{};
|
||||
|
||||
/// Tag keys that are the home tag of the most pages first; a tag's position is its colour
|
||||
/// rank in the tag grouping.
|
||||
late final List<String> tagGroups = () {
|
||||
final count = <String, int>{};
|
||||
for (var i = 0; i < nodeCount; i++) {
|
||||
final t = homeTag(i);
|
||||
if (t != null) count[t] = (count[t] ?? 0) + 1;
|
||||
}
|
||||
return count.keys.toList()..sort((a, b) {
|
||||
final c = count[b]!.compareTo(count[a]!);
|
||||
return c != 0 ? c : a.compareTo(b);
|
||||
});
|
||||
}();
|
||||
|
||||
late final Map<String, int> tagGroupRank = {
|
||||
for (var r = 0; r < tagGroups.length; r++) tagGroups[r]: r,
|
||||
};
|
||||
|
||||
/// Display name of a tag key.
|
||||
String tagLabel(String key) => _tagName[key] ?? key;
|
||||
|
||||
/// Layout-only springs from every page in `nodes` to the best connected page of its home
|
||||
/// tag, so pages sharing a tag cluster spatially.
|
||||
List<(int, int, double)> tagSprings(
|
||||
Iterable<int> nodes, {
|
||||
double strength = 0.6,
|
||||
}) {
|
||||
final anchor = <String, int>{};
|
||||
for (final i in nodes) {
|
||||
final t = homeTag(i);
|
||||
if (t == null) continue;
|
||||
final a = anchor[t];
|
||||
if (a == null || node(i).degree > node(a).degree) anchor[t] = i;
|
||||
}
|
||||
return [
|
||||
for (final i in nodes)
|
||||
if (homeTag(i) case final t? when anchor[t] != i)
|
||||
(i, anchor[t]!, strength),
|
||||
];
|
||||
}
|
||||
|
||||
/// Tag pages actually used as tags, most used first.
|
||||
late final List<int> tags = () {
|
||||
final count = <int, int>{};
|
||||
@@ -112,7 +231,7 @@ class GraphModel {
|
||||
/// Filters of the network modes.
|
||||
class GraphFilter {
|
||||
const GraphFilter({
|
||||
this.journals = false,
|
||||
this.journals = true,
|
||||
this.orphans = true,
|
||||
this.minDegree = 0,
|
||||
this.tag,
|
||||
@@ -126,6 +245,8 @@ class GraphFilter {
|
||||
EdgeKind.blockRef,
|
||||
EdgeKind.embed,
|
||||
EdgeKind.mention,
|
||||
EdgeKind.contains,
|
||||
EdgeKind.tagged,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import '../state/app_state.dart';
|
||||
import '../theme/theme.dart';
|
||||
import 'graph_model.dart';
|
||||
|
||||
enum ColorBy { cluster, tag, none }
|
||||
enum ColorBy { cluster, tag, hub, tagGroup, none }
|
||||
|
||||
/// Calm categorical palette (cluster / tag colours), tuned for each theme.
|
||||
List<Color> graphPalette(Brightness b) => b == Brightness.light
|
||||
@@ -119,6 +119,7 @@ class NetworkCanvasState extends State<NetworkCanvas>
|
||||
// Reused point buffers (no per-frame allocation or boxing).
|
||||
final _edgeBufs = <EdgeKind, _Buf>{};
|
||||
final _nodeBufs = <(int, int), _Buf>{};
|
||||
final _hubBufs = <int, _Buf>{};
|
||||
Float32List _meshPos = Float32List(0);
|
||||
Int32List _meshCol = Int32List(0);
|
||||
double _startScale = 1;
|
||||
@@ -189,6 +190,8 @@ class NetworkCanvasState extends State<NetworkCanvas>
|
||||
3.0,
|
||||
22.0,
|
||||
);
|
||||
// Hubs are a little larger; the painter adds a ring around them.
|
||||
if (n.isHub) _radius[k] = _radius[k] * 1.2 + 1.5;
|
||||
_colorIndex[k] = switch (widget.colorBy) {
|
||||
ColorBy.cluster => n.cluster < 10 ? n.cluster : -1,
|
||||
ColorBy.tag =>
|
||||
@@ -198,6 +201,18 @@ class NetworkCanvasState extends State<NetworkCanvas>
|
||||
final i = g.tags.indexOf(n.primaryTag!);
|
||||
return i < 10 ? i : -1;
|
||||
})(),
|
||||
ColorBy.hub =>
|
||||
n.homeHub == null
|
||||
? -1
|
||||
: (() {
|
||||
final r = g.hubRank[n.homeHub!] ?? -1;
|
||||
return r < 10 ? r : -1;
|
||||
})(),
|
||||
ColorBy.tagGroup => (() {
|
||||
final t = g.homeTag(sub.nodes[k]);
|
||||
final r = t == null ? -1 : (g.tagGroupRank[t] ?? -1);
|
||||
return r < 10 ? r : -1;
|
||||
})(),
|
||||
ColorBy.none => -1,
|
||||
};
|
||||
}
|
||||
@@ -451,6 +466,8 @@ class _NetworkPainter extends CustomPainter {
|
||||
|
||||
/// Laid-out labels per subgraph, invalidated when the text colour changes.
|
||||
static final _labels = Expando<(Color, Map<int, TextPainter>)>();
|
||||
static final _hullLabels = Expando<(Color, Map<int, TextPainter>)>();
|
||||
static const _ringWidth = 1.6;
|
||||
|
||||
Color _edgeColor(EdgeKind k) => switch (k) {
|
||||
EdgeKind.link => colors.muted,
|
||||
@@ -460,6 +477,8 @@ class _NetworkPainter extends CustomPainter {
|
||||
EdgeKind.embed => colors.ref,
|
||||
EdgeKind.mention => colors.faint,
|
||||
EdgeKind.synapse => palette[3],
|
||||
EdgeKind.contains => colors.ink,
|
||||
EdgeKind.tagged => palette[1],
|
||||
};
|
||||
|
||||
@override
|
||||
@@ -494,7 +513,9 @@ class _NetworkPainter extends CustomPainter {
|
||||
canvas.scale(scale);
|
||||
|
||||
// Cluster hulls.
|
||||
if (s.widget.hulls) _hulls(canvas, sub, pos, scale);
|
||||
final hullLabels = s.widget.hulls
|
||||
? _hulls(canvas, sub, pos, scale)
|
||||
: const <_HullLabel>[];
|
||||
|
||||
// Edges, batched by kind.
|
||||
final pulse = s._pulse.value;
|
||||
@@ -585,15 +606,35 @@ class _NetworkPainter extends CustomPainter {
|
||||
b.n = 0;
|
||||
}
|
||||
final journalColor = colors.faint;
|
||||
for (final b in s._hubBufs.values) {
|
||||
b.n = 0;
|
||||
}
|
||||
for (var k = 0; k < sub.length; k++) {
|
||||
if (!visible(k)) continue;
|
||||
final r = brain == null
|
||||
? s._radius[k]
|
||||
: 3 + 9 * (brain.activation[sub.nodes[k]] ?? 0);
|
||||
if (g.isHub(sub.nodes[k])) {
|
||||
s._hubBufs
|
||||
.putIfAbsent(((r + _ringWidth) * 2).round(), _Buf.new)
|
||||
.add2(pos[2 * k], pos[2 * k + 1]);
|
||||
}
|
||||
final ci = g.isJournal(sub.nodes[k]) ? -2 : s._colorIndex[k];
|
||||
final key = (ci, (r * 2).round());
|
||||
buckets.putIfAbsent(key, _Buf.new).add2(pos[2 * k], pos[2 * k + 1]);
|
||||
}
|
||||
// Hub rings: a slightly larger disc under the node (one call per size bucket).
|
||||
for (final MapEntry(key: d2, value: pts) in s._hubBufs.entries) {
|
||||
if (pts.n == 0) continue;
|
||||
canvas.drawRawPoints(
|
||||
ui.PointMode.points,
|
||||
pts.view,
|
||||
Paint()
|
||||
..color = colors.ink.withValues(alpha: dim ? 0.2 : 0.8)
|
||||
..strokeWidth = d2.toDouble()
|
||||
..strokeCap = StrokeCap.round,
|
||||
);
|
||||
}
|
||||
for (final MapEntry(key: (ci, d2), value: pts) in buckets.entries) {
|
||||
if (pts.n == 0) continue;
|
||||
var c = ci == -2 ? journalColor : (ci < 0 ? colors.muted : palette[ci]);
|
||||
@@ -656,6 +697,7 @@ class _NetworkPainter extends CustomPainter {
|
||||
}
|
||||
canvas.restore();
|
||||
|
||||
_paintHullLabels(canvas, size, sub, hullLabels);
|
||||
_paintLabels(canvas, size, sub, pos, highlight, focusLocal);
|
||||
}
|
||||
|
||||
@@ -748,18 +790,39 @@ class _NetworkPainter extends CustomPainter {
|
||||
}
|
||||
}
|
||||
|
||||
void _hulls(Canvas canvas, SubGraph sub, Float32List pos, double scale) {
|
||||
final byCluster = <int, List<Offset>>{};
|
||||
/// Draws the soft hulls (by hub when colouring by hub, else by community) and returns
|
||||
/// the labels to draw on screen afterwards.
|
||||
List<_HullLabel> _hulls(
|
||||
Canvas canvas,
|
||||
SubGraph sub,
|
||||
Float32List pos,
|
||||
double scale,
|
||||
) {
|
||||
final g = sub.model;
|
||||
final by = state.widget.colorBy;
|
||||
final byHub = by == ColorBy.hub;
|
||||
final byTag = by == ColorBy.tagGroup;
|
||||
final groups = <int, List<Offset>>{};
|
||||
for (var k = 0; k < sub.length; k++) {
|
||||
final c = sub.model.node(sub.nodes[k]).cluster;
|
||||
if (c >= 10) continue;
|
||||
byCluster
|
||||
.putIfAbsent(c, () => [])
|
||||
.add(Offset(pos[2 * k], pos[2 * k + 1]));
|
||||
final n = g.node(sub.nodes[k]);
|
||||
final int c;
|
||||
if (byHub) {
|
||||
final h = n.homeHub;
|
||||
c = h == null ? -1 : (g.hubRank[h] ?? -1);
|
||||
} else if (byTag) {
|
||||
final t = g.homeTag(sub.nodes[k]);
|
||||
c = t == null ? -1 : (g.tagGroupRank[t] ?? -1);
|
||||
} else {
|
||||
c = n.cluster;
|
||||
}
|
||||
if (c < 0 || c >= 10) continue;
|
||||
groups.putIfAbsent(c, () => []).add(Offset(pos[2 * k], pos[2 * k + 1]));
|
||||
}
|
||||
for (final MapEntry(key: c, value: pts) in byCluster.entries) {
|
||||
final labels = <_HullLabel>[];
|
||||
for (final MapEntry(key: c, value: pts) in groups.entries) {
|
||||
if (pts.length < 3) continue;
|
||||
final hull = convexHull(corePoints(pts));
|
||||
final core = corePoints(pts);
|
||||
final hull = convexHull(core);
|
||||
if (hull.length < 3) continue;
|
||||
final path = Path()..addPolygon(hull, true);
|
||||
final color = palette[c];
|
||||
@@ -777,6 +840,65 @@ class _NetworkPainter extends CustomPainter {
|
||||
..strokeWidth = 28 / scale
|
||||
..strokeJoin = StrokeJoin.round,
|
||||
);
|
||||
if (byHub || byTag) {
|
||||
var cx = 0.0, cy = 0.0, x0 = double.infinity, x1 = -double.infinity;
|
||||
for (final p in core) {
|
||||
cx += p.dx;
|
||||
cy += p.dy;
|
||||
x0 = math.min(x0, p.dx);
|
||||
x1 = math.max(x1, p.dx);
|
||||
}
|
||||
labels.add(
|
||||
_HullLabel(
|
||||
c,
|
||||
byHub ? g.node(g.hubOrder[c]).title : g.tagLabel(g.tagGroups[c]),
|
||||
Offset(cx / core.length, cy / core.length),
|
||||
(x1 - x0) * scale,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
return labels;
|
||||
}
|
||||
|
||||
/// Hub titles at the hull centroids, only when the hull is wide enough on screen.
|
||||
void _paintHullLabels(
|
||||
Canvas canvas,
|
||||
Size size,
|
||||
SubGraph sub,
|
||||
List<_HullLabel> labels,
|
||||
) {
|
||||
if (labels.isEmpty) return;
|
||||
final s = state;
|
||||
var entry = _hullLabels[sub];
|
||||
if (entry == null || entry.$1 != colors.muted) {
|
||||
entry = _hullLabels[sub] = (colors.muted, <int, TextPainter>{});
|
||||
}
|
||||
for (final l in labels) {
|
||||
if (l.screenWidth < 90) continue;
|
||||
final at = l.center * s._scale + s._offset;
|
||||
if (at.dx < -100 ||
|
||||
at.dy < -30 ||
|
||||
at.dx > size.width + 100 ||
|
||||
at.dy > size.height + 30) {
|
||||
continue;
|
||||
}
|
||||
final tp = entry.$2[l.group] ??= TextPainter(
|
||||
text: TextSpan(
|
||||
text: l.title,
|
||||
style: TextStyle(
|
||||
fontFamily: uiFont,
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: colors.muted,
|
||||
),
|
||||
),
|
||||
textDirection: TextDirection.ltr,
|
||||
maxLines: 1,
|
||||
ellipsis: '…',
|
||||
textScaler: textScaler,
|
||||
)..layout(maxWidth: 200);
|
||||
tp.paint(canvas, at - Offset(tp.width / 2, tp.height / 2));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -813,6 +935,7 @@ class _NetworkPainter extends CustomPainter {
|
||||
k == focus ||
|
||||
(brainAct != null && brainAct > 0.15) ||
|
||||
screenR >= (compact ? 7 : (sub.length > 200 ? 8.5 : 5.5)) ||
|
||||
(!compact && sub.model.isHub(sub.nodes[k]) && screenR >= 5) ||
|
||||
(sub.length <= 40 && !compact)) {
|
||||
candidates.add(k);
|
||||
}
|
||||
@@ -885,6 +1008,15 @@ class _NetworkPainter extends CustomPainter {
|
||||
old.colors != colors || !identical(old.state, state);
|
||||
}
|
||||
|
||||
/// A hub title to draw at a hull centroid (world position, screen width of the hull).
|
||||
class _HullLabel {
|
||||
const _HullLabel(this.group, this.title, this.center, this.screenWidth);
|
||||
final int group;
|
||||
final String title;
|
||||
final Offset center;
|
||||
final double screenWidth;
|
||||
}
|
||||
|
||||
/// Growable float buffer reused across frames.
|
||||
class _Buf {
|
||||
Float32List data = Float32List(256);
|
||||
|
||||
@@ -4,13 +4,15 @@ import 'package:flutter/material.dart';
|
||||
|
||||
import '../theme/theme.dart';
|
||||
import 'graph_model.dart';
|
||||
import 'network_canvas.dart';
|
||||
|
||||
/// A node of the namespace / tag tree.
|
||||
/// A node of the hub / namespace / tag tree.
|
||||
class TreeItem {
|
||||
TreeItem(this.label, {this.global});
|
||||
TreeItem(this.label, {this.global, this.isHub = false});
|
||||
final String label;
|
||||
|
||||
/// Drawn with the folder look.
|
||||
final bool isHub;
|
||||
|
||||
/// Page index when the item is a page.
|
||||
int? global;
|
||||
final children = <TreeItem>[];
|
||||
@@ -19,6 +21,12 @@ class TreeItem {
|
||||
double angle = 0;
|
||||
Offset pos = Offset.zero;
|
||||
|
||||
/// Colour-space position: centre hue (degrees) of this branch's sector and its width.
|
||||
/// Siblings split their parent's sector evenly, so they are equally far apart in hue.
|
||||
double hue = 0;
|
||||
double span = 360;
|
||||
int sibling = 0;
|
||||
|
||||
TreeItem child(String label) {
|
||||
for (final c in children) {
|
||||
if (c.label == label) return c;
|
||||
@@ -29,14 +37,75 @@ class TreeItem {
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a tree with two branches: namespaces (`a/b/c` titles split on `/`) and tags (each
|
||||
/// tag with the pages using it, most used tags first).
|
||||
/// Hub branches: root hubs (hubs that are no other hub's member) with their members,
|
||||
/// recursively, plus the notes that live in no hub (orphans included). A hub is expanded once (the first time it is reached) and never inside
|
||||
/// itself, so cycles and shared sub-hubs stay bounded; later occurrences are leaves.
|
||||
List<TreeItem> _hubBranches(GraphModel g, int maxPerHub, int maxLoose) {
|
||||
final branches = <TreeItem>[];
|
||||
final members = g.hubMembers;
|
||||
final nested = {for (final m in members.values) ...m};
|
||||
final expanded = <int>{};
|
||||
TreeItem build(int hub) {
|
||||
final item = TreeItem(g.node(hub).title, global: hub, isHub: true);
|
||||
if (!expanded.add(hub)) return item;
|
||||
var shown = 0;
|
||||
final all = members[hub] ?? const <int>{};
|
||||
// Sub-hubs are always listed; plain pages are capped.
|
||||
for (final m in all) {
|
||||
if (g.isHub(m)) {
|
||||
item.children.add(build(m));
|
||||
} else if (shown < maxPerHub) {
|
||||
shown++;
|
||||
item.children.add(TreeItem(g.node(m).title, global: m));
|
||||
}
|
||||
}
|
||||
final hidden = all.where((m) => !g.isHub(m)).length - shown;
|
||||
if (hidden > 0) item.children.add(TreeItem('… $hidden more'));
|
||||
return item;
|
||||
}
|
||||
|
||||
final hubs = [
|
||||
for (var i = 0; i < g.nodeCount; i++)
|
||||
if (g.isHub(i)) i,
|
||||
];
|
||||
for (final h in hubs) {
|
||||
if (!nested.contains(h)) branches.add(build(h));
|
||||
}
|
||||
// Hubs only reachable through a cycle still need a place.
|
||||
for (final h in hubs) {
|
||||
if (!expanded.contains(h)) branches.add(build(h));
|
||||
}
|
||||
// Notes under no container hang straight off the centre (namespaced ones keep their
|
||||
// namespace branch).
|
||||
final loose = [
|
||||
for (var i = 0; i < g.nodeCount; i++)
|
||||
if (!g.isHub(i) &&
|
||||
!g.isJournal(i) &&
|
||||
!nested.contains(i) &&
|
||||
!g.node(i).title.contains('/'))
|
||||
i,
|
||||
];
|
||||
for (final i in loose.take(maxLoose)) {
|
||||
branches.add(TreeItem(g.node(i).title, global: i));
|
||||
}
|
||||
if (loose.length > maxLoose) {
|
||||
branches.add(TreeItem('… ${loose.length - maxLoose} more'));
|
||||
}
|
||||
return branches;
|
||||
}
|
||||
|
||||
/// Builds a tree from hubs (folders, straight off the centre, with loose notes), namespaces (`a/b/c` titles split on `/`, attached
|
||||
/// directly to the centre) and tags (each tag with the pages using it, most used tags first).
|
||||
TreeItem buildNamespaceTree(
|
||||
GraphModel g, {
|
||||
String name = 'Graph',
|
||||
int maxTags = 24,
|
||||
int maxPerTag = 30,
|
||||
int maxPerHub = 40,
|
||||
int maxLoose = 80,
|
||||
}) {
|
||||
final root = TreeItem('Graph');
|
||||
final root = TreeItem(name);
|
||||
root.children.addAll(_hubBranches(g, maxPerHub, maxLoose));
|
||||
final ns = TreeItem('Namespaces');
|
||||
final byTitle = <String, int>{};
|
||||
for (var i = 0; i < g.nodeCount; i++) {
|
||||
@@ -53,7 +122,8 @@ TreeItem buildNamespaceTree(
|
||||
at.global ??= byTitle[path];
|
||||
}
|
||||
}
|
||||
if (ns.children.isNotEmpty) root.children.add(ns);
|
||||
// No "Namespaces" node: top-level namespaces hang straight off the centre.
|
||||
root.children.addAll(ns.children);
|
||||
final tags = TreeItem('Tags');
|
||||
for (final tag in g.tags.take(maxTags)) {
|
||||
final item = TreeItem('#${g.node(tag).title}', global: tag);
|
||||
@@ -68,11 +138,32 @@ TreeItem buildNamespaceTree(
|
||||
tags.children.add(item);
|
||||
}
|
||||
if (tags.children.isNotEmpty) root.children.add(tags);
|
||||
// With a single branch, that branch is the centre.
|
||||
final top = root.children.length == 1 ? root.children.single : root;
|
||||
_measure(top, 0);
|
||||
_place(top, 0, 2 * math.pi);
|
||||
return top;
|
||||
_measure(root, 0);
|
||||
_place(root, 0, 2 * math.pi);
|
||||
_colorize(root);
|
||||
return root;
|
||||
}
|
||||
|
||||
/// Gives every arm of `t` its own sector of the hue circle (the centre's arms share it all),
|
||||
/// and every sub-branch an equal slice of its parent's sector.
|
||||
void _colorize(TreeItem t) {
|
||||
final k = t.children.length;
|
||||
for (var j = 0; j < k; j++) {
|
||||
final c = t.children[j];
|
||||
c.span = t.span / k;
|
||||
c.hue = t.hue - t.span / 2 + (j + 0.5) * c.span;
|
||||
c.sibling = j;
|
||||
_colorize(c);
|
||||
}
|
||||
}
|
||||
|
||||
/// Branch colour: hue from the sector, alternating lightness so neighbours stay apart even
|
||||
/// when the slices get thin.
|
||||
Color treeColor(TreeItem t, Brightness b) {
|
||||
final dark = b == Brightness.dark;
|
||||
final l =
|
||||
(dark ? 0.66 : 0.48) + (t.sibling.isOdd ? (dark ? -0.08 : 0.08) : 0);
|
||||
return HSLColor.fromAHSL(1, (t.hue % 360 + 360) % 360, 0.62, l).toColor();
|
||||
}
|
||||
|
||||
int _measure(TreeItem t, int depth) {
|
||||
@@ -98,6 +189,16 @@ void _place(TreeItem t, double a0, double a1) {
|
||||
}
|
||||
}
|
||||
|
||||
void _shift(TreeItem t, Offset d) {
|
||||
for (final x in _walk(t)) {
|
||||
x.pos += d;
|
||||
}
|
||||
}
|
||||
|
||||
class _Tick extends ChangeNotifier {
|
||||
void bump() => notifyListeners();
|
||||
}
|
||||
|
||||
Iterable<TreeItem> _walk(TreeItem t) sync* {
|
||||
yield t;
|
||||
for (final c in t.children) {
|
||||
@@ -105,10 +206,18 @@ Iterable<TreeItem> _walk(TreeItem t) sync* {
|
||||
}
|
||||
}
|
||||
|
||||
/// Radial tree of namespaces and tags; pan/zoom with the GPU transform (no repaint).
|
||||
/// Radial tree of hubs, namespaces and tags; pan/zoom with the GPU transform (no repaint).
|
||||
class TreeCanvas extends StatefulWidget {
|
||||
const TreeCanvas({super.key, required this.model, required this.onTap});
|
||||
const TreeCanvas({
|
||||
super.key,
|
||||
required this.model,
|
||||
required this.onTap,
|
||||
this.name = 'Graph',
|
||||
});
|
||||
final GraphModel model;
|
||||
|
||||
/// Label of the centre: the name of the notes store.
|
||||
final String name;
|
||||
final void Function(int global) onTap;
|
||||
|
||||
@override
|
||||
@@ -116,21 +225,26 @@ class TreeCanvas extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _TreeCanvasState extends State<TreeCanvas> {
|
||||
late TreeItem _root = buildNamespaceTree(widget.model);
|
||||
late TreeItem _root = buildNamespaceTree(widget.model, name: widget.name);
|
||||
final _tick = _Tick();
|
||||
TreeItem? _drag;
|
||||
bool _pan = true;
|
||||
final _transform = TransformationController();
|
||||
bool _placed = false;
|
||||
|
||||
@override
|
||||
void didUpdateWidget(TreeCanvas oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (!identical(oldWidget.model, widget.model)) {
|
||||
_root = buildNamespaceTree(widget.model);
|
||||
if (!identical(oldWidget.model, widget.model) ||
|
||||
oldWidget.name != widget.name) {
|
||||
_root = buildNamespaceTree(widget.model, name: widget.name);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_transform.dispose();
|
||||
_tick.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -139,18 +253,36 @@ class _TreeCanvasState extends State<TreeCanvas> {
|
||||
return maxDepth * _ring + 170;
|
||||
}
|
||||
|
||||
/// Nodes can be dragged away from the rings, so the scene is larger than the layout.
|
||||
double get _half => _extent * 1.6;
|
||||
|
||||
TreeItem? _hit(Offset scene, double half) {
|
||||
final p = scene - Offset(half, half);
|
||||
TreeItem? best;
|
||||
var d = 12.0;
|
||||
for (final t in _walk(_root)) {
|
||||
final x = (t.pos - p).distance;
|
||||
if (x < d) {
|
||||
d = x;
|
||||
best = t;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = context.colors;
|
||||
if (_root.children.isEmpty) {
|
||||
return Center(
|
||||
child: Text(
|
||||
'No namespaces (a/b titles) or tags yet.',
|
||||
'No hubs, namespaces (a/b titles) or tags yet.',
|
||||
style: TextStyle(color: colors.muted),
|
||||
),
|
||||
);
|
||||
}
|
||||
final extent = _extent;
|
||||
final half = _half;
|
||||
return LayoutBuilder(
|
||||
builder: (context, box) {
|
||||
if (!_placed) {
|
||||
@@ -161,8 +293,8 @@ class _TreeCanvasState extends State<TreeCanvas> {
|
||||
);
|
||||
_transform.value = Matrix4.identity()
|
||||
..translateByDouble(
|
||||
box.maxWidth / 2 - extent * s,
|
||||
box.maxHeight / 2 - extent * s,
|
||||
box.maxWidth / 2 - half * s,
|
||||
box.maxHeight / 2 - half * s,
|
||||
0,
|
||||
1,
|
||||
)
|
||||
@@ -171,26 +303,41 @@ class _TreeCanvasState extends State<TreeCanvas> {
|
||||
return InteractiveViewer(
|
||||
transformationController: _transform,
|
||||
constrained: false,
|
||||
panEnabled: _pan,
|
||||
minScale: 0.05,
|
||||
maxScale: 6,
|
||||
boundaryMargin: const EdgeInsets.all(double.infinity),
|
||||
child: GestureDetector(
|
||||
onTapUp: (d) {
|
||||
final p = d.localPosition - Offset(extent, extent);
|
||||
for (final t in _walk(_root)) {
|
||||
if (t.global != null && (t.pos - p).distance < 10) {
|
||||
widget.onTap(t.global!);
|
||||
return;
|
||||
}
|
||||
child: Listener(
|
||||
// Dragging a node moves it with its whole branch; empty space pans the view.
|
||||
onPointerDown: (e) {
|
||||
final t = _hit(e.localPosition, half);
|
||||
if (t != null) {
|
||||
_drag = t;
|
||||
setState(() => _pan = false);
|
||||
}
|
||||
},
|
||||
child: CustomPaint(
|
||||
size: Size(2 * extent, 2 * extent),
|
||||
painter: _TreePainter(
|
||||
_root,
|
||||
extent,
|
||||
colors,
|
||||
graphPalette(Theme.of(context).brightness),
|
||||
onPointerMove: (e) {
|
||||
final t = _drag;
|
||||
if (t == null) return;
|
||||
_shift(t, e.delta / _transform.value.getMaxScaleOnAxis());
|
||||
_tick.bump();
|
||||
},
|
||||
onPointerUp: (_) => _release(),
|
||||
onPointerCancel: (_) => _release(),
|
||||
child: GestureDetector(
|
||||
onTapUp: (d) {
|
||||
final t = _hit(d.localPosition, half);
|
||||
if (t?.global != null) widget.onTap(t!.global!);
|
||||
},
|
||||
child: CustomPaint(
|
||||
size: Size(2 * half, 2 * half),
|
||||
painter: _TreePainter(
|
||||
_root,
|
||||
half,
|
||||
colors,
|
||||
Theme.of(context).brightness,
|
||||
_tick,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -198,29 +345,38 @@ class _TreeCanvasState extends State<TreeCanvas> {
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
void _release() {
|
||||
if (_drag == null) return;
|
||||
_drag = null;
|
||||
setState(() => _pan = true);
|
||||
}
|
||||
}
|
||||
|
||||
class _TreePainter extends CustomPainter {
|
||||
_TreePainter(this.root, this.extent, this.colors, this.palette);
|
||||
_TreePainter(
|
||||
this.root,
|
||||
this.extent,
|
||||
this.colors,
|
||||
this.brightness,
|
||||
Listenable tick,
|
||||
) : super(repaint: tick);
|
||||
final TreeItem root;
|
||||
final double extent;
|
||||
final SynapseColors colors;
|
||||
final List<Color> palette;
|
||||
final Brightness brightness;
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
canvas.translate(extent, extent);
|
||||
final link = Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.2
|
||||
..color = colors.line;
|
||||
..strokeWidth = 1.4;
|
||||
for (final t in _walk(root)) {
|
||||
for (final c in t.children) {
|
||||
// Curve from parent to child bending through the child's angle.
|
||||
final mid = Offset.fromDirection(
|
||||
c.angle,
|
||||
t.depth * _ring + _ring * 0.5,
|
||||
);
|
||||
// Curve from parent to child bending through the child's ray.
|
||||
final mid = c.pos - Offset.fromDirection(c.angle, _ring * 0.5);
|
||||
link.color = treeColor(c, brightness).withValues(alpha: 0.7);
|
||||
canvas.drawPath(
|
||||
Path()
|
||||
..moveTo(t.pos.dx, t.pos.dy)
|
||||
@@ -229,43 +385,80 @@ class _TreePainter extends CustomPainter {
|
||||
);
|
||||
}
|
||||
}
|
||||
var branch = 0;
|
||||
// Colour per first-level branch; with a single-branch tree each subtree gets its own.
|
||||
for (final b in root.children) {
|
||||
final color = palette[branch++ % palette.length];
|
||||
for (final t in _walk(b)) {
|
||||
final r = t.children.isEmpty ? 3.5 : 5.5;
|
||||
canvas.drawCircle(
|
||||
t.pos,
|
||||
r,
|
||||
Paint()..color = t.global == null ? colors.faint : color,
|
||||
);
|
||||
final tp = TextPainter(
|
||||
text: TextSpan(
|
||||
text: t.label,
|
||||
style: TextStyle(
|
||||
fontFamily: uiFont,
|
||||
fontSize: t.children.isEmpty ? 11 : 12.5,
|
||||
fontWeight: t.children.isEmpty
|
||||
? FontWeight.w400
|
||||
: FontWeight.w600,
|
||||
color: t.children.isEmpty ? colors.muted : colors.ink,
|
||||
),
|
||||
),
|
||||
textDirection: TextDirection.ltr,
|
||||
maxLines: 1,
|
||||
ellipsis: '…',
|
||||
)..layout(maxWidth: 150);
|
||||
// Labels outside the circle, left of the node on the left half.
|
||||
final left = math.cos(t.angle) < 0;
|
||||
final at = t.pos + Offset(left ? -tp.width - 8 : 8, -tp.height / 2);
|
||||
tp.paint(canvas, at);
|
||||
void node(TreeItem t, Color color) {
|
||||
final r = t.children.isEmpty ? 3.5 : 5.5;
|
||||
final fill = Paint()
|
||||
..color = t.global == null ? color.withValues(alpha: 0.55) : color;
|
||||
if (t.isHub) {
|
||||
_folder(canvas, t.pos, fill);
|
||||
} else {
|
||||
canvas.drawCircle(t.pos, r, fill);
|
||||
}
|
||||
final tp = TextPainter(
|
||||
text: TextSpan(
|
||||
text: t.label,
|
||||
style: TextStyle(
|
||||
fontFamily: uiFont,
|
||||
fontSize: t.children.isEmpty ? 11 : 12.5,
|
||||
fontWeight: t.children.isEmpty ? FontWeight.w400 : FontWeight.w600,
|
||||
color: t.children.isEmpty ? colors.muted : colors.ink,
|
||||
),
|
||||
),
|
||||
textDirection: TextDirection.ltr,
|
||||
maxLines: 1,
|
||||
ellipsis: '…',
|
||||
)..layout(maxWidth: 150);
|
||||
// Labels outside the circle, left of the node on the left half.
|
||||
final left = math.cos(t.angle) < 0;
|
||||
tp.paint(
|
||||
canvas,
|
||||
t.pos + Offset(left ? -tp.width - 8 : 8, -tp.height / 2),
|
||||
);
|
||||
}
|
||||
canvas.drawCircle(Offset.zero, 7, Paint()..color = colors.accent);
|
||||
|
||||
for (final t in _walk(root).skip(1)) {
|
||||
node(t, treeColor(t, brightness));
|
||||
}
|
||||
// The centre carries the name of the notes store.
|
||||
final c = TextPainter(
|
||||
text: TextSpan(
|
||||
text: root.label,
|
||||
style: TextStyle(
|
||||
fontFamily: uiFont,
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: colors.ink,
|
||||
),
|
||||
),
|
||||
textDirection: TextDirection.ltr,
|
||||
maxLines: 1,
|
||||
ellipsis: '…',
|
||||
)..layout(maxWidth: 180);
|
||||
c.paint(canvas, root.pos + Offset(-c.width / 2, -c.height - 12));
|
||||
canvas.drawCircle(root.pos, 7, Paint()..color = colors.accent);
|
||||
}
|
||||
|
||||
/// Small folder glyph (body plus tab) centred on `c`.
|
||||
void _folder(Canvas canvas, Offset c, Paint paint) {
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(
|
||||
Rect.fromCenter(center: c.translate(0, 1), width: 13, height: 9),
|
||||
const Radius.circular(2),
|
||||
),
|
||||
paint,
|
||||
);
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(
|
||||
Rect.fromLTWH(c.dx - 6.5, c.dy - 5, 6, 3),
|
||||
const Radius.circular(1.2),
|
||||
),
|
||||
paint,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(_TreePainter old) =>
|
||||
!identical(old.root, root) || old.colors != colors;
|
||||
!identical(old.root, root) ||
|
||||
old.colors != colors ||
|
||||
old.brightness != brightness;
|
||||
}
|
||||
@@ -2,6 +2,9 @@ import 'package:flutter/material.dart';
|
||||
|
||||
import '../backend/graph_backend.dart';
|
||||
import '../graph/network_canvas.dart';
|
||||
import '../theme/theme.dart';
|
||||
import 'keymap.dart';
|
||||
import 'settings.dart';
|
||||
import 'write_queue.dart';
|
||||
|
||||
sealed class AppRoute {
|
||||
@@ -20,12 +23,15 @@ class AllPagesRoute extends AppRoute {
|
||||
const AllPagesRoute();
|
||||
}
|
||||
|
||||
class SettingsRoute extends AppRoute {
|
||||
const SettingsRoute();
|
||||
}
|
||||
|
||||
enum GraphMode {
|
||||
network('Network', Icons.hub_outlined),
|
||||
local('Local', Icons.adjust_rounded),
|
||||
brain('Synapses', Icons.bolt_outlined),
|
||||
clusters('Clusters', Icons.bubble_chart_outlined),
|
||||
tree('Namespaces', Icons.account_tree_outlined),
|
||||
tree('Tree', Icons.account_tree_outlined),
|
||||
timeline('Timeline', Icons.timeline_rounded);
|
||||
|
||||
const GraphMode(this.label, this.icon);
|
||||
@@ -54,10 +60,56 @@ class PageTarget extends AppRoute {
|
||||
/// page, so a framework (Riverpod, Bloc) would add a dependency and indirection without
|
||||
/// paying for itself; rebuilds are scoped with `ListenableBuilder`.
|
||||
class AppState extends ChangeNotifier {
|
||||
AppState(this.backend, {WriteQueue? queue})
|
||||
AppState(this.backend, {WriteQueue? queue, SettingsStore? settings})
|
||||
: refs = BlockRefCache(backend),
|
||||
queue = queue ?? WriteQueue() {
|
||||
queue = queue ?? WriteQueue(),
|
||||
_settings = settings ?? MemorySettings() {
|
||||
this.queue.onError = _writeFailed;
|
||||
final saved = _settings.load();
|
||||
final id = saved['theme'];
|
||||
if (id is String && (id == autoThemeId || themeById(id) != null)) {
|
||||
themeId = id;
|
||||
}
|
||||
final keys = saved['keys'];
|
||||
keymap = Keymap(
|
||||
keys is Map
|
||||
? {for (final e in keys.entries) '${e.key}': '${e.value}'}
|
||||
: {},
|
||||
);
|
||||
}
|
||||
|
||||
final SettingsStore _settings;
|
||||
|
||||
/// Key bindings (defaults plus the user's overrides).
|
||||
late final Keymap keymap;
|
||||
|
||||
/// Selected theme id (`auto` follows the system).
|
||||
String themeId = autoThemeId;
|
||||
|
||||
void _saveSettings() {
|
||||
_settings.save({'theme': themeId, 'keys': keymap.toJson()});
|
||||
}
|
||||
|
||||
void setTheme(String id) {
|
||||
themeId = id;
|
||||
_saveSettings();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Binds `combo` to `action`; returns the action already using it (nothing changes then).
|
||||
AppAction? bindKey(AppAction action, Combo combo) {
|
||||
final owner = keymap.bind(action, combo);
|
||||
if (owner == null) {
|
||||
_saveSettings();
|
||||
notifyListeners();
|
||||
}
|
||||
return owner;
|
||||
}
|
||||
|
||||
void resetKey(AppAction? action) {
|
||||
action == null ? keymap.resetAll() : keymap.reset(action);
|
||||
_saveSettings();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
final GraphBackend backend;
|
||||
@@ -67,7 +119,6 @@ class AppState extends ChangeNotifier {
|
||||
AppRoute _route = const JournalsRoute();
|
||||
final _back = <AppRoute>[];
|
||||
final _forward = <AppRoute>[];
|
||||
ThemeMode themeMode = ThemeMode.system;
|
||||
final List<PageBrief> recent = [];
|
||||
|
||||
/// Node positions shared by the graph views (stable layouts across modes and filters).
|
||||
@@ -79,6 +130,17 @@ class AppState extends ChangeNotifier {
|
||||
/// Bumped to make the current view reload from the core (failed writes, renames).
|
||||
int generation = 0;
|
||||
|
||||
/// Hubs expanded in the sidebar tree (kept here so it survives sidebar rebuilds).
|
||||
final expandedHubs = <String>{};
|
||||
|
||||
/// Right sidebar of the page editor (local graph + related pages); collapsed by default.
|
||||
bool pageSidebar = false;
|
||||
|
||||
void togglePageSidebar() {
|
||||
pageSidebar = !pageSidebar;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Last write error, shown once by the shell.
|
||||
String? writeError;
|
||||
|
||||
@@ -107,6 +169,25 @@ class AppState extends ChangeNotifier {
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Points the current route and any history entry that opens `oldTitle` at the page `id`,
|
||||
/// without pushing history (the page was renamed or converted, so its old title no longer
|
||||
/// exists and opening it would create an empty duplicate).
|
||||
void replaceWithId(String id, String oldTitle) {
|
||||
final key = oldTitle.toLowerCase();
|
||||
AppRoute fix(AppRoute r) =>
|
||||
r is PageTarget && r.id == null && r.title!.toLowerCase() == key
|
||||
? PageTarget(id: id)
|
||||
: r;
|
||||
if (_route is PageTarget) _route = PageTarget(id: id);
|
||||
for (final l in [_back, _forward]) {
|
||||
for (var i = 0; i < l.length; i++) {
|
||||
l[i] = fix(l[i]);
|
||||
}
|
||||
}
|
||||
generation++;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void back() {
|
||||
if (_back.isEmpty) return;
|
||||
_forward.add(_route);
|
||||
@@ -132,15 +213,19 @@ class AppState extends ChangeNotifier {
|
||||
queue.run(() => backend.recordVisit(from, page.id)).ignore();
|
||||
}
|
||||
recent.removeWhere((p) => p.id == page.id);
|
||||
recent.insert(
|
||||
0,
|
||||
PageBrief(
|
||||
id: page.id,
|
||||
title: page.title,
|
||||
isJournal: page.journalDate != null,
|
||||
),
|
||||
);
|
||||
if (recent.length > 12) recent.removeLast();
|
||||
// Hubs are folders, not pages: they never show up in recents.
|
||||
if (!page.isHub) {
|
||||
recent.insert(
|
||||
0,
|
||||
PageBrief(
|
||||
id: page.id,
|
||||
title: page.title,
|
||||
isJournal: page.journalDate != null,
|
||||
isHub: false,
|
||||
),
|
||||
);
|
||||
if (recent.length > 12) recent.removeLast();
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@@ -148,8 +233,10 @@ class AppState extends ChangeNotifier {
|
||||
Future<void> loadRecent() async {
|
||||
final pages = await backend.listPages(limit: 8);
|
||||
for (final p in pages) {
|
||||
if (!recent.any((r) => r.id == p.id)) {
|
||||
recent.add(PageBrief(id: p.id, title: p.title, isJournal: false));
|
||||
if (!p.isHub && !recent.any((r) => r.id == p.id)) {
|
||||
recent.add(
|
||||
PageBrief(id: p.id, title: p.title, isJournal: false, isHub: p.isHub),
|
||||
);
|
||||
}
|
||||
}
|
||||
notifyListeners();
|
||||
@@ -162,14 +249,15 @@ class AppState extends ChangeNotifier {
|
||||
id: id,
|
||||
title: title,
|
||||
isJournal: recent[i].isJournal,
|
||||
isHub: recent[i].isHub,
|
||||
);
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Top-bar shortcut: flips between the light and dark Paper themes.
|
||||
void toggleTheme(Brightness current) {
|
||||
themeMode = current == Brightness.dark ? ThemeMode.light : ThemeMode.dark;
|
||||
notifyListeners();
|
||||
setTheme(current == Brightness.dark ? 'paper' : 'paper-dark');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// A key plus modifiers. Ctrl also matches Cmd on macOS.
|
||||
@immutable
|
||||
class Combo {
|
||||
const Combo(
|
||||
this.key, {
|
||||
this.ctrl = false,
|
||||
this.shift = false,
|
||||
this.alt = false,
|
||||
});
|
||||
|
||||
final LogicalKeyboardKey key;
|
||||
final bool ctrl;
|
||||
final bool shift;
|
||||
final bool alt;
|
||||
|
||||
/// `ctrl+shift+<keyId>`: stable across platforms and keyboard layouts.
|
||||
String encode() =>
|
||||
'${ctrl ? 'ctrl+' : ''}${shift ? 'shift+' : ''}${alt ? 'alt+' : ''}${key.keyId}';
|
||||
|
||||
static Combo? decode(String s) {
|
||||
final parts = s.split('+');
|
||||
final id = int.tryParse(parts.last);
|
||||
if (id == null) return null;
|
||||
final mods = parts.sublist(0, parts.length - 1);
|
||||
if (mods.any((m) => m != 'ctrl' && m != 'shift' && m != 'alt')) return null;
|
||||
return Combo(
|
||||
LogicalKeyboardKey.findKeyByKeyId(id) ?? LogicalKeyboardKey(id),
|
||||
ctrl: mods.contains('ctrl'),
|
||||
shift: mods.contains('shift'),
|
||||
alt: mods.contains('alt'),
|
||||
);
|
||||
}
|
||||
|
||||
/// A key that is only a modifier cannot be bound on its own.
|
||||
bool get isModifierOnly => const {
|
||||
'Control Left',
|
||||
'Control Right',
|
||||
'Shift Left',
|
||||
'Shift Right',
|
||||
'Alt Left',
|
||||
'Alt Right',
|
||||
'Meta Left',
|
||||
'Meta Right',
|
||||
}.contains(key.keyLabel);
|
||||
|
||||
String get label {
|
||||
final k = key.keyLabel.isEmpty ? 'Key ${key.keyId}' : key.keyLabel;
|
||||
return [if (ctrl) 'Ctrl', if (shift) 'Shift', if (alt) 'Alt', k].join('+');
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is Combo &&
|
||||
other.key == key &&
|
||||
other.ctrl == ctrl &&
|
||||
other.shift == shift &&
|
||||
other.alt == alt;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(key, ctrl, shift, alt);
|
||||
}
|
||||
|
||||
/// Everything that can be bound to a key. `editor` actions apply inside a focused block;
|
||||
/// the others anywhere in the app.
|
||||
enum AppAction {
|
||||
quickSwitcher('Quick switcher', false),
|
||||
journals('Journals', false),
|
||||
graph('Graph view', false),
|
||||
timeline('Timeline', false),
|
||||
sidebar('Toggle sidebar', false),
|
||||
pageSidebar('Toggle graph sidebar', false),
|
||||
settings('Settings', false),
|
||||
back('Back', false),
|
||||
forward('Forward', false),
|
||||
bold('Bold', true),
|
||||
italic('Italic', true),
|
||||
strike('Strikethrough', true),
|
||||
highlight('Highlight', true),
|
||||
code('Inline code', true),
|
||||
link('Page link', true);
|
||||
|
||||
const AppAction(this.label, this.editor);
|
||||
final String label;
|
||||
final bool editor;
|
||||
|
||||
Combo get defaultCombo => switch (this) {
|
||||
quickSwitcher => Combo(LogicalKeyboardKey.keyK, ctrl: true),
|
||||
journals => Combo(LogicalKeyboardKey.keyJ, ctrl: true, shift: true),
|
||||
graph => Combo(LogicalKeyboardKey.keyG, ctrl: true, shift: true),
|
||||
timeline => Combo(LogicalKeyboardKey.keyT, ctrl: true, shift: true),
|
||||
sidebar => Combo(LogicalKeyboardKey.backslash, ctrl: true),
|
||||
pageSidebar => Combo(LogicalKeyboardKey.backslash, ctrl: true, shift: true),
|
||||
settings => Combo(LogicalKeyboardKey.comma, ctrl: true),
|
||||
back => Combo(LogicalKeyboardKey.arrowLeft, alt: true),
|
||||
forward => Combo(LogicalKeyboardKey.arrowRight, alt: true),
|
||||
bold => Combo(LogicalKeyboardKey.keyB, ctrl: true),
|
||||
italic => Combo(LogicalKeyboardKey.keyI, ctrl: true),
|
||||
strike => Combo(LogicalKeyboardKey.keyS, ctrl: true, shift: true),
|
||||
highlight => Combo(LogicalKeyboardKey.keyH, ctrl: true, shift: true),
|
||||
code => Combo(LogicalKeyboardKey.keyE, ctrl: true),
|
||||
link => Combo(LogicalKeyboardKey.keyL, ctrl: true),
|
||||
};
|
||||
}
|
||||
|
||||
/// Default bindings plus the user's overrides. Combos are unique across all actions; binding
|
||||
/// one that another action holds is refused (the caller shows which one).
|
||||
class Keymap {
|
||||
Keymap([Map<String, String> overrides = const {}]) {
|
||||
for (final e in overrides.entries) {
|
||||
final action = AppAction.values.asNameMap()[e.key];
|
||||
final combo = Combo.decode(e.value);
|
||||
if (action != null && combo != null) _custom[action] = combo;
|
||||
}
|
||||
}
|
||||
|
||||
final _custom = <AppAction, Combo>{};
|
||||
|
||||
Combo of(AppAction a) => _custom[a] ?? a.defaultCombo;
|
||||
bool isCustom(AppAction a) => _custom.containsKey(a);
|
||||
|
||||
/// The action bound to `c`, if any.
|
||||
AppAction? actionFor(Combo c, {bool? editor}) {
|
||||
for (final a in AppAction.values) {
|
||||
if ((editor == null || a.editor == editor) && of(a) == c) return a;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Binds `c` to `a`. Returns the action that already holds `c`, leaving the map unchanged.
|
||||
AppAction? bind(AppAction a, Combo c) {
|
||||
final owner = actionFor(c);
|
||||
if (owner != null && owner != a) return owner;
|
||||
if (c == a.defaultCombo) {
|
||||
_custom.remove(a);
|
||||
} else {
|
||||
_custom[a] = c;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
void reset(AppAction a) => _custom.remove(a);
|
||||
|
||||
void resetAll() => _custom.clear();
|
||||
|
||||
Map<String, String> toJson() => {
|
||||
for (final e in _custom.entries) e.key.name: e.value.encode(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
/// Where user preferences (theme, key bindings) are kept between runs.
|
||||
abstract class SettingsStore {
|
||||
Map<String, dynamic> load();
|
||||
void save(Map<String, dynamic> data);
|
||||
}
|
||||
|
||||
/// Keeps nothing (tests, previews).
|
||||
class MemorySettings implements SettingsStore {
|
||||
Map<String, dynamic> data = {};
|
||||
|
||||
@override
|
||||
Map<String, dynamic> load() => data;
|
||||
|
||||
@override
|
||||
void save(Map<String, dynamic> d) => data = d;
|
||||
}
|
||||
|
||||
/// A small JSON file; unreadable or corrupt files just mean defaults.
|
||||
class FileSettings implements SettingsStore {
|
||||
FileSettings(this.path);
|
||||
final String path;
|
||||
|
||||
@override
|
||||
Map<String, dynamic> load() {
|
||||
try {
|
||||
final v = jsonDecode(File(path).readAsStringSync());
|
||||
return v is Map<String, dynamic> ? v : {};
|
||||
} catch (_) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void save(Map<String, dynamic> data) {
|
||||
try {
|
||||
File(path).writeAsStringSync(jsonEncode(data));
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,52 @@ class SynapseColors extends ThemeExtension<SynapseColors> {
|
||||
highlight: Color(0x55B89B2E),
|
||||
);
|
||||
|
||||
/// "Sweet" (the KDE/GTK theme): deep indigo surfaces, magenta accent, mint for done tasks.
|
||||
static const sweet = SynapseColors(
|
||||
paper: Color(0xFF1B1D2B),
|
||||
surface: Color(0xFF151722),
|
||||
ink: Color(0xFFC9CDDA),
|
||||
muted: Color(0xFF8E93AB),
|
||||
faint: Color(0xFF555A78),
|
||||
line: Color(0xFF2A2D42),
|
||||
accent: Color(0xFFD05CE3),
|
||||
accentSoft: Color(0x33D05CE3),
|
||||
ref: Color(0xFFF2A65A),
|
||||
done: Color(0xFF4DDBA7),
|
||||
codeBg: Color(0xFF12141D),
|
||||
highlight: Color(0x55D05CE3),
|
||||
);
|
||||
|
||||
static const sweetLight = SynapseColors(
|
||||
paper: Color(0xFFF8F6FB),
|
||||
surface: Color(0xFFEFEBF5),
|
||||
ink: Color(0xFF2B2D42),
|
||||
muted: Color(0xFF6A6E88),
|
||||
faint: Color(0xFFA8ABC0),
|
||||
line: Color(0xFFE1DCEB),
|
||||
accent: Color(0xFFB21FC2),
|
||||
accentSoft: Color(0x1AB21FC2),
|
||||
ref: Color(0xFFC77A1A),
|
||||
done: Color(0xFF2FA37A),
|
||||
codeBg: Color(0xFFEBE6F2),
|
||||
highlight: Color(0x66F2C26B),
|
||||
);
|
||||
|
||||
static const nord = SynapseColors(
|
||||
paper: Color(0xFF2E3440),
|
||||
surface: Color(0xFF272C36),
|
||||
ink: Color(0xFFD8DEE9),
|
||||
muted: Color(0xFF9AA5B8),
|
||||
faint: Color(0xFF616E88),
|
||||
line: Color(0xFF3B4252),
|
||||
accent: Color(0xFF88C0D0),
|
||||
accentSoft: Color(0x2288C0D0),
|
||||
ref: Color(0xFFEBCB8B),
|
||||
done: Color(0xFFA3BE8C),
|
||||
codeBg: Color(0xFF242933),
|
||||
highlight: Color(0x55EBCB8B),
|
||||
);
|
||||
|
||||
@override
|
||||
SynapseColors copyWith() => this;
|
||||
|
||||
@@ -107,10 +153,44 @@ extension SynapseThemeX on BuildContext {
|
||||
SynapseColors get colors => Theme.of(this).extension<SynapseColors>()!;
|
||||
}
|
||||
|
||||
ThemeData buildTheme(Brightness brightness) {
|
||||
final c = brightness == Brightness.light
|
||||
? SynapseColors.light
|
||||
: SynapseColors.dark;
|
||||
/// A selectable palette. `auto` follows the system between Paper light and Paper dark.
|
||||
class AppTheme {
|
||||
const AppTheme(this.id, this.label, this.brightness, this.colors);
|
||||
final String id;
|
||||
final String label;
|
||||
final Brightness brightness;
|
||||
final SynapseColors colors;
|
||||
}
|
||||
|
||||
const autoThemeId = 'auto';
|
||||
|
||||
const appThemes = [
|
||||
AppTheme('paper', 'Paper', Brightness.light, SynapseColors.light),
|
||||
AppTheme('paper-dark', 'Paper dark', Brightness.dark, SynapseColors.dark),
|
||||
AppTheme('sweet', 'Sweet', Brightness.dark, SynapseColors.sweet),
|
||||
AppTheme(
|
||||
'sweet-light',
|
||||
'Sweet light',
|
||||
Brightness.light,
|
||||
SynapseColors.sweetLight,
|
||||
),
|
||||
AppTheme('nord', 'Nord', Brightness.dark, SynapseColors.nord),
|
||||
];
|
||||
|
||||
/// The theme with `id`, or null for `auto` and unknown ids.
|
||||
AppTheme? themeById(String id) {
|
||||
for (final t in appThemes) {
|
||||
if (t.id == id) return t;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
ThemeData buildTheme(Brightness brightness, {SynapseColors? colors}) {
|
||||
final c =
|
||||
colors ??
|
||||
(brightness == Brightness.light
|
||||
? SynapseColors.light
|
||||
: SynapseColors.dark);
|
||||
final scheme =
|
||||
ColorScheme.fromSeed(
|
||||
seedColor: c.accent,
|
||||
|
||||
@@ -6,7 +6,17 @@ import '../theme/theme.dart';
|
||||
import '../widgets/common.dart';
|
||||
import '../widgets/dates.dart';
|
||||
|
||||
/// Every non-journal page, most recently edited first, loaded in pages of 100.
|
||||
enum PageSort {
|
||||
edited('Edited'),
|
||||
created('Created'),
|
||||
title('Title');
|
||||
|
||||
const PageSort(this.label);
|
||||
final String label;
|
||||
}
|
||||
|
||||
/// Every non-journal note (hubs are folders, not pages), sortable. The whole list is loaded in
|
||||
/// batches of 200 and sorted on the client; the list itself is built lazily.
|
||||
class AllPagesView extends StatefulWidget {
|
||||
const AllPagesView({super.key});
|
||||
|
||||
@@ -16,96 +26,250 @@ class AllPagesView extends StatefulWidget {
|
||||
|
||||
class _AllPagesViewState extends State<AllPagesView> {
|
||||
final _pages = <PageDto>[];
|
||||
bool _loading = false;
|
||||
bool _done = false;
|
||||
PageSort _sort = PageSort.edited;
|
||||
bool _ascending = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_more();
|
||||
_load();
|
||||
}
|
||||
|
||||
Future<void> _more() async {
|
||||
if (_loading || _done) return;
|
||||
_loading = true;
|
||||
final batch = await AppScope.read(context).backend
|
||||
.listPages(limit: 100, offset: _pages.length);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_pages.addAll(batch);
|
||||
_done = batch.length < 100;
|
||||
_loading = false;
|
||||
Future<void> _load() async {
|
||||
final backend = AppScope.read(context).backend;
|
||||
var offset = 0;
|
||||
while (true) {
|
||||
final batch = await backend.listPages(limit: 200, offset: offset);
|
||||
if (!mounted) return;
|
||||
offset += batch.length;
|
||||
setState(() => _pages.addAll(batch.where((p) => !p.isHub)));
|
||||
if (batch.length < 200) return;
|
||||
}
|
||||
}
|
||||
|
||||
List<PageDto> get _sorted {
|
||||
final list = [..._pages];
|
||||
int cmp(PageDto a, PageDto b) => switch (_sort) {
|
||||
PageSort.edited => a.updatedAt.compareTo(b.updatedAt),
|
||||
PageSort.created => a.createdAt.compareTo(b.createdAt),
|
||||
PageSort.title => a.title.toLowerCase().compareTo(b.title.toLowerCase()),
|
||||
};
|
||||
list.sort((a, b) {
|
||||
final c = cmp(a, b);
|
||||
// Time sorts default to newest first, so "descending" is the natural direction there.
|
||||
final flip = _sort == PageSort.title ? _ascending : !_ascending;
|
||||
return flip ? c : -c;
|
||||
});
|
||||
return list;
|
||||
}
|
||||
|
||||
Future<void> _cleanUp() async {
|
||||
final app = AppScope.read(context);
|
||||
final candidates = await app.backend.legacyCandidates();
|
||||
if (!mounted) return;
|
||||
final removed = await showDialog<List<String>>(
|
||||
context: context,
|
||||
builder: (_) => CleanupDialog(candidates: candidates),
|
||||
);
|
||||
if (removed == null || removed.isEmpty) return;
|
||||
await app.queue.run(() => app.backend.purgePages(removed));
|
||||
app.recent.removeWhere((p) => removed.contains(p.id));
|
||||
app.reload();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final app = AppScope.read(context);
|
||||
final colors = context.colors;
|
||||
final pages = _sorted;
|
||||
return LayoutBuilder(
|
||||
builder: (context, box) => NotificationListener<ScrollNotification>(
|
||||
onNotification: (n) {
|
||||
if (n.metrics.extentAfter < 600) _more();
|
||||
return false;
|
||||
},
|
||||
child: ListView.builder(
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
sidePadding(box.maxWidth),
|
||||
36,
|
||||
sidePadding(box.maxWidth),
|
||||
80,
|
||||
),
|
||||
itemCount: _pages.length + 1,
|
||||
itemBuilder: (context, i) {
|
||||
if (i == 0) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 20),
|
||||
child: Text(
|
||||
'All pages',
|
||||
style: Theme.of(context).textTheme.headlineLarge,
|
||||
),
|
||||
);
|
||||
}
|
||||
final p = _pages[i - 1];
|
||||
final edited = DateTime.fromMillisecondsSinceEpoch(
|
||||
p.updatedAt.toInt(),
|
||||
);
|
||||
return InkWell(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
onTap: () => app.openId(p.id),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 9, horizontal: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
builder: (context, box) => ListView.builder(
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
sidePadding(box.maxWidth),
|
||||
36,
|
||||
sidePadding(box.maxWidth),
|
||||
80,
|
||||
),
|
||||
itemCount: pages.length + 1,
|
||||
itemBuilder: (context, i) {
|
||||
if (i == 0) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 20),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'All pages',
|
||||
style: Theme.of(context).textTheme.headlineLarge,
|
||||
),
|
||||
),
|
||||
PopupMenuButton<PageSort>(
|
||||
key: const ValueKey('page-sort'),
|
||||
tooltip: 'Sort by',
|
||||
initialValue: _sort,
|
||||
onSelected: (v) => setState(() {
|
||||
_sort = v;
|
||||
_ascending = false;
|
||||
}),
|
||||
itemBuilder: (_) => [
|
||||
for (final v in PageSort.values)
|
||||
PopupMenuItem(value: v, child: Text(v.label)),
|
||||
],
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
child: Text(
|
||||
p.title,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(fontSize: 14.5, color: colors.ink),
|
||||
_sort.label,
|
||||
style: TextStyle(fontSize: 13, color: colors.muted),
|
||||
),
|
||||
),
|
||||
if (p.originJournal != null)
|
||||
Text(
|
||||
'born ${shortDate(parseDay(p.originJournal!))}',
|
||||
style: TextStyle(fontSize: 12, color: colors.faint),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
SizedBox(
|
||||
width: 70,
|
||||
child: Text(
|
||||
shortDate(edited),
|
||||
textAlign: TextAlign.right,
|
||||
style: TextStyle(fontSize: 12, color: colors.muted),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
key: const ValueKey('page-sort-direction'),
|
||||
tooltip: _ascending ? 'Ascending' : 'Descending',
|
||||
visualDensity: VisualDensity.compact,
|
||||
iconSize: 18,
|
||||
color: colors.muted,
|
||||
icon: Icon(
|
||||
_ascending
|
||||
? Icons.arrow_upward_rounded
|
||||
: Icons.arrow_downward_rounded,
|
||||
),
|
||||
],
|
||||
),
|
||||
onPressed: () => setState(() => _ascending = !_ascending),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
TextLink(
|
||||
'Clean up',
|
||||
icon: Icons.cleaning_services_outlined,
|
||||
onTap: _cleanUp,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
}
|
||||
final p = pages[i - 1];
|
||||
final edited = DateTime.fromMillisecondsSinceEpoch(
|
||||
p.updatedAt.toInt(),
|
||||
);
|
||||
return InkWell(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
onTap: () => app.openId(p.id),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 9, horizontal: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
p.title,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(fontSize: 14.5, color: colors.ink),
|
||||
),
|
||||
),
|
||||
if (p.originJournal != null)
|
||||
Text(
|
||||
'born ${shortDate(parseDay(p.originJournal!))}',
|
||||
style: TextStyle(fontSize: 12, color: colors.faint),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
SizedBox(
|
||||
width: 70,
|
||||
child: Text(
|
||||
shortDate(edited),
|
||||
textAlign: TextAlign.right,
|
||||
style: TextStyle(fontSize: 12, color: colors.muted),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists legacy Logseq pages with checkboxes; pops with the ids to delete (or null).
|
||||
class CleanupDialog extends StatefulWidget {
|
||||
const CleanupDialog({super.key, required this.candidates});
|
||||
final List<LegacyCandidate> candidates;
|
||||
|
||||
@override
|
||||
State<CleanupDialog> createState() => _CleanupDialogState();
|
||||
}
|
||||
|
||||
class _CleanupDialogState extends State<CleanupDialog> {
|
||||
late final Set<String> _checked = {
|
||||
for (final c in widget.candidates)
|
||||
if (c.preselected) c.id,
|
||||
};
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = context.colors;
|
||||
final items = widget.candidates;
|
||||
return AlertDialog(
|
||||
title: const Text('Remove legacy Logseq pages'),
|
||||
content: SizedBox(
|
||||
width: 460,
|
||||
child: items.isEmpty
|
||||
? Text(
|
||||
'No legacy pages found.',
|
||||
style: TextStyle(color: colors.muted),
|
||||
)
|
||||
: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'This deletes the selected pages and their blocks.',
|
||||
style: TextStyle(fontSize: 13, color: colors.muted),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Flexible(
|
||||
child: ListView(
|
||||
shrinkWrap: true,
|
||||
children: [
|
||||
for (final c in items)
|
||||
CheckboxListTile(
|
||||
dense: true,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
controlAffinity: ListTileControlAffinity.leading,
|
||||
value: _checked.contains(c.id),
|
||||
onChanged: (v) => setState(
|
||||
() => v == true
|
||||
? _checked.add(c.id)
|
||||
: _checked.remove(c.id),
|
||||
),
|
||||
title: Text(c.title),
|
||||
subtitle: Text(
|
||||
'${c.reason} · ${c.blocks} '
|
||||
'${c.blocks == 1 ? 'block' : 'blocks'}',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: colors.faint,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
if (items.isNotEmpty)
|
||||
TextButton(
|
||||
onPressed: _checked.isEmpty
|
||||
? null
|
||||
: () => Navigator.pop(context, _checked.toList()),
|
||||
child: Text('Delete (${_checked.length})'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../backend/graph_backend.dart';
|
||||
import '../state/app_state.dart';
|
||||
import '../theme/theme.dart';
|
||||
import '../widgets/pickers.dart';
|
||||
|
||||
/// "Convert to hub": title, description, member checklist and what to do with the outline.
|
||||
/// Pops `true` once the page has been converted.
|
||||
class ConvertToHubDialog extends StatefulWidget {
|
||||
const ConvertToHubDialog({super.key, required this.page});
|
||||
final PageDto page;
|
||||
|
||||
@override
|
||||
State<ConvertToHubDialog> createState() => _ConvertToHubDialogState();
|
||||
}
|
||||
|
||||
class _ConvertToHubDialogState extends State<ConvertToHubDialog> {
|
||||
HubPreviewDto? _preview;
|
||||
final _title = TextEditingController();
|
||||
final _description = TextEditingController();
|
||||
final _noteTitle = TextEditingController();
|
||||
final _checked = <String>{};
|
||||
bool _keep = false;
|
||||
bool _busy = false;
|
||||
String? _error;
|
||||
Object? _loadError;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_load();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_title.dispose();
|
||||
_description.dispose();
|
||||
_noteTitle.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
final app = AppScope.read(context);
|
||||
try {
|
||||
final p = await app.backend.hubConversionPreview(widget.page.id);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_preview = p;
|
||||
_title.text = p.suggestedTitle;
|
||||
_description.text = p.suggestedDescription;
|
||||
_noteTitle.text = p.suggestedNoteTitle;
|
||||
_checked.addAll(p.members.map((m) => m.id));
|
||||
_keep = p.proseBlocks > 0;
|
||||
});
|
||||
} catch (e) {
|
||||
if (mounted) setState(() => _loadError = e);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _convert() async {
|
||||
final p = _preview!;
|
||||
final app = AppScope.read(context);
|
||||
setState(() {
|
||||
_busy = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
await app.queue.run(
|
||||
() => app.backend.convertToHub(
|
||||
widget.page.id,
|
||||
_title.text.trim(),
|
||||
_description.text.trim(),
|
||||
[
|
||||
for (final m in p.members)
|
||||
if (_checked.contains(m.id)) m.id,
|
||||
],
|
||||
keepOutlineAs: _keep ? _noteTitle.text.trim() : null,
|
||||
),
|
||||
report: false,
|
||||
);
|
||||
if (mounted) Navigator.pop(context, true);
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_busy = false;
|
||||
_error = errorText(e);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = context.colors;
|
||||
final p = _preview;
|
||||
return AlertDialog(
|
||||
title: const Text('Convert to hub'),
|
||||
content: SizedBox(
|
||||
width: 480,
|
||||
child: _loadError != null
|
||||
? Text(errorText(_loadError!))
|
||||
: p == null
|
||||
? const SizedBox(
|
||||
height: 80,
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
)
|
||||
: SingleChildScrollView(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
TextField(
|
||||
key: const ValueKey('convert-title'),
|
||||
controller: _title,
|
||||
onChanged: (_) => setState(() {}),
|
||||
decoration: const InputDecoration(labelText: 'Title'),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
key: const ValueKey('convert-description'),
|
||||
controller: _description,
|
||||
minLines: 1,
|
||||
maxLines: 3,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Description',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'MEMBERS (${_checked.length}/${p.members.length})',
|
||||
style: Theme.of(context).textTheme.labelSmall,
|
||||
),
|
||||
if (p.members.isEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Text(
|
||||
'No candidates found. Add notes from the hub afterwards.',
|
||||
style: TextStyle(fontSize: 13, color: colors.muted),
|
||||
),
|
||||
),
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxHeight: 220),
|
||||
child: ListView(
|
||||
shrinkWrap: true,
|
||||
children: [
|
||||
for (final m in p.members)
|
||||
CheckboxListTile(
|
||||
key: ValueKey('member-${m.id}'),
|
||||
dense: true,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
controlAffinity: ListTileControlAffinity.leading,
|
||||
value: _checked.contains(m.id),
|
||||
title: Text(m.title),
|
||||
onChanged: (v) => setState(
|
||||
() => v == true
|
||||
? _checked.add(m.id)
|
||||
: _checked.remove(m.id),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
CheckboxListTile(
|
||||
key: const ValueKey('keep-outline'),
|
||||
dense: true,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
controlAffinity: ListTileControlAffinity.leading,
|
||||
value: _keep,
|
||||
title: const Text('Keep the original outline in a note'),
|
||||
subtitle: p.blocks == 0
|
||||
? null
|
||||
: Text(
|
||||
_keep
|
||||
? '${p.blocks} blocks move to the note'
|
||||
: '${p.blocks} blocks will be deleted',
|
||||
style: TextStyle(color: colors.faint),
|
||||
),
|
||||
onChanged: (v) => setState(() => _keep = v == true),
|
||||
),
|
||||
if (_keep)
|
||||
TextField(
|
||||
key: const ValueKey('convert-note-title'),
|
||||
controller: _noteTitle,
|
||||
onChanged: (_) => setState(() {}),
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Note title',
|
||||
errorText: _noteTitle.text.trim().isEmpty
|
||||
? 'A title is required to keep the outline'
|
||||
: null,
|
||||
),
|
||||
),
|
||||
if (_error != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 12),
|
||||
child: Text(
|
||||
_error!,
|
||||
key: const ValueKey('convert-error'),
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
fontSize: 13,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: _busy ? null : () => Navigator.pop(context),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed:
|
||||
p == null ||
|
||||
_busy ||
|
||||
_title.text.trim().isEmpty ||
|
||||
(_keep && _noteTitle.text.trim().isEmpty)
|
||||
? null
|
||||
: _convert,
|
||||
child: const Text('Convert'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -22,23 +22,25 @@ class GraphView extends StatefulWidget {
|
||||
const GraphView({super.key, this.mode = GraphMode.network, this.focusId});
|
||||
final GraphMode mode;
|
||||
|
||||
/// Page to focus in the local and synapse modes.
|
||||
/// Page to focus in the synapse mode.
|
||||
final String? focusId;
|
||||
|
||||
@override
|
||||
State<GraphView> createState() => _GraphViewState();
|
||||
}
|
||||
|
||||
/// How the clusters mode groups pages.
|
||||
enum ClusterBy { hubs, tags, communities }
|
||||
|
||||
class _GraphViewState extends State<GraphView> {
|
||||
late GraphMode _mode = widget.mode;
|
||||
GraphModel? _model;
|
||||
Object? _error;
|
||||
GraphFilter _filter = const GraphFilter();
|
||||
ColorBy _colorBy = ColorBy.cluster;
|
||||
int _depth = 2;
|
||||
|
||||
/// Journals are context for a neighbourhood, so the local mode shows them by default.
|
||||
bool _localJournals = true;
|
||||
/// Clusters mode grouping; null = hubs when the graph has any, else communities.
|
||||
ClusterBy? _clusterBy;
|
||||
int? _focus;
|
||||
BrainOverlay? _brain;
|
||||
SubGraph? _sub;
|
||||
@@ -82,6 +84,10 @@ class _GraphViewState extends State<GraphView> {
|
||||
}
|
||||
}
|
||||
|
||||
ClusterBy get _grouping =>
|
||||
_clusterBy ??
|
||||
((_model?.hasHubs ?? false) ? ClusterBy.hubs : ClusterBy.communities);
|
||||
|
||||
void _setMode(GraphMode m) {
|
||||
setState(() => _mode = m);
|
||||
_rebuildSub();
|
||||
@@ -102,16 +108,18 @@ class _GraphViewState extends State<GraphView> {
|
||||
if (m == null) return;
|
||||
switch (_mode) {
|
||||
case GraphMode.network || GraphMode.clusters:
|
||||
setState(() => _sub = m.subgraph(_filter.apply(m), _filter.kinds));
|
||||
case GraphMode.local:
|
||||
final f = _focus;
|
||||
if (f == null) return;
|
||||
final kinds = _filter.kinds;
|
||||
final hood = m.neighbourhood(f, _depth, kinds);
|
||||
final nodes = hood.keys
|
||||
.where((i) => i == f || _localJournals || !m.isJournal(i))
|
||||
.toList();
|
||||
setState(() => _sub = m.subgraph(nodes, kinds));
|
||||
final nodes = _filter.apply(m);
|
||||
// Hub grouping: layout-only springs to the home hub so folders cluster spatially.
|
||||
final springs = _mode != GraphMode.clusters
|
||||
? const <(int, int, double)>[]
|
||||
: switch (_grouping) {
|
||||
ClusterBy.hubs => m.hubSprings(nodes),
|
||||
ClusterBy.tags => m.tagSprings(nodes),
|
||||
ClusterBy.communities => const <(int, int, double)>[],
|
||||
};
|
||||
setState(
|
||||
() => _sub = m.subgraph(nodes, _filter.kinds, springs: springs),
|
||||
);
|
||||
case GraphMode.brain:
|
||||
final f = _focus;
|
||||
if (f == null) return;
|
||||
@@ -348,39 +356,25 @@ class _GraphViewState extends State<GraphView> {
|
||||
items: const {
|
||||
ColorBy.cluster: 'Colour: cluster',
|
||||
ColorBy.tag: 'Colour: tag',
|
||||
ColorBy.hub: 'Colour: hub',
|
||||
ColorBy.none: 'Colour: none',
|
||||
},
|
||||
onChanged: (c) => setState(() => _colorBy = c ?? ColorBy.cluster),
|
||||
),
|
||||
];
|
||||
case GraphMode.local:
|
||||
return [
|
||||
search,
|
||||
_Labeled(
|
||||
'Depth $_depth',
|
||||
SizedBox(
|
||||
width: 120,
|
||||
child: Slider(
|
||||
key: const ValueKey('depth'),
|
||||
value: _depth.toDouble(),
|
||||
min: 1,
|
||||
max: 3,
|
||||
divisions: 2,
|
||||
onChanged: (v) {
|
||||
setState(() => _depth = v.round());
|
||||
_rebuildSub();
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
chip('Journals', _localJournals, (v) {
|
||||
setState(() => _localJournals = v);
|
||||
_rebuildSub();
|
||||
}),
|
||||
if (_focus != null)
|
||||
_FocusLink(
|
||||
title: m.node(_focus!).title,
|
||||
onTap: () => _open(_focus!),
|
||||
if (_mode == GraphMode.clusters)
|
||||
_Dropdown<ClusterBy>(
|
||||
key: const ValueKey('cluster-group'),
|
||||
value: _grouping,
|
||||
hint: 'Group',
|
||||
items: const {
|
||||
ClusterBy.hubs: 'Group: hubs',
|
||||
ClusterBy.tags: 'Group: tags',
|
||||
ClusterBy.communities: 'Group: communities',
|
||||
},
|
||||
onChanged: (v) {
|
||||
_clusterBy = v;
|
||||
_rebuildSub();
|
||||
},
|
||||
),
|
||||
];
|
||||
case GraphMode.brain:
|
||||
@@ -426,11 +420,17 @@ class _GraphViewState extends State<GraphView> {
|
||||
),
|
||||
);
|
||||
}
|
||||
if (_mode == GraphMode.tree) return TreeCanvas(model: m, onTap: _open);
|
||||
if (_mode == GraphMode.tree) {
|
||||
return TreeCanvas(
|
||||
model: m,
|
||||
onTap: _open,
|
||||
name: AppScope.read(context).backend.graphName,
|
||||
);
|
||||
}
|
||||
final sub = _sub;
|
||||
if (sub == null) return const SizedBox.shrink();
|
||||
final app = AppScope.read(context);
|
||||
final explore = _mode == GraphMode.local || _mode == GraphMode.brain;
|
||||
final explore = _mode == GraphMode.brain;
|
||||
return Stack(
|
||||
children: [
|
||||
Positioned.fill(
|
||||
@@ -438,7 +438,13 @@ class _GraphViewState extends State<GraphView> {
|
||||
key: ValueKey(_mode),
|
||||
sub: sub,
|
||||
cache: app.graphPositions,
|
||||
colorBy: _mode == GraphMode.clusters ? ColorBy.cluster : _colorBy,
|
||||
colorBy: _mode == GraphMode.clusters
|
||||
? switch (_grouping) {
|
||||
ClusterBy.hubs => ColorBy.hub,
|
||||
ClusterBy.tags => ColorBy.tagGroup,
|
||||
ClusterBy.communities => ColorBy.cluster,
|
||||
}
|
||||
: _colorBy,
|
||||
hulls: _mode == GraphMode.clusters,
|
||||
focus: explore ? _focus : null,
|
||||
brain: _mode == GraphMode.brain ? _brain : null,
|
||||
@@ -485,6 +491,7 @@ class _Labeled extends StatelessWidget {
|
||||
|
||||
class _Dropdown<T> extends StatelessWidget {
|
||||
const _Dropdown({
|
||||
super.key,
|
||||
required this.value,
|
||||
required this.hint,
|
||||
required this.items,
|
||||
@@ -566,17 +573,39 @@ class _Legend extends StatelessWidget {
|
||||
],
|
||||
),
|
||||
);
|
||||
Widget hubMark() => Padding(
|
||||
padding: const EdgeInsets.only(right: 14),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
width: 11,
|
||||
height: 11,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: colors.muted,
|
||||
border: Border.all(color: colors.ink, width: 1.6),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 5),
|
||||
Text('Hub', style: TextStyle(fontSize: 11.5, color: colors.muted)),
|
||||
],
|
||||
),
|
||||
);
|
||||
final items = mode == GraphMode.brain
|
||||
? [
|
||||
line(palette[3], 'Synapse (thicker = stronger)', w: 3),
|
||||
line(colors.accent, 'Activation pulse', w: 3),
|
||||
hubMark(),
|
||||
]
|
||||
: [
|
||||
line(colors.muted, 'Link'),
|
||||
line(colors.accent, 'Tag'),
|
||||
line(palette[2], 'Property'),
|
||||
line(colors.ref, 'Block ref / embed'),
|
||||
line(colors.ink, 'Contains (hub → note)', w: 1),
|
||||
line(colors.faint, 'Mention', dashed: true),
|
||||
hubMark(),
|
||||
];
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
|
||||
@@ -679,6 +708,8 @@ class _LocalGraphPanelState extends State<LocalGraphPanel> {
|
||||
EdgeKind.blockRef,
|
||||
EdgeKind.embed,
|
||||
EdgeKind.mention,
|
||||
EdgeKind.contains,
|
||||
EdgeKind.tagged,
|
||||
};
|
||||
final hood = m.neighbourhood(f, _depth, kinds).keys.toList();
|
||||
setState(() => _sub = m.subgraph(hood, kinds));
|
||||
@@ -721,15 +752,6 @@ class _LocalGraphPanelState extends State<LocalGraphPanel> {
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'Open in graph view',
|
||||
visualDensity: VisualDensity.compact,
|
||||
iconSize: 15,
|
||||
color: colors.muted,
|
||||
icon: const Icon(Icons.open_in_full_rounded),
|
||||
onPressed: () =>
|
||||
app.go(GraphRoute(GraphMode.local, focusId: widget.pageId)),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../backend/graph_backend.dart';
|
||||
import '../state/app_state.dart';
|
||||
import '../theme/theme.dart';
|
||||
import '../widgets/common.dart';
|
||||
import '../widgets/dates.dart';
|
||||
import '../widgets/pickers.dart';
|
||||
import '../widgets/tags.dart';
|
||||
import 'graph_view.dart';
|
||||
import 'page_screen.dart';
|
||||
|
||||
/// A hub: title, short description and its members (sub-hubs first, then notes). It has no
|
||||
/// outline. Membership is stored on the member, so adding/removing edits the member.
|
||||
class HubScreen extends StatefulWidget {
|
||||
const HubScreen({
|
||||
super.key,
|
||||
required this.page,
|
||||
required this.aliases,
|
||||
required this.structure,
|
||||
required this.hubSizes,
|
||||
});
|
||||
final PageDto page;
|
||||
final List<String> aliases;
|
||||
final PageStructure? structure;
|
||||
final Map<String, int> hubSizes;
|
||||
|
||||
@override
|
||||
State<HubScreen> createState() => _HubScreenState();
|
||||
}
|
||||
|
||||
class _HubScreenState extends State<HubScreen> {
|
||||
late final _desc = TextEditingController(text: widget.page.description);
|
||||
late final _focus = FocusNode()..addListener(_blur);
|
||||
late String _committed = widget.page.description;
|
||||
AppState? _app;
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
_app = AppScope.read(context);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_commit();
|
||||
_desc.dispose();
|
||||
_focus.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _blur() {
|
||||
if (!_focus.hasFocus) _commit();
|
||||
}
|
||||
|
||||
void _commit() {
|
||||
final text = _desc.text.trim();
|
||||
if (text == _committed) return;
|
||||
_committed = text;
|
||||
final app = _app!;
|
||||
app.queue
|
||||
.run(() => app.backend.setHubDescription(widget.page.id, text))
|
||||
.ignore();
|
||||
}
|
||||
|
||||
Future<void> _add() async {
|
||||
final app = AppScope.read(context);
|
||||
final hub = widget.page;
|
||||
final st = widget.structure;
|
||||
final taken = {hub.id, ...?st?.members.map((m) => m.id)};
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
final r = await showPagePicker(
|
||||
context,
|
||||
heading: 'Add to ${hub.title}',
|
||||
canCreateNote: true,
|
||||
canCreateHub: true,
|
||||
search: (q) async {
|
||||
if (q.isEmpty) {
|
||||
final l = await app.backend.listPages(limit: 20);
|
||||
return [
|
||||
for (final p in l)
|
||||
if (!taken.contains(p.id))
|
||||
PickItem(id: p.id, title: p.title, isHub: p.isHub),
|
||||
];
|
||||
}
|
||||
final hits = await app.backend.searchTitles(q);
|
||||
return [
|
||||
for (final h in hits)
|
||||
if (!taken.contains(h.pageId))
|
||||
PickItem(id: h.pageId, title: h.title),
|
||||
];
|
||||
},
|
||||
);
|
||||
if (r == null || !mounted) return;
|
||||
try {
|
||||
await app.queue.run(() async {
|
||||
final String id;
|
||||
if (r.item != null) {
|
||||
id = r.item!.id;
|
||||
} else if (r.newHub) {
|
||||
id = (await app.backend.createHub(r.newTitle!, '')).id;
|
||||
} else {
|
||||
id = (await app.backend.createPageFromTemplate(
|
||||
hub.id,
|
||||
r.newTitle!,
|
||||
)).id;
|
||||
}
|
||||
await app.backend.addToHub(id, hub.id);
|
||||
}, report: false);
|
||||
app.reload();
|
||||
} catch (e) {
|
||||
messenger.showSnackBar(SnackBar(content: Text(errorText(e))));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _openTemplate() async {
|
||||
final app = AppScope.read(context);
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
try {
|
||||
app.openId(await app.backend.hubTemplate(widget.page.id));
|
||||
} catch (e) {
|
||||
messenger.showSnackBar(SnackBar(content: Text(errorText(e))));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _remove(PageBrief m) async {
|
||||
final app = AppScope.read(context);
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
try {
|
||||
await app.queue.run(
|
||||
() => app.backend.removeFromHub(m.id, widget.page.id),
|
||||
report: false,
|
||||
);
|
||||
app.reload();
|
||||
} catch (e) {
|
||||
messenger.showSnackBar(SnackBar(content: Text(errorText(e))));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = context.colors;
|
||||
final app = AppScope.read(context);
|
||||
final st = widget.structure;
|
||||
final page = widget.page;
|
||||
final members = st?.members ?? const <PageBrief>[];
|
||||
return LayoutBuilder(
|
||||
builder: (context, box) {
|
||||
final pad = sidePadding(box.maxWidth);
|
||||
return ListView(
|
||||
padding: EdgeInsets.fromLTRB(pad, 36, pad, 120),
|
||||
children: [
|
||||
if (st != null && st.nsPath.isNotEmpty) ...[
|
||||
Breadcrumb(path: st.nsPath),
|
||||
const SizedBox(height: 6),
|
||||
],
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(child: TitleField(page: page)),
|
||||
PageMenu(page: page, structure: st),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextField(
|
||||
key: const ValueKey('hub-description'),
|
||||
controller: _desc,
|
||||
focusNode: _focus,
|
||||
minLines: 1,
|
||||
maxLines: 3,
|
||||
style: TextStyle(fontSize: 14.5, color: colors.muted),
|
||||
decoration: const InputDecoration.collapsed(
|
||||
hintText: 'Add a short description',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Wrap(
|
||||
spacing: 14,
|
||||
runSpacing: 4,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
if (st != null && st.inHubs.isNotEmpty)
|
||||
InHubs(pageId: page.id, hubs: st.inHubs),
|
||||
if (page.originJournal != null)
|
||||
TextLink(
|
||||
'Born ${longDate(page.originJournal!)}',
|
||||
icon: Icons.spa_outlined,
|
||||
onTap: () => app.openTitle(page.originJournal!),
|
||||
style: const TextStyle(fontSize: 12),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TagBar(page: page),
|
||||
const SizedBox(height: 28),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: SectionLabel(
|
||||
'Members',
|
||||
trailing: Text(
|
||||
'${members.length}',
|
||||
style: TextStyle(fontSize: 11, color: colors.faint),
|
||||
),
|
||||
),
|
||||
),
|
||||
TextLink(
|
||||
'Template',
|
||||
icon: Icons.article_outlined,
|
||||
onTap: _openTemplate,
|
||||
style: const TextStyle(fontSize: 12.5),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
TextLink(
|
||||
'Add',
|
||||
icon: Icons.add_rounded,
|
||||
onTap: _add,
|
||||
style: const TextStyle(fontSize: 12.5),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
if (st != null && members.isEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Text(
|
||||
'Empty. Add notes or sub-hubs to organise them here.',
|
||||
style: TextStyle(fontSize: 13, color: colors.muted),
|
||||
),
|
||||
),
|
||||
for (final m in members)
|
||||
_MemberRow(
|
||||
key: ValueKey('member-${m.id}'),
|
||||
member: m,
|
||||
count: widget.hubSizes[m.id],
|
||||
onOpen: () => app.openId(m.id),
|
||||
onRemove: () => _remove(m),
|
||||
),
|
||||
const SizedBox(height: 36),
|
||||
LocalGraphPanel(key: ValueKey('local-${page.id}'), pageId: page.id),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _MemberRow extends StatefulWidget {
|
||||
const _MemberRow({
|
||||
super.key,
|
||||
required this.member,
|
||||
required this.count,
|
||||
required this.onOpen,
|
||||
required this.onRemove,
|
||||
});
|
||||
final PageBrief member;
|
||||
final int? count;
|
||||
final VoidCallback onOpen;
|
||||
final VoidCallback onRemove;
|
||||
|
||||
@override
|
||||
State<_MemberRow> createState() => _MemberRowState();
|
||||
}
|
||||
|
||||
class _MemberRowState extends State<_MemberRow> {
|
||||
bool _hover = false;
|
||||
|
||||
Future<void> _menu(Offset at) async {
|
||||
final r = await showMenu<bool>(
|
||||
context: context,
|
||||
position: RelativeRect.fromLTRB(at.dx, at.dy, at.dx, at.dy),
|
||||
items: const [PopupMenuItem(value: true, child: Text('Remove from hub'))],
|
||||
);
|
||||
if (r == true) widget.onRemove();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = context.colors;
|
||||
final m = widget.member;
|
||||
return MouseRegion(
|
||||
onEnter: (_) => setState(() => _hover = true),
|
||||
onExit: (_) => setState(() => _hover = false),
|
||||
child: GestureDetector(
|
||||
onLongPressStart: (d) => _menu(d.globalPosition),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
onTap: widget.onOpen,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
m.isHub ? Icons.folder_outlined : Icons.description_outlined,
|
||||
size: 17,
|
||||
color: colors.accent.withAlpha(0xCC),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
m.title,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(fontSize: 14.5, color: colors.ink),
|
||||
),
|
||||
),
|
||||
if (m.isHub && widget.count != null)
|
||||
Text(
|
||||
'${widget.count}',
|
||||
style: TextStyle(fontSize: 11.5, color: colors.faint),
|
||||
),
|
||||
SizedBox(
|
||||
width: 28,
|
||||
child: _hover
|
||||
? InkResponse(
|
||||
key: ValueKey('remove-${m.id}'),
|
||||
radius: 14,
|
||||
onTap: widget.onRemove,
|
||||
child: Icon(
|
||||
Icons.close_rounded,
|
||||
size: 15,
|
||||
color: colors.faint,
|
||||
),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../backend/graph_backend.dart';
|
||||
import '../state/app_state.dart';
|
||||
import '../theme/theme.dart';
|
||||
import '../widgets/pickers.dart';
|
||||
|
||||
/// Sidebar "HUBS" section: a collapsible folder tree (root hubs, their sub-hubs and pages).
|
||||
/// Always visible, with a "+" to create a hub; root hubs start expanded.
|
||||
class HubsSection extends StatefulWidget {
|
||||
const HubsSection({super.key, required this.onOpen, this.selectedId});
|
||||
final void Function(String id) onOpen;
|
||||
final String? selectedId;
|
||||
|
||||
@override
|
||||
State<HubsSection> createState() => _HubsSectionState();
|
||||
}
|
||||
|
||||
class _HubsSectionState extends State<HubsSection> {
|
||||
HubsDto? _data;
|
||||
Map<String, HubDto> _byId = const {};
|
||||
int? _generation;
|
||||
AppState? _app;
|
||||
Timer? _refresh;
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
final app = AppScope.of(context);
|
||||
if (_app != app) {
|
||||
_app?.queue.revision.removeListener(_edited);
|
||||
_app = app..queue.revision.addListener(_edited);
|
||||
}
|
||||
if (_generation != app.generation) {
|
||||
_generation = app.generation;
|
||||
_load();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_refresh?.cancel();
|
||||
_app?.queue.revision.removeListener(_edited);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _edited() {
|
||||
_refresh?.cancel();
|
||||
_refresh = Timer(const Duration(milliseconds: 1500), _load);
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
final app = _app;
|
||||
if (app == null) return;
|
||||
try {
|
||||
final d = await app.backend.hubs();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_data = d;
|
||||
_byId = {for (final h in d.hubs) h.id: h};
|
||||
});
|
||||
} catch (e) {
|
||||
debugPrint('hubs load failed: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _create() async {
|
||||
final app = AppScope.read(context);
|
||||
final hub = await showNameDialog<PageDto>(
|
||||
context,
|
||||
heading: 'New hub',
|
||||
confirm: 'Create',
|
||||
submit: (t) =>
|
||||
app.queue.run(() => app.backend.createHub(t, ''), report: false),
|
||||
);
|
||||
if (hub == null) return;
|
||||
app.reload();
|
||||
app.openId(hub.id);
|
||||
}
|
||||
|
||||
void _toggle(String id) {
|
||||
final open = AppScope.read(context).expandedHubs;
|
||||
setState(() => open.contains(id) ? open.remove(id) : open.add(id));
|
||||
}
|
||||
|
||||
/// Rows of a hub's subtree. `path` holds the hubs above, which guards against cycles.
|
||||
void _rows(
|
||||
List<Widget> out,
|
||||
HubDto hub,
|
||||
int depth,
|
||||
Set<String> path,
|
||||
Set<String> open,
|
||||
) {
|
||||
final expanded = open.contains(hub.id);
|
||||
// Keys use the full path: a sub-hub can sit in several hubs.
|
||||
final inner = {...path, hub.id};
|
||||
final at = inner.join('/');
|
||||
out.add(
|
||||
_TreeRow(
|
||||
key: ValueKey('hub-$at'),
|
||||
label: hub.title,
|
||||
depth: depth,
|
||||
isHub: true,
|
||||
expanded: expanded,
|
||||
selected: widget.selectedId == hub.id,
|
||||
onToggle: () => _toggle(hub.id),
|
||||
onTap: () => widget.onOpen(hub.id),
|
||||
),
|
||||
);
|
||||
if (!expanded) return;
|
||||
// Only sub-hubs are children here; notes are listed on the hub's own screen.
|
||||
for (final m in hub.members) {
|
||||
final sub = hub.subHubs.contains(m.id) ? _byId[m.id] : null;
|
||||
if (sub != null && !inner.contains(sub.id)) {
|
||||
_rows(out, sub, depth + 1, inner, open);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final data = _data;
|
||||
final open = AppScope.read(context).expandedHubs;
|
||||
final rows = <Widget>[];
|
||||
for (final id in data?.roots ?? const <String>[]) {
|
||||
final h = _byId[id];
|
||||
if (h != null) _rows(rows, h, 0, const {}, open);
|
||||
}
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 0, 20, 6),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'HUBS',
|
||||
style: Theme.of(context).textTheme.labelSmall,
|
||||
),
|
||||
),
|
||||
InkResponse(
|
||||
key: const ValueKey('new-hub'),
|
||||
radius: 12,
|
||||
onTap: _create,
|
||||
child: Icon(
|
||||
Icons.add_rounded,
|
||||
size: 16,
|
||||
color: context.colors.faint,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
...rows,
|
||||
const SizedBox(height: 22),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _TreeRow extends StatefulWidget {
|
||||
const _TreeRow({
|
||||
super.key,
|
||||
required this.label,
|
||||
required this.depth,
|
||||
required this.isHub,
|
||||
required this.selected,
|
||||
required this.onTap,
|
||||
this.expanded = false,
|
||||
this.onToggle,
|
||||
});
|
||||
final String label;
|
||||
final int depth;
|
||||
final bool isHub;
|
||||
final bool expanded;
|
||||
final bool selected;
|
||||
final VoidCallback onTap;
|
||||
|
||||
/// Non-null for hubs that can be expanded.
|
||||
final VoidCallback? onToggle;
|
||||
|
||||
@override
|
||||
State<_TreeRow> createState() => _TreeRowState();
|
||||
}
|
||||
|
||||
class _TreeRowState extends State<_TreeRow> {
|
||||
bool _hover = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = context.colors;
|
||||
final active = widget.selected;
|
||||
final toggle = widget.onToggle;
|
||||
return MouseRegion(
|
||||
cursor: SystemMouseCursors.click,
|
||||
onEnter: (_) => setState(() => _hover = true),
|
||||
onExit: (_) => setState(() => _hover = false),
|
||||
child: Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 1),
|
||||
padding: EdgeInsets.only(left: 4.0 + 14 * widget.depth, right: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: active
|
||||
? colors.accentSoft
|
||||
: _hover
|
||||
? colors.line.withAlpha(0x66)
|
||||
: null,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 22,
|
||||
height: 28,
|
||||
child: toggle == null
|
||||
? null
|
||||
: GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: toggle,
|
||||
child: Icon(
|
||||
widget.expanded
|
||||
? Icons.expand_more_rounded
|
||||
: Icons.chevron_right_rounded,
|
||||
size: 16,
|
||||
color: colors.faint,
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: widget.onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
widget.isHub
|
||||
? (widget.expanded
|
||||
? Icons.folder_open_outlined
|
||||
: Icons.folder_outlined)
|
||||
: Icons.description_outlined,
|
||||
size: 14,
|
||||
color: active ? colors.accent : colors.faint,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
widget.label,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: active
|
||||
? FontWeight.w600
|
||||
: FontWeight.w500,
|
||||
color: active ? colors.ink : colors.muted,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,11 @@ import '../state/outline_controller.dart';
|
||||
import '../theme/theme.dart';
|
||||
import '../widgets/common.dart';
|
||||
import '../widgets/dates.dart';
|
||||
import '../widgets/pickers.dart';
|
||||
import '../widgets/tags.dart';
|
||||
import 'convert_dialog.dart';
|
||||
import 'graph_view.dart';
|
||||
import 'hub_screen.dart';
|
||||
import 'journals_view.dart';
|
||||
|
||||
/// A single page: title, aliases, outline, linked references and related notes.
|
||||
@@ -24,6 +28,8 @@ class _PageScreenState extends State<PageScreen> {
|
||||
OutlineController? _outline;
|
||||
List<BacklinkGroup>? _backlinks;
|
||||
List<RelatedDto>? _related;
|
||||
PageStructure? _structure;
|
||||
Map<String, int> _hubSizes = const {};
|
||||
Object? _error;
|
||||
|
||||
@override
|
||||
@@ -69,6 +75,8 @@ class _PageScreenState extends State<PageScreen> {
|
||||
app.pageShown(view.page);
|
||||
// Make sure pending writes (e.g. a link just typed elsewhere) are visible.
|
||||
await app.queue.idle;
|
||||
if (view.page.journalDate == null) await _loadStructure();
|
||||
if (view.page.isHub) return;
|
||||
final results = await Future.wait([
|
||||
app.backend.backlinks(view.page.id),
|
||||
app.backend.related(view.page.id),
|
||||
@@ -83,6 +91,27 @@ class _PageScreenState extends State<PageScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Hub and namespace context of the page (not shown for journals).
|
||||
Future<void> _loadStructure() async {
|
||||
final app = AppScope.read(context);
|
||||
final id = _view!.page.id;
|
||||
try {
|
||||
final st = await app.backend.pageStructure(id);
|
||||
var sizes = const <String, int>{};
|
||||
if (st.isHub && st.members.any((m) => m.isHub)) {
|
||||
final hubs = await app.backend.hubs();
|
||||
sizes = {for (final h in hubs.hubs) h.id: h.members.length};
|
||||
}
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_structure = st;
|
||||
_hubSizes = sizes;
|
||||
});
|
||||
} catch (e) {
|
||||
debugPrint('page structure failed: $e');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_error != null) {
|
||||
@@ -92,10 +121,20 @@ class _PageScreenState extends State<PageScreen> {
|
||||
}
|
||||
final view = _view;
|
||||
if (view == null) return const SizedBox.shrink();
|
||||
if (view.page.isHub) {
|
||||
return HubScreen(
|
||||
page: view.page,
|
||||
aliases: view.aliases,
|
||||
structure: _structure,
|
||||
hubSizes: _hubSizes,
|
||||
);
|
||||
}
|
||||
return LayoutBuilder(
|
||||
builder: (context, box) {
|
||||
final wide = box.maxWidth >= 1180;
|
||||
final mainWidth = wide ? box.maxWidth - 300 : box.maxWidth;
|
||||
final open = AppScope.of(context).pageSidebar;
|
||||
final wide = box.maxWidth >= 900;
|
||||
final side = open && wide;
|
||||
final mainWidth = side ? box.maxWidth - 300 : box.maxWidth;
|
||||
final pad = sidePadding(mainWidth);
|
||||
final scroll = CustomScrollView(
|
||||
slivers: [
|
||||
@@ -104,12 +143,18 @@ class _PageScreenState extends State<PageScreen> {
|
||||
padding: EdgeInsets.symmetric(horizontal: pad),
|
||||
sliver: SliverMainAxisGroup(
|
||||
slivers: [
|
||||
SliverToBoxAdapter(child: _Header(view: view)),
|
||||
SliverToBoxAdapter(
|
||||
child: _Header(view: view, structure: _structure),
|
||||
),
|
||||
if (_structure != null)
|
||||
SliverToBoxAdapter(
|
||||
child: _NamespaceSection(structure: _structure!),
|
||||
),
|
||||
OutlineSliver(controller: _outline!),
|
||||
SliverToBoxAdapter(
|
||||
child: _LinkedReferences(groups: _backlinks),
|
||||
),
|
||||
if (!wide) ...[
|
||||
if (open && !wide) ...[
|
||||
SliverToBoxAdapter(child: RelatedPanel(related: _related)),
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
@@ -124,7 +169,7 @@ class _PageScreenState extends State<PageScreen> {
|
||||
),
|
||||
],
|
||||
);
|
||||
if (!wide) return scroll;
|
||||
if (!side) return scroll;
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
@@ -154,8 +199,9 @@ class _PageScreenState extends State<PageScreen> {
|
||||
}
|
||||
|
||||
class _Header extends StatelessWidget {
|
||||
const _Header({required this.view});
|
||||
const _Header({required this.view, required this.structure});
|
||||
final PageData view;
|
||||
final PageStructure? structure;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -185,13 +231,38 @@ class _Header extends StatelessWidget {
|
||||
],
|
||||
),
|
||||
] else ...[
|
||||
_TitleField(page: page),
|
||||
if (structure != null && structure!.nsPath.isNotEmpty) ...[
|
||||
Breadcrumb(path: structure!.nsPath),
|
||||
const SizedBox(height: 6),
|
||||
],
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(child: TitleField(page: page)),
|
||||
IconButton(
|
||||
key: const ValueKey('page-sidebar-toggle'),
|
||||
tooltip: AppScope.of(context).pageSidebar
|
||||
? 'Hide graph sidebar'
|
||||
: 'Show graph sidebar',
|
||||
visualDensity: VisualDensity.compact,
|
||||
iconSize: 20,
|
||||
color: AppScope.of(context).pageSidebar
|
||||
? colors.accent
|
||||
: colors.muted,
|
||||
icon: const Icon(Icons.view_sidebar_outlined),
|
||||
onPressed: AppScope.read(context).togglePageSidebar,
|
||||
),
|
||||
PageMenu(page: page, structure: structure),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Wrap(
|
||||
spacing: 14,
|
||||
runSpacing: 4,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
if (structure != null && structure!.inHubs.isNotEmpty)
|
||||
InHubs(pageId: page.id, hubs: structure!.inHubs),
|
||||
if (page.originJournal != null)
|
||||
TextLink(
|
||||
'Born ${longDate(page.originJournal!)}',
|
||||
@@ -202,6 +273,9 @@ class _Header extends StatelessWidget {
|
||||
_Aliases(page: page, initial: view.aliases),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TagBar(page: page),
|
||||
if (page.isTag) TaggedNotes(tag: page.title),
|
||||
],
|
||||
],
|
||||
),
|
||||
@@ -210,15 +284,15 @@ class _Header extends StatelessWidget {
|
||||
}
|
||||
|
||||
/// Page title; editing it renames the page (and rewrites every link to it).
|
||||
class _TitleField extends StatefulWidget {
|
||||
const _TitleField({required this.page});
|
||||
class TitleField extends StatefulWidget {
|
||||
const TitleField({super.key, required this.page});
|
||||
final PageDto page;
|
||||
|
||||
@override
|
||||
State<_TitleField> createState() => _TitleFieldState();
|
||||
State<TitleField> createState() => TitleFieldState();
|
||||
}
|
||||
|
||||
class _TitleFieldState extends State<_TitleField> {
|
||||
class TitleFieldState extends State<TitleField> {
|
||||
late final _text = TextEditingController(text: widget.page.title);
|
||||
late final _focus = FocusNode()..addListener(_blur);
|
||||
late String _committed = widget.page.title;
|
||||
@@ -244,10 +318,12 @@ class _TitleFieldState extends State<_TitleField> {
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
try {
|
||||
await app.queue.run(() => app.backend.renamePage(widget.page.id, title));
|
||||
final old = _committed;
|
||||
_committed = title;
|
||||
app.renamed(widget.page.id, title);
|
||||
// The core rewrote links in other blocks, possibly on this page: reload them.
|
||||
app.reload();
|
||||
// The core rewrote links in other blocks, possibly on this page: reload them. The
|
||||
// route must not keep opening the old title (that would create a duplicate page).
|
||||
app.replaceWithId(widget.page.id, old);
|
||||
} catch (e) {
|
||||
_text.text = _committed;
|
||||
messenger.showSnackBar(SnackBar(content: Text('Rename failed: $e')));
|
||||
@@ -494,3 +570,248 @@ class RelatedPanel extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Namespace ancestors of the page, `A / B` above the title. Segments open their page
|
||||
/// (virtual ones are created on open, like links).
|
||||
class Breadcrumb extends StatelessWidget {
|
||||
const Breadcrumb({super.key, required this.path});
|
||||
final List<NamespaceEntry> path;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = context.colors;
|
||||
final app = AppScope.read(context);
|
||||
return Wrap(
|
||||
spacing: 6,
|
||||
runSpacing: 2,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.account_tree_outlined, size: 14, color: colors.faint),
|
||||
for (var i = 0; i < path.length; i++) ...[
|
||||
if (i > 0)
|
||||
Text('/', style: TextStyle(fontSize: 12, color: colors.faint)),
|
||||
TextLink(
|
||||
path[i].title.split('/').last,
|
||||
onTap: () => path[i].id != null
|
||||
? app.openId(path[i].id!)
|
||||
: app.openTitle(path[i].title),
|
||||
style: const TextStyle(fontSize: 12.5),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// "In: hub, hub" chips for the hubs containing the page; each has a remove button.
|
||||
class InHubs extends StatelessWidget {
|
||||
const InHubs({super.key, required this.pageId, required this.hubs});
|
||||
final String pageId;
|
||||
final List<PageBrief> hubs;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = context.colors;
|
||||
final app = AppScope.read(context);
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 4,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
Text('In', style: TextStyle(fontSize: 12, color: colors.faint)),
|
||||
for (final h in hubs)
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
TextLink(
|
||||
h.title,
|
||||
icon: Icons.folder_outlined,
|
||||
onTap: () => app.openId(h.id),
|
||||
style: const TextStyle(fontSize: 12),
|
||||
),
|
||||
InkResponse(
|
||||
key: ValueKey('leave-${h.id}'),
|
||||
radius: 10,
|
||||
onTap: () async {
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
try {
|
||||
await app.queue.run(
|
||||
() => app.backend.removeFromHub(pageId, h.id),
|
||||
report: false,
|
||||
);
|
||||
app.reload();
|
||||
} catch (e) {
|
||||
messenger.showSnackBar(
|
||||
SnackBar(content: Text(errorText(e))),
|
||||
);
|
||||
}
|
||||
},
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(3),
|
||||
child: Icon(
|
||||
Icons.close_rounded,
|
||||
size: 12,
|
||||
color: colors.faint,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The page's "⋯" menu: hub conversion and hub membership.
|
||||
class PageMenu extends StatelessWidget {
|
||||
const PageMenu({super.key, required this.page, required this.structure});
|
||||
final PageDto page;
|
||||
final PageStructure? structure;
|
||||
|
||||
Future<void> _addToHub(BuildContext context) async {
|
||||
final app = AppScope.read(context);
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
final taken = {page.id, ...?structure?.inHubs.map((h) => h.id)};
|
||||
final r = await showPagePicker(
|
||||
context,
|
||||
heading: 'Add to hub',
|
||||
canCreateHub: true,
|
||||
search: (q) async {
|
||||
final all = await app.backend.hubs();
|
||||
return [
|
||||
for (final h in all.hubs)
|
||||
if (!taken.contains(h.id) &&
|
||||
h.title.toLowerCase().contains(q.toLowerCase()))
|
||||
PickItem(id: h.id, title: h.title, isHub: true),
|
||||
];
|
||||
},
|
||||
);
|
||||
if (r == null) return;
|
||||
try {
|
||||
await app.queue.run(() async {
|
||||
final id =
|
||||
r.item?.id ?? (await app.backend.createHub(r.newTitle!, '')).id;
|
||||
await app.backend.addToHub(page.id, id);
|
||||
}, report: false);
|
||||
app.reload();
|
||||
} catch (e) {
|
||||
messenger.showSnackBar(SnackBar(content: Text(errorText(e))));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _toHub(BuildContext context) async {
|
||||
final app = AppScope.read(context);
|
||||
final ok = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (_) => ConvertToHubDialog(page: page),
|
||||
);
|
||||
if (ok == true) {
|
||||
app.recent.removeWhere((p) => p.id == page.id);
|
||||
app.replaceWithId(page.id, page.title);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _toNote(BuildContext context) async {
|
||||
final app = AppScope.read(context);
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
try {
|
||||
await app.queue.run(
|
||||
() => app.backend.convertToNote(page.id),
|
||||
report: false,
|
||||
);
|
||||
app.reload();
|
||||
} catch (e) {
|
||||
messenger.showSnackBar(SnackBar(content: Text(errorText(e))));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => PopupMenuButton<String>(
|
||||
key: const ValueKey('page-menu'),
|
||||
icon: Icon(Icons.more_horiz_rounded, color: context.colors.faint),
|
||||
tooltip: 'More',
|
||||
onSelected: (v) => switch (v) {
|
||||
'hub' => _toHub(context),
|
||||
'note' => _toNote(context),
|
||||
_ => _addToHub(context),
|
||||
},
|
||||
itemBuilder: (_) => [
|
||||
if (!page.isHub)
|
||||
const PopupMenuItem(value: 'hub', child: Text('Convert to hub…')),
|
||||
if (page.isHub)
|
||||
const PopupMenuItem(value: 'note', child: Text('Convert to note')),
|
||||
const PopupMenuItem(value: 'add', child: Text('Add to hub…')),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// "Namespace" listing (title-kin children) under the header.
|
||||
class _NamespaceSection extends StatelessWidget {
|
||||
const _NamespaceSection({required this.structure});
|
||||
final PageStructure structure;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = context.colors;
|
||||
final app = AppScope.read(context);
|
||||
final st = structure;
|
||||
if (st.nsChildren.isEmpty) return const SizedBox.shrink();
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 18),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SectionLabel(
|
||||
'Namespace',
|
||||
trailing: Text(
|
||||
'${st.nsChildren.length}',
|
||||
style: TextStyle(fontSize: 11, color: colors.faint),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
children: [
|
||||
for (final c in st.nsChildren)
|
||||
SizedBox(
|
||||
width: 230,
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
onTap: () => c.id != null
|
||||
? app.openId(c.id!)
|
||||
: app.openTitle(c.title),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8,
|
||||
vertical: 6,
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.account_tree_outlined,
|
||||
size: 16,
|
||||
color: colors.accent.withAlpha(0xCC),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
c.title.split('/').last,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 13.5,
|
||||
color: colors.ink,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../state/app_state.dart';
|
||||
import '../state/keymap.dart';
|
||||
import '../theme/theme.dart';
|
||||
import '../widgets/common.dart';
|
||||
|
||||
/// Theme picker and key bindings.
|
||||
class SettingsView extends StatelessWidget {
|
||||
const SettingsView({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final app = AppScope.of(context);
|
||||
final colors = context.colors;
|
||||
return LayoutBuilder(
|
||||
builder: (context, box) => ListView(
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
sidePadding(box.maxWidth),
|
||||
36,
|
||||
sidePadding(box.maxWidth),
|
||||
80,
|
||||
),
|
||||
children: [
|
||||
Text('Settings', style: Theme.of(context).textTheme.headlineLarge),
|
||||
const SizedBox(height: 28),
|
||||
_Heading('Theme'),
|
||||
Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 12,
|
||||
children: [
|
||||
_ThemeCard(
|
||||
id: autoThemeId,
|
||||
label: 'System',
|
||||
swatch: [
|
||||
SynapseColors.light.paper,
|
||||
SynapseColors.dark.paper,
|
||||
SynapseColors.light.accent,
|
||||
SynapseColors.dark.accent,
|
||||
],
|
||||
selected: app.themeId == autoThemeId,
|
||||
),
|
||||
for (final t in appThemes)
|
||||
_ThemeCard(
|
||||
id: t.id,
|
||||
label: t.label,
|
||||
swatch: [
|
||||
t.colors.paper,
|
||||
t.colors.surface,
|
||||
t.colors.accent,
|
||||
t.colors.ref,
|
||||
],
|
||||
selected: app.themeId == t.id,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 36),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: _Heading('Keyboard shortcuts')),
|
||||
TextLink(
|
||||
'Reset all',
|
||||
icon: Icons.restart_alt_rounded,
|
||||
onTap: () => app.resetKey(null),
|
||||
),
|
||||
],
|
||||
),
|
||||
Text(
|
||||
'Click a shortcut, then press the new combination. Esc cancels.',
|
||||
style: TextStyle(fontSize: 13, color: colors.muted),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
for (final editor in [false, true]) ...[
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 14, bottom: 4),
|
||||
child: Text(
|
||||
editor ? 'EDITOR' : 'APP',
|
||||
style: Theme.of(context).textTheme.labelSmall,
|
||||
),
|
||||
),
|
||||
for (final a in AppAction.values.where((a) => a.editor == editor))
|
||||
_BindingRow(action: a),
|
||||
],
|
||||
const SizedBox(height: 28),
|
||||
Text(
|
||||
'Type "/" in a block for commands (link, bold, headings, todo, ...). '
|
||||
'Prefix a character with a backslash to show it literally: \\*not italic\\*.',
|
||||
style: TextStyle(fontSize: 13, color: colors.muted),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Heading extends StatelessWidget {
|
||||
const _Heading(this.text);
|
||||
final String text;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: Text(text, style: Theme.of(context).textTheme.headlineSmall),
|
||||
);
|
||||
}
|
||||
|
||||
class _ThemeCard extends StatelessWidget {
|
||||
const _ThemeCard({
|
||||
required this.id,
|
||||
required this.label,
|
||||
required this.swatch,
|
||||
required this.selected,
|
||||
});
|
||||
|
||||
final String id;
|
||||
final String label;
|
||||
final List<Color> swatch;
|
||||
final bool selected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = context.colors;
|
||||
return InkWell(
|
||||
key: ValueKey('theme-$id'),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
onTap: () => AppScope.read(context).setTheme(id),
|
||||
child: Container(
|
||||
width: 132,
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(
|
||||
color: selected ? colors.accent : colors.line,
|
||||
width: selected ? 2 : 1,
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
child: Row(
|
||||
children: [
|
||||
for (final c in swatch)
|
||||
Expanded(child: Container(height: 28, color: c)),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: selected ? FontWeight.w600 : FontWeight.w400,
|
||||
color: colors.ink,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _BindingRow extends StatefulWidget {
|
||||
const _BindingRow({required this.action});
|
||||
final AppAction action;
|
||||
|
||||
@override
|
||||
State<_BindingRow> createState() => _BindingRowState();
|
||||
}
|
||||
|
||||
class _BindingRowState extends State<_BindingRow> {
|
||||
final _focus = FocusNode();
|
||||
bool _listening = false;
|
||||
String? _conflict;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_focus.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
KeyEventResult _onKey(FocusNode _, KeyEvent e) {
|
||||
if (!_listening || e is! KeyDownEvent) return KeyEventResult.ignored;
|
||||
if (e.logicalKey == LogicalKeyboardKey.escape) {
|
||||
setState(() => _listening = false);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
final kb = HardwareKeyboard.instance;
|
||||
final combo = Combo(
|
||||
e.logicalKey,
|
||||
ctrl: kb.isControlPressed || kb.isMetaPressed,
|
||||
shift: kb.isShiftPressed,
|
||||
alt: kb.isAltPressed,
|
||||
);
|
||||
if (combo.isModifierOnly) return KeyEventResult.handled;
|
||||
final owner = AppScope.read(context).bindKey(widget.action, combo);
|
||||
setState(() {
|
||||
_listening = false;
|
||||
_conflict = owner == null ? null : 'Already used by "${owner.label}"';
|
||||
});
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final app = AppScope.of(context);
|
||||
final colors = context.colors;
|
||||
final a = widget.action;
|
||||
return Focus(
|
||||
focusNode: _focus,
|
||||
onKeyEvent: _onKey,
|
||||
onFocusChange: (f) {
|
||||
if (!f && _listening) setState(() => _listening = false);
|
||||
},
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 3),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
a.label,
|
||||
style: TextStyle(fontSize: 14, color: colors.ink),
|
||||
),
|
||||
),
|
||||
if (_conflict != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 12),
|
||||
child: Text(
|
||||
_conflict!,
|
||||
style: TextStyle(fontSize: 12, color: colors.ref),
|
||||
),
|
||||
),
|
||||
OutlinedButton(
|
||||
key: ValueKey('bind-${a.name}'),
|
||||
style: OutlinedButton.styleFrom(
|
||||
minimumSize: const Size(120, 32),
|
||||
side: BorderSide(
|
||||
color: _listening ? colors.accent : colors.line,
|
||||
),
|
||||
foregroundColor: colors.ink,
|
||||
),
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_listening = true;
|
||||
_conflict = null;
|
||||
});
|
||||
_focus.requestFocus();
|
||||
},
|
||||
child: Text(
|
||||
_listening ? 'Press keys…' : app.keymap.of(a).label,
|
||||
style: TextStyle(
|
||||
fontSize: 12.5,
|
||||
color: app.keymap.isCustom(a) ? colors.accent : colors.ink,
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'Reset',
|
||||
iconSize: 16,
|
||||
visualDensity: VisualDensity.compact,
|
||||
color: colors.faint,
|
||||
onPressed: app.keymap.isCustom(a) ? () => app.resetKey(a) : null,
|
||||
icon: const Icon(Icons.restart_alt_rounded),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,17 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../state/app_state.dart';
|
||||
import '../state/keymap.dart';
|
||||
import '../theme/theme.dart';
|
||||
import '../widgets/dates.dart';
|
||||
import 'all_pages_view.dart';
|
||||
import 'journals_view.dart';
|
||||
import 'page_screen.dart';
|
||||
import 'hubs_tree.dart';
|
||||
import 'quick_switcher.dart';
|
||||
import 'graph_view.dart';
|
||||
import 'settings_view.dart';
|
||||
|
||||
/// App frame: sidebar (navigation, recents, theme), top bar and the current view.
|
||||
class Shell extends StatefulWidget {
|
||||
@@ -39,39 +42,21 @@ class _ShellState extends State<Shell> {
|
||||
);
|
||||
});
|
||||
}
|
||||
final actions = <AppAction, VoidCallback>{
|
||||
AppAction.quickSwitcher: () => showQuickSwitcher(context),
|
||||
AppAction.journals: () => app.go(const JournalsRoute()),
|
||||
AppAction.graph: () => app.go(const GraphRoute(GraphMode.network)),
|
||||
AppAction.timeline: () => app.go(const TimelineRoute()),
|
||||
AppAction.sidebar: () => setState(() => _sidebar = !_sidebar),
|
||||
AppAction.pageSidebar: app.togglePageSidebar,
|
||||
AppAction.settings: () => app.go(const SettingsRoute()),
|
||||
AppAction.back: app.back,
|
||||
AppAction.forward: app.forward,
|
||||
};
|
||||
return CallbackShortcuts(
|
||||
bindings: {
|
||||
const SingleActivator(LogicalKeyboardKey.keyK, control: true): () =>
|
||||
showQuickSwitcher(context),
|
||||
const SingleActivator(LogicalKeyboardKey.keyK, meta: true): () =>
|
||||
showQuickSwitcher(context),
|
||||
const SingleActivator(
|
||||
LogicalKeyboardKey.keyJ,
|
||||
control: true,
|
||||
shift: true,
|
||||
): () =>
|
||||
app.go(const JournalsRoute()),
|
||||
const SingleActivator(
|
||||
LogicalKeyboardKey.keyG,
|
||||
control: true,
|
||||
shift: true,
|
||||
): () =>
|
||||
app.go(const GraphRoute(GraphMode.network)),
|
||||
const SingleActivator(
|
||||
LogicalKeyboardKey.keyT,
|
||||
control: true,
|
||||
shift: true,
|
||||
): () =>
|
||||
app.go(const TimelineRoute()),
|
||||
const SingleActivator(
|
||||
LogicalKeyboardKey.backslash,
|
||||
control: true,
|
||||
): () =>
|
||||
setState(() => _sidebar = !_sidebar),
|
||||
const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true):
|
||||
app.back,
|
||||
const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true):
|
||||
app.forward,
|
||||
for (final e in actions.entries)
|
||||
...Map.fromEntries(activators(app.keymap.of(e.key), e.value)),
|
||||
},
|
||||
child: Focus(
|
||||
autofocus: true,
|
||||
@@ -125,6 +110,7 @@ class _ShellState extends State<Shell> {
|
||||
focusId: route.focusId,
|
||||
),
|
||||
AllPagesRoute() => const AllPagesView(),
|
||||
SettingsRoute() => const SettingsView(),
|
||||
PageTarget() => PageScreen(target: route),
|
||||
},
|
||||
),
|
||||
@@ -164,15 +150,19 @@ class _TopBar extends StatelessWidget {
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
icon(Icons.menu_rounded, 'Toggle sidebar (Ctrl+\\)', onMenu),
|
||||
icon(
|
||||
Icons.menu_rounded,
|
||||
'Toggle sidebar (${app.keymap.of(AppAction.sidebar).label})',
|
||||
onMenu,
|
||||
),
|
||||
icon(
|
||||
Icons.arrow_back_rounded,
|
||||
'Back (Alt+←)',
|
||||
'Back (${app.keymap.of(AppAction.back).label})',
|
||||
app.canGoBack ? app.back : null,
|
||||
),
|
||||
icon(
|
||||
Icons.arrow_forward_rounded,
|
||||
'Forward (Alt+→)',
|
||||
'Forward (${app.keymap.of(AppAction.forward).label})',
|
||||
app.canGoForward ? app.forward : null,
|
||||
),
|
||||
const Spacer(),
|
||||
@@ -214,7 +204,10 @@ class _SearchPill extends StatelessWidget {
|
||||
const SizedBox(width: 8),
|
||||
Text('Search', style: TextStyle(fontSize: 13, color: colors.muted)),
|
||||
const SizedBox(width: 18),
|
||||
Text('Ctrl K', style: TextStyle(fontSize: 11, color: colors.faint)),
|
||||
Text(
|
||||
AppScope.of(context).keymap.of(AppAction.quickSwitcher).label,
|
||||
style: TextStyle(fontSize: 11, color: colors.faint),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -275,31 +268,34 @@ class _Sidebar extends StatelessWidget {
|
||||
selected: route is GraphRoute,
|
||||
onTap: () => go(const GraphRoute(GraphMode.network)),
|
||||
),
|
||||
_NavItem(
|
||||
icon: Icons.timeline_rounded,
|
||||
label: 'Timeline',
|
||||
selected: route is TimelineRoute,
|
||||
onTap: () => go(const TimelineRoute()),
|
||||
),
|
||||
_NavItem(
|
||||
icon: Icons.description_outlined,
|
||||
label: 'All pages',
|
||||
selected: route is AllPagesRoute,
|
||||
onTap: () => go(const AllPagesRoute()),
|
||||
),
|
||||
const SizedBox(height: 22),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20),
|
||||
child: Text(
|
||||
'RECENT',
|
||||
style: Theme.of(context).textTheme.labelSmall,
|
||||
),
|
||||
_NavItem(
|
||||
icon: Icons.settings_outlined,
|
||||
label: 'Settings',
|
||||
selected: route is SettingsRoute,
|
||||
onTap: () => go(const SettingsRoute()),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
const SizedBox(height: 22),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
padding: EdgeInsets.zero,
|
||||
children: [
|
||||
HubsSection(
|
||||
selectedId: route is PageTarget ? route.id : null,
|
||||
onOpen: (id) => go(PageTarget(id: id)),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 0, 20, 6),
|
||||
child: Text(
|
||||
'RECENT',
|
||||
style: Theme.of(context).textTheme.labelSmall,
|
||||
),
|
||||
),
|
||||
for (final p in app.recent)
|
||||
_NavItem(
|
||||
label: p.isJournal ? longDate(p.title) : p.title,
|
||||
@@ -418,3 +414,29 @@ class _Logo extends CustomPainter {
|
||||
@override
|
||||
bool shouldRepaint(_Logo old) => old.color != color;
|
||||
}
|
||||
|
||||
/// The shortcut activators for `combo` (Ctrl also answers to Cmd on macOS).
|
||||
List<MapEntry<ShortcutActivator, VoidCallback>> activators(
|
||||
Combo combo,
|
||||
VoidCallback run,
|
||||
) => [
|
||||
MapEntry(
|
||||
SingleActivator(
|
||||
combo.key,
|
||||
control: combo.ctrl,
|
||||
shift: combo.shift,
|
||||
alt: combo.alt,
|
||||
),
|
||||
run,
|
||||
),
|
||||
if (combo.ctrl && defaultTargetPlatform == TargetPlatform.macOS)
|
||||
MapEntry(
|
||||
SingleActivator(
|
||||
combo.key,
|
||||
meta: true,
|
||||
shift: combo.shift,
|
||||
alt: combo.alt,
|
||||
),
|
||||
run,
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,251 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../theme/theme.dart';
|
||||
|
||||
/// A page offered by [showPagePicker].
|
||||
class PickItem {
|
||||
const PickItem({required this.id, required this.title, this.isHub = false});
|
||||
final String id;
|
||||
final String title;
|
||||
final bool isHub;
|
||||
}
|
||||
|
||||
/// The outcome of [showPagePicker]: an existing page, or a title to create.
|
||||
class PickResult {
|
||||
const PickResult.existing(PickItem this.item)
|
||||
: newTitle = null,
|
||||
newHub = false;
|
||||
const PickResult.create(String this.newTitle, {required this.newHub})
|
||||
: item = null;
|
||||
final PickItem? item;
|
||||
final String? newTitle;
|
||||
final bool newHub;
|
||||
}
|
||||
|
||||
/// Search-as-you-type page picker. [search] returns candidates for the query (empty
|
||||
/// query included). Creation rows are offered for a non-empty query without an exact match.
|
||||
Future<PickResult?> showPagePicker(
|
||||
BuildContext context, {
|
||||
required String heading,
|
||||
required Future<List<PickItem>> Function(String query) search,
|
||||
bool canCreateNote = false,
|
||||
bool canCreateHub = false,
|
||||
}) => showDialog<PickResult>(
|
||||
context: context,
|
||||
builder: (_) => _PagePicker(
|
||||
heading: heading,
|
||||
search: search,
|
||||
canCreateNote: canCreateNote,
|
||||
canCreateHub: canCreateHub,
|
||||
),
|
||||
);
|
||||
|
||||
class _PagePicker extends StatefulWidget {
|
||||
const _PagePicker({
|
||||
required this.heading,
|
||||
required this.search,
|
||||
required this.canCreateNote,
|
||||
required this.canCreateHub,
|
||||
});
|
||||
final String heading;
|
||||
final Future<List<PickItem>> Function(String) search;
|
||||
final bool canCreateNote;
|
||||
final bool canCreateHub;
|
||||
|
||||
@override
|
||||
State<_PagePicker> createState() => _PagePickerState();
|
||||
}
|
||||
|
||||
class _PagePickerState extends State<_PagePicker> {
|
||||
final _text = TextEditingController();
|
||||
List<PickItem> _items = const [];
|
||||
int _seq = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_query('');
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_text.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _query(String q) async {
|
||||
final n = ++_seq;
|
||||
final r = await widget.search(q.trim());
|
||||
if (mounted && n == _seq) setState(() => _items = r);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = context.colors;
|
||||
final q = _text.text.trim();
|
||||
final exact = _items.any((i) => i.title.toLowerCase() == q.toLowerCase());
|
||||
final create = q.isNotEmpty && !exact;
|
||||
Widget row(IconData icon, String label, VoidCallback onTap, {Key? key}) =>
|
||||
ListTile(
|
||||
key: key,
|
||||
dense: true,
|
||||
leading: Icon(icon, size: 18, color: colors.accent),
|
||||
title: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
onTap: onTap,
|
||||
);
|
||||
return AlertDialog(
|
||||
title: Text(widget.heading),
|
||||
content: SizedBox(
|
||||
width: 420,
|
||||
height: 380,
|
||||
child: Column(
|
||||
children: [
|
||||
TextField(
|
||||
controller: _text,
|
||||
autofocus: true,
|
||||
decoration: const InputDecoration(hintText: 'Search pages'),
|
||||
onChanged: _query,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
children: [
|
||||
if (create && widget.canCreateNote)
|
||||
row(
|
||||
Icons.add_rounded,
|
||||
'Create note "$q"',
|
||||
() => Navigator.pop(
|
||||
context,
|
||||
PickResult.create(q, newHub: false),
|
||||
),
|
||||
),
|
||||
if (create && widget.canCreateHub)
|
||||
row(
|
||||
Icons.create_new_folder_outlined,
|
||||
'Create hub "$q"',
|
||||
() => Navigator.pop(
|
||||
context,
|
||||
PickResult.create(q, newHub: true),
|
||||
),
|
||||
),
|
||||
for (final i in _items)
|
||||
row(
|
||||
i.isHub
|
||||
? Icons.folder_outlined
|
||||
: Icons.description_outlined,
|
||||
i.title,
|
||||
() => Navigator.pop(context, PickResult.existing(i)),
|
||||
key: ValueKey('pick-${i.id}'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks for a name. [submit] runs on confirm; when it throws, the message is shown inline
|
||||
/// and the dialog stays open. Returns what [submit] returned.
|
||||
Future<T?> showNameDialog<T>(
|
||||
BuildContext context, {
|
||||
required String heading,
|
||||
required String confirm,
|
||||
required Future<T> Function(String name) submit,
|
||||
String hint = 'Title',
|
||||
}) => showDialog<T>(
|
||||
context: context,
|
||||
builder: (_) => _NameDialog<T>(
|
||||
heading: heading,
|
||||
confirm: confirm,
|
||||
submit: submit,
|
||||
hint: hint,
|
||||
),
|
||||
);
|
||||
|
||||
class _NameDialog<T> extends StatefulWidget {
|
||||
const _NameDialog({
|
||||
required this.heading,
|
||||
required this.confirm,
|
||||
required this.submit,
|
||||
required this.hint,
|
||||
});
|
||||
final String heading;
|
||||
final String confirm;
|
||||
final String hint;
|
||||
final Future<T> Function(String) submit;
|
||||
|
||||
@override
|
||||
State<_NameDialog<T>> createState() => _NameDialogState<T>();
|
||||
}
|
||||
|
||||
class _NameDialogState<T> extends State<_NameDialog<T>> {
|
||||
final _text = TextEditingController();
|
||||
String? _error;
|
||||
bool _busy = false;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_text.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _go() async {
|
||||
final name = _text.text.trim();
|
||||
if (name.isEmpty || _busy) return;
|
||||
setState(() {
|
||||
_busy = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final r = await widget.submit(name);
|
||||
if (mounted) Navigator.pop(context, r);
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_busy = false;
|
||||
_error = errorText(e);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => AlertDialog(
|
||||
title: Text(widget.heading),
|
||||
content: SizedBox(
|
||||
width: 380,
|
||||
child: TextField(
|
||||
controller: _text,
|
||||
autofocus: true,
|
||||
decoration: InputDecoration(hintText: widget.hint, errorText: _error),
|
||||
onSubmitted: (_) => _go(),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(onPressed: _go, child: Text(widget.confirm)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// A readable message for an exception coming back from the core.
|
||||
String errorText(Object e) {
|
||||
var s = '$e';
|
||||
for (final p in ['Exception: ', 'AnyhowException(', 'PanicException(']) {
|
||||
if (s.startsWith(p)) s = s.substring(p.length);
|
||||
}
|
||||
if (s.endsWith(')') && !s.contains('(')) s = s.substring(0, s.length - 1);
|
||||
return s.trim();
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../backend/graph_backend.dart';
|
||||
import '../state/app_state.dart';
|
||||
import '../theme/theme.dart';
|
||||
import 'common.dart';
|
||||
import 'pickers.dart';
|
||||
|
||||
/// Type and tag chips of a page, each with a remove button, and "Type" / "Tag" links that open
|
||||
/// a picker. Types are plain names; tags are pages (tapping one opens it). Tag pages cannot
|
||||
/// be tagged, so they only get types.
|
||||
class TagBar extends StatelessWidget {
|
||||
const TagBar({super.key, required this.page});
|
||||
final PageDto page;
|
||||
|
||||
Future<void> _run(
|
||||
BuildContext context,
|
||||
Future<PageDto> Function(GraphBackend b) op,
|
||||
) async {
|
||||
final app = AppScope.read(context);
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
try {
|
||||
await app.queue.run(() => op(app.backend), report: false);
|
||||
app.reload();
|
||||
} catch (e) {
|
||||
messenger.showSnackBar(SnackBar(content: Text(errorText(e))));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _add(BuildContext context, {required bool type}) async {
|
||||
final app = AppScope.read(context);
|
||||
final catalog = type
|
||||
? await app.backend.typeCatalog()
|
||||
: await app.backend.tagCatalog();
|
||||
if (!context.mounted) return;
|
||||
final name = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (_) => _TagPicker(
|
||||
catalog: catalog,
|
||||
taken: type ? page.types : page.tags,
|
||||
label: type ? 'type' : 'tag',
|
||||
),
|
||||
);
|
||||
if (name == null || !context.mounted) return;
|
||||
await _run(
|
||||
context,
|
||||
(b) => type ? b.addPageType(page.id, name) : b.addPageTag(page.id, name),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _chip(
|
||||
BuildContext context,
|
||||
String keyId,
|
||||
String name, {
|
||||
VoidCallback? onTap,
|
||||
required VoidCallback onRemove,
|
||||
}) {
|
||||
final colors = context.colors;
|
||||
return Container(
|
||||
key: ValueKey(keyId),
|
||||
padding: const EdgeInsets.only(left: 9, right: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: colors.surface,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
InkWell(
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 3),
|
||||
child: Text(
|
||||
name,
|
||||
style: TextStyle(fontSize: 12, color: colors.muted),
|
||||
),
|
||||
),
|
||||
),
|
||||
InkResponse(
|
||||
key: ValueKey('un$keyId'),
|
||||
radius: 10,
|
||||
onTap: onRemove,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(4),
|
||||
child: Icon(Icons.close_rounded, size: 12, color: colors.faint),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _row(
|
||||
BuildContext context,
|
||||
IconData icon,
|
||||
String label,
|
||||
List<Widget> chips,
|
||||
Widget add,
|
||||
) {
|
||||
final colors = context.colors;
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 76,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(icon, size: 13, color: colors.faint),
|
||||
const SizedBox(width: 5),
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(fontSize: 12, color: colors.faint),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Wrap(
|
||||
spacing: 6,
|
||||
runSpacing: 6,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [...chips, add],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final app = AppScope.read(context);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_row(
|
||||
context,
|
||||
Icons.category_outlined,
|
||||
'Type',
|
||||
[
|
||||
for (final t in page.types)
|
||||
_chip(
|
||||
context,
|
||||
'type-$t',
|
||||
t,
|
||||
onRemove: () =>
|
||||
_run(context, (b) => b.removePageType(page.id, t)),
|
||||
),
|
||||
],
|
||||
TextLink(
|
||||
'+ add',
|
||||
key: const ValueKey('add-type'),
|
||||
onTap: () => _add(context, type: true),
|
||||
style: const TextStyle(fontSize: 12),
|
||||
),
|
||||
),
|
||||
if (!page.isTag) ...[
|
||||
const SizedBox(height: 6),
|
||||
_row(
|
||||
context,
|
||||
Icons.sell_outlined,
|
||||
'Tags',
|
||||
[
|
||||
for (final t in page.tags)
|
||||
_chip(
|
||||
context,
|
||||
'tag-$t',
|
||||
'#$t',
|
||||
onTap: () => app.openTitle(t),
|
||||
onRemove: () =>
|
||||
_run(context, (b) => b.removePageTag(page.id, t)),
|
||||
),
|
||||
],
|
||||
TextLink(
|
||||
'+ add',
|
||||
key: const ValueKey('add-tag'),
|
||||
onTap: () => _add(context, type: false),
|
||||
style: const TextStyle(fontSize: 12),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Notes carrying the tag page `tag`, as links under the header of the tag page.
|
||||
class TaggedNotes extends StatelessWidget {
|
||||
const TaggedNotes({super.key, required this.tag});
|
||||
final String tag;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final app = AppScope.read(context);
|
||||
final colors = context.colors;
|
||||
return FutureBuilder<List<PageBrief>>(
|
||||
future: app.backend.pagesWithTag(tag),
|
||||
builder: (context, snap) {
|
||||
final pages = snap.data ?? const <PageBrief>[];
|
||||
if (pages.isEmpty) return const SizedBox.shrink();
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: 10),
|
||||
child: Wrap(
|
||||
key: const ValueKey('tagged-notes'),
|
||||
spacing: 14,
|
||||
runSpacing: 4,
|
||||
children: [
|
||||
Text(
|
||||
'Tagged',
|
||||
style: TextStyle(fontSize: 12, color: colors.faint),
|
||||
),
|
||||
for (final p in pages)
|
||||
TextLink(
|
||||
p.title,
|
||||
icon: Icons.description_outlined,
|
||||
onTap: () => app.openId(p.id),
|
||||
style: const TextStyle(fontSize: 12),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists the pages carrying `tag`; picking one opens it.
|
||||
Future<void> showTagPages(BuildContext context, String tag) async {
|
||||
final app = AppScope.read(context);
|
||||
final pages = await app.backend.pagesWithTag(tag);
|
||||
if (!context.mounted) return;
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: Text(tag),
|
||||
content: SizedBox(
|
||||
width: 360,
|
||||
child: pages.isEmpty
|
||||
? const Text('No notes with this tag yet.')
|
||||
: ListView(
|
||||
shrinkWrap: true,
|
||||
children: [
|
||||
for (final p in pages)
|
||||
ListTile(
|
||||
dense: true,
|
||||
leading: Icon(
|
||||
p.isHub
|
||||
? Icons.folder_outlined
|
||||
: Icons.description_outlined,
|
||||
size: 18,
|
||||
),
|
||||
title: Text(p.title),
|
||||
onTap: () {
|
||||
Navigator.pop(ctx);
|
||||
app.openId(p.id);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _TagPicker extends StatefulWidget {
|
||||
const _TagPicker({
|
||||
required this.catalog,
|
||||
required this.taken,
|
||||
required this.label,
|
||||
});
|
||||
final List<TagDto> catalog;
|
||||
final List<String> taken;
|
||||
final String label;
|
||||
|
||||
@override
|
||||
State<_TagPicker> createState() => _TagPickerState();
|
||||
}
|
||||
|
||||
class _TagPickerState extends State<_TagPicker> {
|
||||
final _text = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_text.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String get _query => _text.text.trim().replaceFirst(RegExp(r'^#+'), '');
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = context.colors;
|
||||
final taken = {for (final t in widget.taken) t.toLowerCase()};
|
||||
final q = _query.toLowerCase();
|
||||
final options = [
|
||||
for (final t in widget.catalog)
|
||||
if (!taken.contains(t.name.toLowerCase()) &&
|
||||
t.name.toLowerCase().contains(q))
|
||||
t,
|
||||
];
|
||||
final exact = widget.catalog.any((t) => t.name.toLowerCase() == q);
|
||||
return AlertDialog(
|
||||
title: Text('Add ${widget.label}'),
|
||||
content: SizedBox(
|
||||
width: 360,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
TextField(
|
||||
key: ValueKey('${widget.label}-input'),
|
||||
controller: _text,
|
||||
autofocus: true,
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Search or type a new ${widget.label}',
|
||||
),
|
||||
onChanged: (_) => setState(() {}),
|
||||
onSubmitted: (_) {
|
||||
if (_query.isNotEmpty) Navigator.pop(context, _query);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Flexible(
|
||||
child: SingleChildScrollView(
|
||||
child: Wrap(
|
||||
spacing: 6,
|
||||
runSpacing: 6,
|
||||
children: [
|
||||
if (_query.isNotEmpty && !exact && !taken.contains(q))
|
||||
ActionChip(
|
||||
key: ValueKey('${widget.label}-create'),
|
||||
avatar: const Icon(Icons.add_rounded, size: 14),
|
||||
label: Text('Create "$_query"'),
|
||||
onPressed: () => Navigator.pop(context, _query),
|
||||
),
|
||||
for (final t in options)
|
||||
ActionChip(
|
||||
key: ValueKey('${widget.label}-opt-${t.name}'),
|
||||
label: Text(
|
||||
t.count > 0 ? '${t.name} · ${t.count}' : t.name,
|
||||
style: TextStyle(
|
||||
fontSize: 12.5,
|
||||
color: t.count > 0 ? colors.ink : colors.muted,
|
||||
),
|
||||
),
|
||||
onPressed: () => Navigator.pop(context, t.name),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user